把杯子里面的水清空,从零开始学习编程。第五节 yii/base/Component.php

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

use Yii;
use yii\helpers\StringHelper;

/**
 * 该类为  property event behavior 的基类
 *
 * 该组件给 event 和 behavior 的特性 , 以及实现于 在父类中的 property 特性的
 *
 * 事件是一种将自定义的代码 "注入" 到特定的位置的现有代码的方法 。 例如,注释对象可以触发
 * 用户添加评论时的“添加”事件。我们可以编写自定义代码并将其附加到此事件,以便当事件发生时
 * 是触发(即注释将被添加),我们的自定义代码将被执行。
 *
 * 事件由一个名称标识,该名称在其定义的类中应该是唯一的。事件名是*区分大小写的*。
 *
 * 一个或多个PHP回调,称为*事件处理程序*,可以附加到一个事件。您可以调用 trigger() to
 * 引发事件。当引发事件时,将按事件处理程序的顺序自动调用事件处理程序
 *
 * 要将事件处理程序附加到事件,调用 on() :
 *
 * ```php
 * $post->on('update', function ($event) {
 *     // send email notification
 * });
 * ```
 *
 * 在上面,一个匿名函数被附加到post的“update”事件。你可以附加以下类型的事件处理程序:
 *
 * - 匿名函数:`function ($event){…}'
 * - 对象方法:' [$object, 'handleAdd'] '
 * - 静态类方法:' ['Page', 'handleAdd'] '
 * - 全局函数:“handleAdd '
 *
 * 事件处理程序的签名应该如下:
 *
 * ```php
 * function foo($event)
 * ```
 *
 * 其中' $event '是一个[[event]]对象,它包含与事件相关的参数。
 *
 * 在使用配置数组配置组件时,还可以将处理程序附加到事件。语法如下:
 *
 * ```php
 * [
 *     'on add' => function ($event) { ... }
 * ]
 * ```
 *
 * 其中' on add '表示将事件附加到' add '事件。
 *
 * 有时,您可能希望在将额外数据附加到事件时将其与事件处理程序关联起来然后在调用处理程序时访问它。你可以这样做
 *
 * ```php
 * $post->on('update', function ($event) {
 *     // the data can be accessed via $event->data
 * }, $data);
 * ```
 *
 * 一个行为是 behavior 或者是它的一个子类的一个实例。组件可以附加一个或多个行为。
 * 当行为被附加到组件时,可以通过组件直接访问其公共属性和方法,就好像组件拥有这些属性和方法一样。
 *
 * 要将行为附加到组件,请在 behaviors() 中声明 ,或者显示的调用 attachBehavior 。行为 在 behaviors() 中声明的自动附加到相应的组件
 *
 * 在用配置数组配置组件时,还可以将行为附加到组件。语法如下:
 *
 * ```php
 * [
 *     'as tree' => [
 *         'class' => 'Tree',
 *     ],
 * ]
 * ```
 *
 * 其中 as tree 表示附加一个名为tree 的行为 ,数组将被传递给 \Yii::createObject() 创建对应的对象
 *
 * 有关组件的详细信息和使用信息,请参阅[关于组件的指导文章](guide:concept-components).
 *
 * @property Behavior[] $behaviors 附加到此组件的行为列表。此属性是只读的。
 *
 * @author Qiang Xue <[email protected]>
 * @since 2.0
 */
class Component extends BaseObject
{
    /**
     * @var array 附加的事件处理程序 (事件名称=>处理程序)
     */
    private $_events = [];
    /**
     * @var array 为通配符模式附加的事件处理程序(事件名通配符=>处理程序)
     * @since 2.0.14
     */
    private $_eventWildcards = [];
    /**
     * @var Behavior[]|null 附加的行为(行为名=>行为)。这是' null '时,没有初始化。
     */
    private $_behaviors;


