Yii2 framework backup
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

323 lines
10 KiB

13 years ago
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
13 years ago
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
use ReflectionClass;
Added php-cs-fixer coding standards validation to Travis CI (#14100) * php-cs-fixer: PSR2 rule. * php-cs-fixer: PSR2 rule - fix views. * Travis setup refactoring. * Add php-cs-fixer to travis cs tests. * Fix tests on hhvm-3.12 * improve travis config * composer update * revert composer update * improve travis config * Fix CS. * Extract config to separate classes. * Extract config to separate classes. * Add file header. * Force short array syntax. * binary_operator_spaces fixer * Fix broken tests * cast_spaces fixer * concat_space fixer * dir_constant fixer * ereg_to_preg fixer * function_typehint_space fixer * hash_to_slash_comment fixer * is_null fixer * linebreak_after_opening_tag fixer * lowercase_cast fixer * magic_constant_casing fixer * modernize_types_casting fixer * native_function_casing fixer * new_with_braces fixer * no_alias_functions fixer * no_blank_lines_after_class_opening fixer * no_blank_lines_after_phpdoc fixer * no_empty_comment fixer * no_empty_phpdoc fixer * no_empty_statement fixer * no_extra_consecutive_blank_lines fixer * no_leading_import_slash fixer * no_leading_namespace_whitespace fixer * no_mixed_echo_print fixer * no_multiline_whitespace_around_double_arrow fixer * no_multiline_whitespace_before_semicolons fixer * no_php4_constructor fixer * no_short_bool_cast fixer * no_singleline_whitespace_before_semicolons fixer * no_spaces_around_offset fixer * no_trailing_comma_in_list_call fixer * no_trailing_comma_in_singleline_array fixer * no_unneeded_control_parentheses fixer * no_unused_imports fixer * no_useless_return fixer * no_whitespace_before_comma_in_array fixer * no_whitespace_in_blank_line fixer * not_operator_with_successor_space fixer * object_operator_without_whitespace fixer * ordered_imports fixer * php_unit_construct fixer * php_unit_dedicate_assert fixer * php_unit_fqcn_annotation fixer * phpdoc_indent fixer * phpdoc_no_access fixer * phpdoc_no_empty_return fixer * phpdoc_no_package fixer * phpdoc_no_useless_inheritdoc fixer * Fix broken tests * phpdoc_return_self_reference fixer * phpdoc_single_line_var_spacing fixer * phpdoc_single_line_var_spacing fixer * phpdoc_to_comment fixer * phpdoc_trim fixer * phpdoc_var_without_name fixer * psr4 fixer * self_accessor fixer * short_scalar_cast fixer * single_blank_line_before_namespace fixer * single_quote fixer * standardize_not_equals fixer * ternary_operator_spaces fixer * trailing_comma_in_multiline_array fixer * trim_array_spaces fixer * protected_to_private fixer * unary_operator_spaces fixer * whitespace_after_comma_in_array fixer * `parent::setRules()` -> `$this->setRules()` * blank_line_after_opening_tag fixer * Update finder config. * Revert changes for YiiRequirementChecker. * Fix array formatting. * Add missing import. * Fix CS for new code merged from master. * Fix some indentation issues.
7 years ago
use Yii;
12 years ago
13 years ago
/**
* Widget is the base class for widgets.
*
* For more details and usage information on Widget, see the [guide article on widgets](guide:structure-widgets).
*
* @property string $id ID of the widget.
11 years ago
* @property \yii\web\View $view The view object that can be used to render views or view files. Note that the
* type of this property differs in getter and setter. See [[getView()]] and [[setView()]] for details.
* @property string $viewPath The directory containing the view files for this widget. This property is
* read-only.
*
13 years ago
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Widget extends Component implements ViewContextInterface
13 years ago
{
/**
* @event Event an event that is triggered when the widget is initialized via [[init()]].
* @since 2.0.11
*/
const EVENT_INIT = 'init';
/**
* @event WidgetEvent an event raised right before executing a widget.
* You may set [[WidgetEvent::isValid]] to be false to cancel the widget execution.
* @since 2.0.11
*/
const EVENT_BEFORE_RUN = 'beforeRun';
/**
* @event WidgetEvent an event raised right after executing a widget.
* @since 2.0.11
*/
const EVENT_AFTER_RUN = 'afterRun';
/**
* @var int a counter used to generate [[id]] for widgets.
* @internal
*/
public static $counter = 0;
/**
* @var string the prefix to the automatically generated widget IDs.
* @see getId()
*/
public static $autoIdPrefix = 'w';
/**
* @var Widget[] the widgets that are currently being rendered (not ended). This property
* is maintained by [[begin()]] and [[end()]] methods.
* @internal
*/
public static $stack = [];
/**
* Initializes the object.
* This method is called at the end of the constructor.
* The default implementation will trigger an [[EVENT_INIT]] event.
*/
public function init()
{
parent::init();
$this->trigger(self::EVENT_INIT);
}
/**
* Begins a widget.
* This method creates an instance of the calling class. It will apply the configuration
* to the created instance. A matching [[end()]] call should be called later.
* As some widgets may use output buffering, the [[end()]] call should be made in the same view
* to avoid breaking the nesting of output buffers.
* @param array $config name-value pairs that will be used to initialize the object properties
* @return static the newly created widget instance
* @see end()
*/
public static function begin($config = [])
{
$config['class'] = get_called_class();
/* @var $widget Widget */
$widget = Yii::createObject($config);
self::$stack[] = $widget;
return $widget;
}
/**
* Ends a widget.
* Note that the rendering result of the widget is directly echoed out.
* @return static the widget instance that is ended.
* @throws InvalidCallException if [[begin()]] and [[end()]] calls are not properly nested
* @see begin()
*/
public static function end()
{
if (!empty(self::$stack)) {
$widget = array_pop(self::$stack);
if (get_class($widget) === get_called_class()) {
/* @var $widget Widget */
if ($widget->beforeRun()) {
$result = $widget->run();
$result = $widget->afterRun($result);
echo $result;
}
return $widget;
}
throw new InvalidCallException('Expecting end() of ' . get_class($widget) . ', found ' . get_called_class());
}
throw new InvalidCallException('Unexpected ' . get_called_class() . '::end() call. A matching begin() is not found.');
}
/**
* Creates a widget instance and runs it.
* The widget rendering result is returned by this method.
* @param array $config name-value pairs that will be used to initialize the object properties
* @return string the rendering result of the widget.
* @throws \Exception
*/
public static function widget($config = [])
{
ob_start();
ob_implicit_flush(false);
try {
/* @var $widget Widget */
$config['class'] = get_called_class();
$widget = Yii::createObject($config);
$out = '';
if ($widget->beforeRun()) {
$result = $widget->run();
$out = $widget->afterRun($result);
}
} catch (\Exception $e) {
// close the output buffer opened above if it has not been closed already
if (ob_get_level() > 0) {
ob_end_clean();
}
throw $e;
}
return ob_get_clean() . $out;
}
private $_id;
/**
* Returns the ID of the widget.
* @param bool $autoGenerate whether to generate an ID if it is not set previously
* @return string ID of the widget.
*/
public function getId($autoGenerate = true)
{
if ($autoGenerate && $this->_id === null) {
$this->_id = static::$autoIdPrefix . static::$counter++;
}
return $this->_id;
}
/**
* Sets the ID of the widget.
* @param string $value id of the widget.
*/
public function setId($value)
{
$this->_id = $value;
}
private $_view;
/**
* Returns the view object that can be used to render views or view files.
* The [[render()]] and [[renderFile()]] methods will use
* this view object to implement the actual view rendering.
* If not set, it will default to the "view" application component.
* @return \yii\web\View the view object that can be used to render views or view files.
*/
public function getView()
{
if ($this->_view === null) {
$this->_view = Yii::$app->getView();
}
return $this->_view;
}
/**
* Sets the view object to be used by this widget.
* @param View $view the view object that can be used to render views or view files.
*/
public function setView($view)
{
$this->_view = $view;
}
/**
* Executes the widget.
* @return string the result of widget execution to be outputted.
*/
public function run()
{
}
/**
* Renders a view.
*
* The view to be rendered can be specified in one of the following formats:
*
* - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
* - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
* The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
* - absolute path within module (e.g. "/site/index"): the view name starts with a single slash.
* The actual view file will be looked for under the [[Module::viewPath|view path]] of the currently
* active module.
* - relative path (e.g. "index"): the actual view file will be looked for under [[viewPath]].
*
* If the view name does not contain a file extension, it will use the default one `.php`.
*
* @param string $view the view name.
* @param array $params the parameters (name-value pairs) that should be made available in the view.
* @return string the rendering result.
* @throws InvalidArgumentException if the view file does not exist.
*/
public function render($view, $params = [])
{
return $this->getView()->render($view, $params, $this);
}
/**
* Renders a view file.
* @param string $file the view file to be rendered. This can be either a file path or a [path alias](guide:concept-aliases).
* @param array $params the parameters (name-value pairs) that should be made available in the view.
* @return string the rendering result.
* @throws InvalidArgumentException if the view file does not exist.
*/
public function renderFile($file, $params = [])
{
return $this->getView()->renderFile($file, $params, $this);
}
/**
* Returns the directory containing the view files for this widget.
* The default implementation returns the 'views' subdirectory under the directory containing the widget class file.
* @return string the directory containing the view files for this widget.
*/
public function getViewPath()
{
$class = new ReflectionClass($this);
return dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views';
}
/**
* This method is invoked right before the widget is executed.
*
* The method will trigger the [[EVENT_BEFORE_RUN]] event. The return value of the method
* will determine whether the widget should continue to run.
*
* When overriding this method, make sure you call the parent implementation like the following:
*
* ```php
* public function beforeRun()
* {
* if (!parent::beforeRun()) {
* return false;
* }
*
* // your custom code here
*
* return true; // or false to not run the widget
* }
* ```
*
* @return bool whether the widget should continue to be executed.
* @since 2.0.11
*/
public function beforeRun()
{
$event = new WidgetEvent();
$this->trigger(self::EVENT_BEFORE_RUN, $event);
return $event->isValid;
}
/**
* This method is invoked right after a widget is executed.
*
* The method will trigger the [[EVENT_AFTER_RUN]] event. The return value of the method
* will be used as the widget return value.
*
* If you override this method, your code should look like the following:
*
* ```php
* public function afterRun($result)
* {
* $result = parent::afterRun($result);
* // your custom code here
* return $result;
* }
* ```
*
* @param mixed $result the widget return result.
* @return mixed the processed widget result.
* @since 2.0.11
*/
public function afterRun($result)
{
$event = new WidgetEvent();
$event->result = $result;
$this->trigger(self::EVENT_AFTER_RUN, $event);
return $event->result;
}
}