Widget.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\base;
  8. use ReflectionClass;
  9. use Yii;
  10. /**
  11. * Widget is the base class for widgets.
  12. *
  13. * For more details and usage information on Widget, see the [guide article on widgets](guide:structure-widgets).
  14. *
  15. * @property string $id ID of the widget.
  16. * @property \yii\web\View $view The view object that can be used to render views or view files. Note that the
  17. * type of this property differs in getter and setter. See [[getView()]] and [[setView()]] for details.
  18. * @property string $viewPath The directory containing the view files for this widget. This property is
  19. * read-only.
  20. *
  21. * @author Qiang Xue <qiang.xue@gmail.com>
  22. * @since 2.0
  23. */
  24. class Widget extends Component implements ViewContextInterface
  25. {
  26. /**
  27. * @event Event an event that is triggered when the widget is initialized via [[init()]].
  28. * @since 2.0.11
  29. */
  30. const EVENT_INIT = 'init';
  31. /**
  32. * @event WidgetEvent an event raised right before executing a widget.
  33. * You may set [[WidgetEvent::isValid]] to be false to cancel the widget execution.
  34. * @since 2.0.11
  35. */
  36. const EVENT_BEFORE_RUN = 'beforeRun';
  37. /**
  38. * @event WidgetEvent an event raised right after executing a widget.
  39. * @since 2.0.11
  40. */
  41. const EVENT_AFTER_RUN = 'afterRun';
  42. /**
  43. * @var int a counter used to generate [[id]] for widgets.
  44. * @internal
  45. */
  46. public static $counter = 0;
  47. /**
  48. * @var string the prefix to the automatically generated widget IDs.
  49. * @see getId()
  50. */
  51. public static $autoIdPrefix = 'w';
  52. /**
  53. * @var Widget[] the widgets that are currently being rendered (not ended). This property
  54. * is maintained by [[begin()]] and [[end()]] methods.
  55. * @internal
  56. */
  57. public static $stack = [];
  58. /**
  59. * Initializes the object.
  60. * This method is called at the end of the constructor.
  61. * The default implementation will trigger an [[EVENT_INIT]] event.
  62. */
  63. public function init()
  64. {
  65. parent::init();
  66. $this->trigger(self::EVENT_INIT);
  67. }
  68. /**
  69. * Begins a widget.
  70. * This method creates an instance of the calling class. It will apply the configuration
  71. * to the created instance. A matching [[end()]] call should be called later.
  72. * As some widgets may use output buffering, the [[end()]] call should be made in the same view
  73. * to avoid breaking the nesting of output buffers.
  74. * @param array $config name-value pairs that will be used to initialize the object properties
  75. * @return static the newly created widget instance
  76. * @see end()
  77. */
  78. public static function begin($config = [])
  79. {
  80. $config['class'] = get_called_class();
  81. /* @var $widget Widget */
  82. $widget = Yii::createObject($config);
  83. self::$stack[] = $widget;
  84. return $widget;
  85. }
  86. /**
  87. * Ends a widget.
  88. * Note that the rendering result of the widget is directly echoed out.
  89. * @return static the widget instance that is ended.
  90. * @throws InvalidCallException if [[begin()]] and [[end()]] calls are not properly nested
  91. * @see begin()
  92. */
  93. public static function end()
  94. {
  95. if (!empty(self::$stack)) {
  96. $widget = array_pop(self::$stack);
  97. if (get_class($widget) === get_called_class()) {
  98. /* @var $widget Widget */
  99. if ($widget->beforeRun()) {
  100. $result = $widget->run();
  101. $result = $widget->afterRun($result);
  102. echo $result;
  103. }
  104. return $widget;
  105. }
  106. throw new InvalidCallException('Expecting end() of ' . get_class($widget) . ', found ' . get_called_class());
  107. }
  108. throw new InvalidCallException('Unexpected ' . get_called_class() . '::end() call. A matching begin() is not found.');
  109. }
  110. /**
  111. * Creates a widget instance and runs it.
  112. * The widget rendering result is returned by this method.
  113. * @param array $config name-value pairs that will be used to initialize the object properties
  114. * @return string the rendering result of the widget.
  115. * @throws \Exception
  116. */
  117. public static function widget($config = [])
  118. {
  119. ob_start();
  120. ob_implicit_flush(false);
  121. try {
  122. /* @var $widget Widget */
  123. $config['class'] = get_called_class();
  124. $widget = Yii::createObject($config);
  125. $out = '';
  126. if ($widget->beforeRun()) {
  127. $result = $widget->run();
  128. $out = $widget->afterRun($result);
  129. }
  130. } catch (\Exception $e) {
  131. // close the output buffer opened above if it has not been closed already
  132. if (ob_get_level() > 0) {
  133. ob_end_clean();
  134. }
  135. throw $e;
  136. }
  137. return ob_get_clean() . $out;
  138. }
  139. private $_id;
  140. /**
  141. * Returns the ID of the widget.
  142. * @param bool $autoGenerate whether to generate an ID if it is not set previously
  143. * @return string ID of the widget.
  144. */
  145. public function getId($autoGenerate = true)
  146. {
  147. if ($autoGenerate && $this->_id === null) {
  148. $this->_id = static::$autoIdPrefix . static::$counter++;
  149. }
  150. return $this->_id;
  151. }
  152. /**
  153. * Sets the ID of the widget.
  154. * @param string $value id of the widget.
  155. */
  156. public function setId($value)
  157. {
  158. $this->_id = $value;
  159. }
  160. private $_view;
  161. /**
  162. * Returns the view object that can be used to render views or view files.
  163. * The [[render()]] and [[renderFile()]] methods will use
  164. * this view object to implement the actual view rendering.
  165. * If not set, it will default to the "view" application component.
  166. * @return \yii\web\View the view object that can be used to render views or view files.
  167. */
  168. public function getView()
  169. {
  170. if ($this->_view === null) {
  171. $this->_view = Yii::$app->getView();
  172. }
  173. return $this->_view;
  174. }
  175. /**
  176. * Sets the view object to be used by this widget.
  177. * @param View $view the view object that can be used to render views or view files.
  178. */
  179. public function setView($view)
  180. {
  181. $this->_view = $view;
  182. }
  183. /**
  184. * Executes the widget.
  185. * @return string the result of widget execution to be outputted.
  186. */
  187. public function run()
  188. {
  189. }
  190. /**
  191. * Renders a view.
  192. *
  193. * The view to be rendered can be specified in one of the following formats:
  194. *
  195. * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
  196. * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
  197. * The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
  198. * - absolute path within module (e.g. "/site/index"): the view name starts with a single slash.
  199. * The actual view file will be looked for under the [[Module::viewPath|view path]] of the currently
  200. * active module.
  201. * - relative path (e.g. "index"): the actual view file will be looked for under [[viewPath]].
  202. *
  203. * If the view name does not contain a file extension, it will use the default one `.php`.
  204. *
  205. * @param string $view the view name.
  206. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  207. * @return string the rendering result.
  208. * @throws InvalidArgumentException if the view file does not exist.
  209. */
  210. public function render($view, $params = [])
  211. {
  212. return $this->getView()->render($view, $params, $this);
  213. }
  214. /**
  215. * Renders a view file.
  216. * @param string $file the view file to be rendered. This can be either a file path or a [path alias](guide:concept-aliases).
  217. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  218. * @return string the rendering result.
  219. * @throws InvalidArgumentException if the view file does not exist.
  220. */
  221. public function renderFile($file, $params = [])
  222. {
  223. return $this->getView()->renderFile($file, $params, $this);
  224. }
  225. /**
  226. * Returns the directory containing the view files for this widget.
  227. * The default implementation returns the 'views' subdirectory under the directory containing the widget class file.
  228. * @return string the directory containing the view files for this widget.
  229. */
  230. public function getViewPath()
  231. {
  232. $class = new ReflectionClass($this);
  233. return dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views';
  234. }
  235. /**
  236. * This method is invoked right before the widget is executed.
  237. *
  238. * The method will trigger the [[EVENT_BEFORE_RUN]] event. The return value of the method
  239. * will determine whether the widget should continue to run.
  240. *
  241. * When overriding this method, make sure you call the parent implementation like the following:
  242. *
  243. * ```php
  244. * public function beforeRun()
  245. * {
  246. * if (!parent::beforeRun()) {
  247. * return false;
  248. * }
  249. *
  250. * // your custom code here
  251. *
  252. * return true; // or false to not run the widget
  253. * }
  254. * ```
  255. *
  256. * @return bool whether the widget should continue to be executed.
  257. * @since 2.0.11
  258. */
  259. public function beforeRun()
  260. {
  261. $event = new WidgetEvent();
  262. $this->trigger(self::EVENT_BEFORE_RUN, $event);
  263. return $event->isValid;
  264. }
  265. /**
  266. * This method is invoked right after a widget is executed.
  267. *
  268. * The method will trigger the [[EVENT_AFTER_RUN]] event. The return value of the method
  269. * will be used as the widget return value.
  270. *
  271. * If you override this method, your code should look like the following:
  272. *
  273. * ```php
  274. * public function afterRun($result)
  275. * {
  276. * $result = parent::afterRun($result);
  277. * // your custom code here
  278. * return $result;
  279. * }
  280. * ```
  281. *
  282. * @param mixed $result the widget return result.
  283. * @return mixed the processed widget result.
  284. * @since 2.0.11
  285. */
  286. public function afterRun($result)
  287. {
  288. $event = new WidgetEvent();
  289. $event->result = $result;
  290. $this->trigger(self::EVENT_AFTER_RUN, $event);
  291. return $event->result;
  292. }
  293. }