    /**
     * 返回组件属性的值。
     *
     * 该方法将按照以下顺序进行检查并采取相应的行动:
     *
     *  - 由getter定义的属性:返回getter结果
     *  - 行为的属性:返回行为属性值
     *
     * Do not call this method directly as it is a PHP magic method that
     * will be implicitly called when executing `$value = $component->property;`.
     * @param string $name the property name
     * @return mixed the property value or the value of a behavior's property
     * @throws UnknownPropertyException if the property is not defined
     * @throws InvalidCallException if the property is write-only.
     * @see __set()
     */
    public function __get($name)
    {
        $getter = 'get' . $name;
        if (method_exists($this, $getter)) {
            // read property, e.g. getName()
            return $this->$getter();
        }

        // behavior property
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canGetProperty($name)) {
                return $behavior->$name;
            }
        }

        if (method_exists($this, 'set' . $name)) {
            throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
        }

        throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
    }

    /**
     * 设置组件属性的值。
     *
     * 该方法将按照以下顺序进行检查并采取相应的行动:
     *
     *  - 由setter定义的属性:设置属性值
     *  - “on xyz”格式的事件:将处理程序附加到事件“xyz”
     *  - “作为xyz”格式的行为:附加名为“xyz”的行为
     *  - 行为的属性:设置行为属性值
     *
     * Do not call this method directly as it is a PHP magic method that
     * will be implicitly called when executing `$component->property = $value;`.
     * @param string $name the property name or the event name
     * @param mixed $value the property value
     * @throws UnknownPropertyException if the property is not defined
     * @throws InvalidCallException if the property is read-only.
     * @see __get()
     */
    public function __set($name, $value)
    {
        $setter = 'set' . $name;
        if (method_exists($this, $setter)) {
            // set property
            $this->$setter($value);

            return;
        } elseif (strncmp($name, 'on ', 3) === 0) {
            // on event: attach event handler
            $this->on(trim(substr($name, 3)), $value);

            return;
        } elseif (strncmp($name, 'as ', 3) === 0) {
            // as behavior: attach behavior
            $name = trim(substr($name, 3));
            $this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));

            return;
        }

        // behavior property
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canSetProperty($name)) {
                $behavior->$name = $value;
                return;
            }
        }

        if (method_exists($this, 'get' . $name)) {
            throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
        }

        throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
    }

    /**
     * 检查属性是否已设置,即是否已定义,是否不为空。
     *
     * 该方法将按照以下顺序进行检查并采取相应的行动:
     *
     *  - 由setter定义的属性:返回是否设置该属性
     *  - 行为的属性:返回属性是否设置
     *  - 对于不存在的属性返回“false”
     *
     * Do not call this method directly as it is a PHP magic method that
     * will be implicitly called when executing `isset($component->property)`.
     * @param string $name the property name or the event name
     * @return bool whether the named property is set
     * @see https://secure.php.net/manual/en/function.isset.php
     */
    public function __isset($name)
    {
        $getter = 'get' . $name;
        if (method_exists($this, $getter)) {
            return $this->$getter() !== null;
        }

        // behavior property
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canGetProperty($name)) {
                return $behavior->$name !== null;
            }
        }

        return false;
    }

    /**
     * 将组件属性设置为null。
     *
     * 该方法将按照以下顺序进行检查并采取相应的行动:
     *
     *  - 由setter定义的属性:将属性值设置为null
     *  - 行为的属性:将属性值设置为null
     *
     * Do not call this method directly as it is a PHP magic method that
     * will be implicitly called when executing `unset($component->property)`.
     * @param string $name the property name
     * @throws InvalidCallException if the property is read only.
     * @see https://secure.php.net/manual/en/function.unset.php
     */
    public function __unset($name)
    {
        $setter = 'set' . $name;
        if (method_exists($this, $setter)) {
            $this->$setter(null);
            return;
        }

        // behavior property
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canSetProperty($name)) {
                $behavior->$name = null;
                return;
            }
        }

        throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
    }

    /**
     * 调用命名的方法,而不是类方法。
     *
     * 此方法将检查是否有任何附加的行为
     * 命名的方法,如果可用,将执行它。
     *
     * Do not call this method directly as it is a PHP magic method that
     * will be implicitly called when an unknown method is being invoked.
     * @param string $name the method name
     * @param array $params method parameters
     * @return mixed the method return value
     * @throws UnknownMethodException when calling unknown method
     */
    public function __call($name, $params)
    {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $object) {
            if ($object->hasMethod($name)) {
                return call_user_func_array([$object, $name], $params);
            }
        }
        throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
    }

    /**
     * 此方法在通过克隆现有对象创建对象之后调用。
     * 它删除了所有行为,因为它们被附加到旧对象上。
     */
    public function __clone()
    {
        $this->_events = [];
        $this->_eventWildcards = [];
        $this->_behaviors = null;
    }

    /**
     * 返回一个值,该值指示是否为该组件定义属性。
     *
     * 属性定义如下:
     *
     * - 该类具有与指定名称相关联的getter或setter方法(在本例中,属性名不区分大小写);
     * - 该类有一个具有指定名称的成员变量(当' $checkVars '为真时);
     * - 附加行为具有给定名称的属性(当' $ checkbehavior '为真时)。
     *
     * @param string $name the property name
     * @param bool $checkVars whether to treat member variables as properties
     * @param bool $checkBehaviors whether to treat behaviors' properties as properties of this component
     * @return bool whether the property is defined
     * @see canGetProperty()
     * @see canSetProperty()
     */
    public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
    {
        return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
    }

    /**
     * 返回一个值,该值指示是否可以读取属性。
     *
     * 属性可以在以下情况下读取:
     *
     * - 该类具有与指定名称相关联的getter方法(在本例中,属性名不区分大小写);
     * - 该类有一个具有指定名称的成员变量(当' $checkVars '为真时);
     * - 附加行为具有给定名称的可读属性(当“$ checkbehavior”为真时)。
     *
     * @param string $name the property name
     * @param bool $checkVars 是否将成员变量视为属性
     * @param bool $checkBehaviors whether to treat behaviors' properties as properties of this component
     * @return bool whether the property can be read
     * @see canSetProperty()
     */
    public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
    {
        if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
            return true;
        } elseif ($checkBehaviors) {
            $this->ensureBehaviors();
            foreach ($this->_behaviors as $behavior) {
                if ($behavior->canGetProperty($name, $checkVars)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 返回一个值,该值指示是否可以设置属性。
     *
     * 在下列情况下,可以写入属性:
     *
     * - 该类具有与指定名称关联的setter方法(在本例中,属性名不区分大小写);
     * - 该类有一个具有指定名称的成员变量(当' $checkVars '为真时);
     * - 附加行为具有给定名称的可写属性(当' $ checkbehavior '为真时)。
     *
     * @param string $name the property name
     * @param bool $checkVars whether to treat member variables as properties
     * @param bool $checkBehaviors whether to treat behaviors' properties as properties of this component
     * @return bool whether the property can be written
     * @see canGetProperty()
     */
    public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
    {
        if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
            return true;
        } elseif ($checkBehaviors) {
            $this->ensureBehaviors();
            foreach ($this->_behaviors as $behavior) {
                if ($behavior->canSetProperty($name, $checkVars)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 返回一个值,该值指示是否定义了一个方法。
     *
     * 定义一个方法,如果:
     *
     * - 该类有一个具有指定名称的方法
     * - 附加行为有一个具有给定名称的方法(当' $ checkbehavior '为真时)。
     *
     * @param string $name the property name
     * @param bool $checkBehaviors whether to treat behaviors' methods as methods of this component
     * @return bool whether the method is defined
     */
    public function hasMethod($name, $checkBehaviors = true)
    {
        if (method_exists($this, $name)) {
            return true;
        } elseif ($checkBehaviors) {
            $this->ensureBehaviors();
            foreach ($this->_behaviors as $behavior) {
                if ($behavior->hasMethod($name)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 返回此组件应作为行为的行为列表。
     *
     * 子类可以重写此方法,以指定它们想要作为的行为。
     *
     * 此方法的返回值应该是一个行为对象数组或按行为名索引的配置数组。
     * 行为配置可以是指定行为类的字符串,也可以是以下结构的数组:
     *
     * ```php
     * 'behaviorName' => [
     *     'class' => 'BehaviorClass',
     *     'property1' => 'value1',
     *     'property2' => 'value2',
     * ]
     * ```
     *
     * 请注意,行为类必须从 behavior 扩展而来。可以使用名称或匿名方式附加行为。
     * 当使用名称作为数组键时,使用这个名称,以后可以使用 getBehavior() 检索行为,
     * 或者使用detachBehavior()分离行为。无法检索或分离匿名行为。
     *
     * Behaviors declared in this method will be attached to the component automatically (on demand).
     *
     * @return array the behavior configurations.
     */
    public function behaviors()
    {
        return [];
    }

    /**
     * 返回一个值,该值指示是否有任何附加到命名事件的处理程序。
     * @param string $name the event name
     * @return bool whether there is any handler attached to the event.
     */
    public function hasEventHandlers($name)
    {
        $this->ensureBehaviors();

        foreach ($this->_eventWildcards as $wildcard => $handlers) {
            if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
                return true;
            }
        }

        return !empty($this->_events[$name]) || Event::hasHandlers($this, $name);
    }

    /**
     * 将事件处理程序附加到事件。
     *
     * 事件处理程序必须是一个有效的PHP回调。以下是一些例子:
     *
     * ```
     * function ($event) { ... }         // anonymous function
     * [$object, 'handleClick']          // $object->handleClick()
     * ['Page', 'handleClick']           // Page::handleClick()
     * 'handleClick'                     // global function handleClick()
     * ```
     *
     * 事件处理程序必须定义以下签名,
     *
     * ```
     * function ($event)
     * ```
     *
     * 其中' $event '是一个[[event]]对象,它包含与事件相关的参数。
     *
     * Since 2.0.14 you can specify event name as a wildcard pattern:
     *
     * ```php
     * $component->on('event.group.*', function ($event) {
     *     Yii::trace($event->name . ' is triggered.');
     * });
     * ```
     *
     * @param string $name 事件名
     * @param callable $handler 事件处理程序
     * @param mixed $data 事件触发时要传递给事件处理程序的数据。当调用事件处理程序时,可以通过[[event::data]]访问该数据。
     * @param bool $append 是否将新的事件处理程序追加到现有处理程序列表的末尾。如果为false,新的处理程序将被插入到现有处理程序列表的开头。
     * @see off()
     */
    public function on($name, $handler, $data = null, $append = true)
    {
        $this->ensureBehaviors();

        if (strpos($name, '*') !== false) {
            if ($append || empty($this->_eventWildcards[$name])) {
                $this->_eventWildcards[$name][] = [$handler, $data];
            } else {
                array_unshift($this->_eventWildcards[$name], [$handler, $data]);
            }
            return;
        }

        if ($append || empty($this->_events[$name])) {
            $this->_events[$name][] = [$handler, $data];
        } else {
            array_unshift($this->_events[$name], [$handler, $data]);
        }
    }

    /**
     * 从此组件中分离现有事件处理程序。
     *
     * This method is the opposite of [[on()]].
     *
     * Note: in case wildcard pattern is passed for event name, only the handlers registered with this
     * wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
     *
     * @param string $name event name
     * @param callable $handler the event handler to be removed.
     * If it is null, all handlers attached to the named event will be removed.
     * @return bool if a handler is found and detached
     * @see on()
     */
    public function off($name, $handler = null)
    {
        $this->ensureBehaviors();
        if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
            return false;
        }
        if ($handler === null) {
            unset($this->_events[$name], $this->_eventWildcards[$name]);
            return true;
        }

        $removed = false;
        // plain event names
        if (isset($this->_events[$name])) {
            foreach ($this->_events[$name] as $i => $event) {
                if ($event[0] === $handler) {
                    unset($this->_events[$name][$i]);
                    $removed = true;
                }
            }
            if ($removed) {
                $this->_events[$name] = array_values($this->_events[$name]);
                return $removed;
            }
        }

        // wildcard event names
        if (isset($this->_eventWildcards[$name])) {
            foreach ($this->_eventWildcards[$name] as $i => $event) {
                if ($event[0] === $handler) {
                    unset($this->_eventWildcards[$name][$i]);
                    $removed = true;
                }
            }
            if ($removed) {
                $this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
                // remove empty wildcards to save future redundant regex checks:
                if (empty($this->_eventWildcards[$name])) {
                    unset($this->_eventWildcards[$name]);
                }
            }
        }

        return $removed;
    }

    /**
     * Triggers an event.
     * This method represents the happening of an event. It invokes
     * all attached handlers for the event including class-level handlers.
     * @param string $name the event name
     * @param Event $event the event parameter. If not set, a default [[Event]] object will be created.
     */
    public function trigger($name, Event $event = null)
    {
        $this->ensureBehaviors();

        $eventHandlers = [];
        foreach ($this->_eventWildcards as $wildcard => $handlers) {
            if (StringHelper::matchWildcard($wildcard, $name)) {
                $eventHandlers = array_merge($eventHandlers, $handlers);
            }
        }

        if (!empty($this->_events[$name])) {
            $eventHandlers = array_merge($eventHandlers, $this->_events[$name]);
        }

        if (!empty($eventHandlers)) {
            if ($event === null) {
                $event = new Event();
            }
            if ($event->sender === null) {
                $event->sender = $this;
            }
            $event->handled = false;
            $event->name = $name;
            foreach ($eventHandlers as $handler) {
                $event->data = $handler[1];
                call_user_func($handler[0], $event);
                // stop further handling if the event is handled
                if ($event->handled) {
                    return;
                }
            }
        }

        // invoke class-level attached handlers
        Event::trigger($this, $name, $event);
    }

    /**
     * Returns the named behavior object.
     * @param string $name the behavior name
     * @return null|Behavior the behavior object, or null if the behavior does not exist
     */
    public function getBehavior($name)
    {
        $this->ensureBehaviors();
        return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
    }

    /**
     * Returns all behaviors attached to this component.
     * @return Behavior[] list of behaviors attached to this component
     */
    public function getBehaviors()
    {
        $this->ensureBehaviors();
        return $this->_behaviors;
    }

    /**
     * Attaches a behavior to this component.
     * This method will create the behavior object based on the given
     * configuration. After that, the behavior object will be attached to
     * this component by calling the [[Behavior::attach()]] method.
     * @param string $name the name of the behavior.
     * @param string|array|Behavior $behavior the behavior configuration. This can be one of the following:
     *
     *  - a [[Behavior]] object
     *  - a string specifying the behavior class
     *  - an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
     *
     * @return Behavior the behavior object
     * @see detachBehavior()
     */
    public function attachBehavior($name, $behavior)
    {
        $this->ensureBehaviors();
        return $this->attachBehaviorInternal($name, $behavior);
    }

    /**
     * Attaches a list of behaviors to the component.
     * Each behavior is indexed by its name and should be a [[Behavior]] object,
     * a string specifying the behavior class, or an configuration array for creating the behavior.
     * @param array $behaviors list of behaviors to be attached to the component
     * @see attachBehavior()
     */
    public function attachBehaviors($behaviors)
    {
        $this->ensureBehaviors();
        foreach ($behaviors as $name => $behavior) {
            $this->attachBehaviorInternal($name, $behavior);
        }
    }

    /**
     * Detaches a behavior from the component.
     * The behavior's [[Behavior::detach()]] method will be invoked.
     * @param string $name the behavior's name.
     * @return null|Behavior the detached behavior. Null if the behavior does not exist.
     */
    public function detachBehavior($name)
    {
        $this->ensureBehaviors();
        if (isset($this->_behaviors[$name])) {
            $behavior = $this->_behaviors[$name];
            unset($this->_behaviors[$name]);
            $behavior->detach();
            return $behavior;
        }

        return null;
    }

    /**
     * Detaches all behaviors from the component.
     */
    public function detachBehaviors()
    {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $name => $behavior) {
            $this->detachBehavior($name);
        }
    }

    /**
     * 确保在 behaviors() 中声明的行为被附加到这个组件。
     */
    public function ensureBehaviors()
    {
        if ($this->_behaviors === null) {
            $this->_behaviors = [];
            foreach ($this->behaviors() as $name => $behavior) {
                $this->attachBehaviorInternal($name, $behavior);
            }
        }
    }

    /**
     * Attaches a behavior to this component.
     * @param string|int $name the name of the behavior. If this is an integer, it means the behavior
     * is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name
     * will be detached first.
     * @param string|array|Behavior $behavior the behavior to be attached
     * @return Behavior the attached behavior.
     */
    private function attachBehaviorInternal($name, $behavior)
    {
        if (!($behavior instanceof Behavior)) {
            $behavior = Yii::createObject($behavior);
        }
        if (is_int($name)) {
            $behavior->attach($this);
            $this->_behaviors[] = $behavior;
        } else {
            if (isset($this->_behaviors[$name])) {
                $this->_behaviors[$name]->detach();
            }
            $behavior->attach($this);
            $this->_behaviors[$name] = $behavior;
        }

        return $behavior;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章