Completed
Push — 16753-fix-pjax ( 954723 )
by Alexander
13:41
created

Widget::widget()   A

Complexity

Conditions 4
Paths 12

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

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