Widget.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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 Yii;
  9. use ReflectionClass;
  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. static::$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(static::$stack)) {
  96. $widget = array_pop(static::$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. } else {
  106. throw new InvalidCallException('Expecting end() of ' . get_class($widget) . ', found ' . get_called_class());
  107. }
  108. } else {
  109. throw new InvalidCallException('Unexpected ' . get_called_class() . '::end() call. A matching begin() is not found.');
  110. }
  111. }
  112. /**
  113. * Creates a widget instance and runs it.
  114. * The widget rendering result is returned by this method.
  115. * @param array $config name-value pairs that will be used to initialize the object properties
  116. * @return string the rendering result of the widget.
  117. * @throws \Exception
  118. */
  119. public static function widget($config = [])
  120. {
  121. ob_start();
  122. ob_implicit_flush(false);
  123. try {
  124. /* @var $widget Widget */
  125. $config['class'] = get_called_class();
  126. $widget = Yii::createObject($config);
  127. $out = '';
  128. if ($widget->beforeRun()) {
  129. $result = $widget->run();
  130. $out = $widget->afterRun($result);
  131. }
  132. } catch (\Exception $e) {
  133. // close the output buffer opened above if it has not been closed already
  134. if (ob_get_level() > 0) {
  135. ob_end_clean();
  136. }
  137. throw $e;
  138. }
  139. return ob_get_clean() . $out;
  140. }
  141. private $_id;
  142. /**
  143. * Returns the ID of the widget.
  144. * @param bool $autoGenerate whether to generate an ID if it is not set previously
  145. * @return string ID of the widget.
  146. */
  147. public function getId($autoGenerate = true)
  148. {
  149. if ($autoGenerate && $this->_id === null) {
  150. $this->_id = static::$autoIdPrefix . static::$counter++;
  151. }
  152. return $this->_id;
  153. }
  154. /**
  155. * Sets the ID of the widget.
  156. * @param string $value id of the widget.
  157. */
  158. public function setId($value)
  159. {
  160. $this->_id = $value;
  161. }
  162. private $_view;
  163. /**
  164. * Returns the view object that can be used to render views or view files.
  165. * The [[render()]] and [[renderFile()]] methods will use
  166. * this view object to implement the actual view rendering.
  167. * If not set, it will default to the "view" application component.
  168. * @return \yii\web\View the view object that can be used to render views or view files.
  169. */
  170. public function getView()
  171. {
  172. if ($this->_view === null) {
  173. $this->_view = Yii::$app->getView();
  174. }
  175. return $this->_view;
  176. }
  177. /**
  178. * Sets the view object to be used by this widget.
  179. * @param View $view the view object that can be used to render views or view files.
  180. */
  181. public function setView($view)
  182. {
  183. $this->_view = $view;
  184. }
  185. /**
  186. * Executes the widget.
  187. * @return string the result of widget execution to be outputted.
  188. */
  189. public function run()
  190. {
  191. }
  192. /**
  193. * Renders a view.
  194. * The view to be rendered can be specified in one of the following formats:
  195. *
  196. * - path alias (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 InvalidParamException 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.
  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 InvalidParamException 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. }