Completed
Push — petrabarus-widget-event ( beac23 )
by Alexander
38:33
created

Widget::afterRun()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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