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