Widget.php 11 KB

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