|
- <?php
-
-
- namespace yii\base;
-
- use Yii;
- use ReflectionClass;
-
-
- class Widget extends Component implements ViewContextInterface
- {
-
-
- public static $counter = 0;
-
-
- public static $autoIdPrefix = 'w';
-
-
- public static $stack = [];
-
-
-
-
- public static function begin($config = [])
- {
- $config['class'] = get_called_class();
-
- $widget = Yii::createObject($config);
- static::$stack[] = $widget;
-
- return $widget;
- }
-
-
-
- public static function end()
- {
- if (!empty(static::$stack)) {
- $widget = array_pop(static::$stack);
- if (get_class($widget) === get_called_class()) {
- echo $widget->run();
- return $widget;
- } else {
- throw new InvalidCallException('Expecting end() of ' . get_class($widget) . ', found ' . get_called_class());
- }
- } else {
- throw new InvalidCallException('Unexpected ' . get_called_class() . '::end() call. A matching begin() is not found.');
- }
- }
-
-
-
- public static function widget($config = [])
- {
- ob_start();
- ob_implicit_flush(false);
- try {
-
- $config['class'] = get_called_class();
- $widget = Yii::createObject($config);
- $out = $widget->run();
- } catch (\Exception $e) {
-
- if (ob_get_level() > 0) {
- ob_end_clean();
- }
- throw $e;
- }
-
- return ob_get_clean() . $out;
- }
-
- private $_id;
-
-
-
- public function getId($autoGenerate = true)
- {
- if ($autoGenerate && $this->_id === null) {
- $this->_id = static::$autoIdPrefix . static::$counter++;
- }
-
- return $this->_id;
- }
-
-
-
- public function setId($value)
- {
- $this->_id = $value;
- }
-
- private $_view;
-
-
-
- public function getView()
- {
- if ($this->_view === null) {
- $this->_view = Yii::$app->getView();
- }
-
- return $this->_view;
- }
-
-
-
- public function setView($view)
- {
- $this->_view = $view;
- }
-
-
-
- public function run()
- {
- }
-
-
-
- public function render($view, $params = [])
- {
- return $this->getView()->render($view, $params, $this);
- }
-
-
-
- public function renderFile($file, $params = [])
- {
- return $this->getView()->renderFile($file, $params, $this);
- }
-
-
-
- public function getViewPath()
- {
- $class = new ReflectionClass($this);
-
- return dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views';
- }
- }
|