Completed
Push — master ( bd59d8...c19b2f )
by Carsten
15:27 queued 05:18
created

Widget::end()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.074

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 10
cts 12
cp 0.8333
rs 9.2
c 0
b 0
f 0
cc 4
eloc 13
nc 4
nop 0
crap 4.074
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 Yii;
11
use ReflectionClass;
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 23
    public function init()
70
    {
71 23
        parent::init();
72 23
        $this->trigger(self::EVENT_INIT);
73 23
    }
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 35
    public static function begin($config = [])
86
    {
87 35
        $config['class'] = get_called_class();
88
        /* @var $widget Widget */
89 35
        $widget = Yii::createObject($config);
90 35
        static::$stack[] = $widget;
91
92 35
        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 35
    public static function end()
103
    {
104 35
        if (!empty(static::$stack)) {
105 35
            $widget = array_pop(static::$stack);
106 35
            if (get_class($widget) === get_called_class()) {
107
                /* @var $widget Widget */
108 35
                if ($widget->beforeRun()) {
109 35
                    $result = $widget->run();
110 35
                    $result = $widget->afterRun($result);
111 35
                    echo $result;
112 35
                }
113 35
                return $widget;
114
            } else {
115
                throw new InvalidCallException('Expecting end() of ' . get_class($widget) . ', found ' . get_called_class());
116
            }
117
        } else {
118
            throw new InvalidCallException('Unexpected ' . get_called_class() . '::end() call. A matching begin() is not found.');
119
        }
120
    }
121
122
    /**
123
     * Creates a widget instance and runs it.
124
     * The widget rendering result is returned by this method.
125
     * @param array $config name-value pairs that will be used to initialize the object properties
126
     * @return string the rendering result of the widget.
127
     * @throws \Exception
128
     */
129 20
    public static function widget($config = [])
130
    {
131 20
        ob_start();
132 20
        ob_implicit_flush(false);
133
        try {
134
            /* @var $widget Widget */
135 20
            $config['class'] = get_called_class();
136 20
            $widget = Yii::createObject($config);
137 20
            $out = '';
138 20
            if ($widget->beforeRun()) {
139 20
                $result = $widget->run();
140 20
                $out = $widget->afterRun($result);
141 20
            }
142 20
        } catch (\Exception $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
150 20
        return ob_get_clean() . $out;
151
    }
152
153
    private $_id;
154
155
    /**
156
     * Returns the ID of the widget.
157
     * @param bool $autoGenerate whether to generate an ID if it is not set previously
158
     * @return string ID of the widget.
159
     */
160 61
    public function getId($autoGenerate = true)
161
    {
162 61
        if ($autoGenerate && $this->_id === null) {
163 48
            $this->_id = static::$autoIdPrefix . static::$counter++;
164 48
        }
165
166 61
        return $this->_id;
167
    }
168
169
    /**
170
     * Sets the ID of the widget.
171
     * @param string $value id of the widget.
172
     */
173 14
    public function setId($value)
174
    {
175 14
        $this->_id = $value;
176 14
    }
177
178 1
    private $_view;
179
180
    /**
181
     * Returns the view object that can be used to render views or view files.
182
     * The [[render()]] and [[renderFile()]] methods will use
183
     * this view object to implement the actual view rendering.
184
     * If not set, it will default to the "view" application component.
185
     * @return \yii\web\View the view object that can be used to render views or view files.
186
     */
187 19
    public function getView()
188
    {
189 19
        if ($this->_view === null) {
190 13
            $this->_view = Yii::$app->getView();
191 13
        }
192
193 19
        return $this->_view;
194
    }
195
196
    /**
197
     * Sets the view object to be used by this widget.
198
     * @param View $view the view object that can be used to render views or view files.
199
     */
200 42
    public function setView($view)
201
    {
202 42
        $this->_view = $view;
203 42
    }
204
205
    /**
206
     * Executes the widget.
207
     * @return string the result of widget execution to be outputted.
208
     */
209
    public function run()
210
    {
211
    }
212
213
    /**
214
     * Renders a view.
215
     * The view to be rendered can be specified in one of the following formats:
216
     *
217
     * - path alias (e.g. "@app/views/site/index");
218
     * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
219
     *   The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
220
     * - absolute path within module (e.g. "/site/index"): the view name starts with a single slash.
221
     *   The actual view file will be looked for under the [[Module::viewPath|view path]] of the currently
222
     *   active module.
223
     * - relative path (e.g. "index"): the actual view file will be looked for under [[viewPath]].
224
     *
225
     * If the view name does not contain a file extension, it will use the default one `.php`.
226
     *
227
     * @param string $view the view name.
228
     * @param array $params the parameters (name-value pairs) that should be made available in the view.
229
     * @return string the rendering result.
230
     * @throws InvalidParamException if the view file does not exist.
231
     */
232
    public function render($view, $params = [])
233
    {
234
        return $this->getView()->render($view, $params, $this);
235
    }
236
237
    /**
238
     * Renders a view file.
239
     * @param string $file the view file to be rendered. This can be either a file path or a path alias.
240
     * @param array $params the parameters (name-value pairs) that should be made available in the view.
241
     * @return string the rendering result.
242
     * @throws InvalidParamException if the view file does not exist.
243
     */
244
    public function renderFile($file, $params = [])
245
    {
246
        return $this->getView()->renderFile($file, $params, $this);
247
    }
248
249
    /**
250
     * Returns the directory containing the view files for this widget.
251
     * The default implementation returns the 'views' subdirectory under the directory containing the widget class file.
252
     * @return string the directory containing the view files for this widget.
253
     */
254
    public function getViewPath()
255
    {
256
        $class = new ReflectionClass($this);
257
258
        return dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views';
259
    }
260
    
261
    /**
262
     * This method is invoked right before the widget is executed.
263
     *
264
     * The method will trigger the [[EVENT_BEFORE_RUN]] event. The return value of the method
265
     * will determine whether the widget should continue to run.
266
     *
267
     * When overriding this method, make sure you call the parent implementation like the following:
268
     *
269
     * ```php
270
     * public function beforeRun()
271
     * {
272
     *     if (!parent::beforeRun()) {
273
     *         return false;
274
     *     }
275
     *
276
     *     // your custom code here
277
     *
278
     *     return true; // or false to not run the widget
279
     * }
280
     * ```
281
     *
282
     * @return bool whether the widget should continue to be executed.
283
     * @since 2.0.11
284
     */
285 54
    public function beforeRun()
286
    {
287 54
        $event = new WidgetEvent();
288 54
        $this->trigger(self::EVENT_BEFORE_RUN, $event);
289 54
        return $event->isValid;
290
    }
291
292
    /**
293
     * This method is invoked right after a widget is executed.
294
     *
295
     * The method will trigger the [[EVENT_AFTER_RUN]] event. The return value of the method
296
     * will be used as the widget return value.
297
     *
298
     * If you override this method, your code should look like the following:
299
     *
300
     * ```php
301
     * public function afterRun($result)
302
     * {
303
     *     $result = parent::afterRun($result);
304
     *     // your custom code here
305
     *     return $result;
306
     * }
307
     * ```
308
     *
309
     * @param mixed $result the widget return result.
310
     * @return mixed the processed widget result.
311
     * @since 2.0.11
312
     */
313 54
    public function afterRun($result)
314
    {
315 54
        $event = new WidgetEvent();
316 54
        $event->result = $result;
317 54
        $this->trigger(self::EVENT_AFTER_RUN, $event);
318 54
        return $event->result;
319
    }
320
}
321