把杯子裏面的水清空,從零開始學習編程。第五節 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;
    }
}

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