Passed
Pull Request — master (#20270)
by
unknown
08:31
created

Widget::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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