Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

678 lines
25KB

  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. namespace yii\base;
  8. use Yii;
  9. /**
  10. * Component is the base class that implements the *property*, *event* and *behavior* features.
  11. *
  12. * Component provides the *event* and *behavior* features, in addition to the *property* feature which is implemented in
  13. * its parent class [[Object]].
  14. *
  15. * Event is a way to "inject" custom code into existing code at certain places. For example, a comment object can trigger
  16. * an "add" event when the user adds a comment. We can write custom code and attach it to this event so that when the event
  17. * is triggered (i.e. comment will be added), our custom code will be executed.
  18. *
  19. * An event is identified by a name that should be unique within the class it is defined at. Event names are *case-sensitive*.
  20. *
  21. * One or multiple PHP callbacks, called *event handlers*, can be attached to an event. You can call [[trigger()]] to
  22. * raise an event. When an event is raised, the event handlers will be invoked automatically in the order they were
  23. * attached.
  24. *
  25. * To attach an event handler to an event, call [[on()]]:
  26. *
  27. * ```php
  28. * $post->on('update', function ($event) {
  29. * // send email notification
  30. * });
  31. * ```
  32. *
  33. * In the above, an anonymous function is attached to the "update" event of the post. You may attach
  34. * the following types of event handlers:
  35. *
  36. * - anonymous function: `function ($event) { ... }`
  37. * - object method: `[$object, 'handleAdd']`
  38. * - static class method: `['Page', 'handleAdd']`
  39. * - global function: `'handleAdd'`
  40. *
  41. * The signature of an event handler should be like the following:
  42. *
  43. * ```php
  44. * function foo($event)
  45. * ```
  46. *
  47. * where `$event` is an [[Event]] object which includes parameters associated with the event.
  48. *
  49. * You can also attach a handler to an event when configuring a component with a configuration array.
  50. * The syntax is like the following:
  51. *
  52. * ```php
  53. * [
  54. * 'on add' => function ($event) { ... }
  55. * ]
  56. * ```
  57. *
  58. * where `on add` stands for attaching an event to the `add` event.
  59. *
  60. * Sometimes, you may want to associate extra data with an event handler when you attach it to an event
  61. * and then access it when the handler is invoked. You may do so by
  62. *
  63. * ```php
  64. * $post->on('update', function ($event) {
  65. * // the data can be accessed via $event->data
  66. * }, $data);
  67. * ```
  68. *
  69. * A behavior is an instance of [[Behavior]] or its child class. A component can be attached with one or multiple
  70. * behaviors. When a behavior is attached to a component, its public properties and methods can be accessed via the
  71. * component directly, as if the component owns those properties and methods.
  72. *
  73. * To attach a behavior to a component, declare it in [[behaviors()]], or explicitly call [[attachBehavior]]. Behaviors
  74. * declared in [[behaviors()]] are automatically attached to the corresponding component.
  75. *
  76. * One can also attach a behavior to a component when configuring it with a configuration array. The syntax is like the
  77. * following:
  78. *
  79. * ```php
  80. * [
  81. * 'as tree' => [
  82. * 'class' => 'Tree',
  83. * ],
  84. * ]
  85. * ```
  86. *
  87. * where `as tree` stands for attaching a behavior named `tree`, and the array will be passed to [[\Yii::createObject()]]
  88. * to create the behavior object.
  89. *
  90. * @property Behavior[] $behaviors List of behaviors attached to this component. This property is read-only.
  91. *
  92. * @author Qiang Xue <qiang.xue@gmail.com>
  93. * @since 2.0
  94. */
  95. class Component extends Object
  96. {
  97. /**
  98. * @var array the attached event handlers (event name => handlers)
  99. */
  100. private $_events = [];
  101. /**
  102. * @var Behavior[]|null the attached behaviors (behavior name => behavior). This is `null` when not initialized.
  103. */
  104. private $_behaviors;
  105. /**
  106. * Returns the value of a component property.
  107. * This method will check in the following order and act accordingly:
  108. *
  109. * - a property defined by a getter: return the getter result
  110. * - a property of a behavior: return the behavior property value
  111. *
  112. * Do not call this method directly as it is a PHP magic method that
  113. * will be implicitly called when executing `$value = $component->property;`.
  114. * @param string $name the property name
  115. * @return mixed the property value or the value of a behavior's property
  116. * @throws UnknownPropertyException if the property is not defined
  117. * @throws InvalidCallException if the property is write-only.
  118. * @see __set()
  119. */
  120. public function __get($name)
  121. {
  122. $getter = 'get' . $name;
  123. if (method_exists($this, $getter)) {
  124. // read property, e.g. getName()
  125. return $this->$getter();
  126. } else {
  127. // behavior property
  128. $this->ensureBehaviors();
  129. foreach ($this->_behaviors as $behavior) {
  130. if ($behavior->canGetProperty($name)) {
  131. return $behavior->$name;
  132. }
  133. }
  134. }
  135. if (method_exists($this, 'set' . $name)) {
  136. throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
  137. } else {
  138. throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
  139. }
  140. }
  141. /**
  142. * Sets the value of a component property.
  143. * This method will check in the following order and act accordingly:
  144. *
  145. * - a property defined by a setter: set the property value
  146. * - an event in the format of "on xyz": attach the handler to the event "xyz"
  147. * - a behavior in the format of "as xyz": attach the behavior named as "xyz"
  148. * - a property of a behavior: set the behavior property value
  149. *
  150. * Do not call this method directly as it is a PHP magic method that
  151. * will be implicitly called when executing `$component->property = $value;`.
  152. * @param string $name the property name or the event name
  153. * @param mixed $value the property value
  154. * @throws UnknownPropertyException if the property is not defined
  155. * @throws InvalidCallException if the property is read-only.
  156. * @see __get()
  157. */
  158. public function __set($name, $value)
  159. {
  160. $setter = 'set' . $name;
  161. if (method_exists($this, $setter)) {
  162. // set property
  163. $this->$setter($value);
  164. return;
  165. } elseif (strncmp($name, 'on ', 3) === 0) {
  166. // on event: attach event handler
  167. $this->on(trim(substr($name, 3)), $value);
  168. return;
  169. } elseif (strncmp($name, 'as ', 3) === 0) {
  170. // as behavior: attach behavior
  171. $name = trim(substr($name, 3));
  172. $this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
  173. return;
  174. } else {
  175. // behavior property
  176. $this->ensureBehaviors();
  177. foreach ($this->_behaviors as $behavior) {
  178. if ($behavior->canSetProperty($name)) {
  179. $behavior->$name = $value;
  180. return;
  181. }
  182. }
  183. }
  184. if (method_exists($this, 'get' . $name)) {
  185. throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
  186. } else {
  187. throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
  188. }
  189. }
  190. /**
  191. * Checks if a property is set, i.e. defined and not null.
  192. * This method will check in the following order and act accordingly:
  193. *
  194. * - a property defined by a setter: return whether the property is set
  195. * - a property of a behavior: return whether the property is set
  196. * - return `false` for non existing properties
  197. *
  198. * Do not call this method directly as it is a PHP magic method that
  199. * will be implicitly called when executing `isset($component->property)`.
  200. * @param string $name the property name or the event name
  201. * @return boolean whether the named property is set
  202. * @see http://php.net/manual/en/function.isset.php
  203. */
  204. public function __isset($name)
  205. {
  206. $getter = 'get' . $name;
  207. if (method_exists($this, $getter)) {
  208. return $this->$getter() !== null;
  209. } else {
  210. // behavior property
  211. $this->ensureBehaviors();
  212. foreach ($this->_behaviors as $behavior) {
  213. if ($behavior->canGetProperty($name)) {
  214. return $behavior->$name !== null;
  215. }
  216. }
  217. }
  218. return false;
  219. }
  220. /**
  221. * Sets a component property to be null.
  222. * This method will check in the following order and act accordingly:
  223. *
  224. * - a property defined by a setter: set the property value to be null
  225. * - a property of a behavior: set the property value to be null
  226. *
  227. * Do not call this method directly as it is a PHP magic method that
  228. * will be implicitly called when executing `unset($component->property)`.
  229. * @param string $name the property name
  230. * @throws InvalidCallException if the property is read only.
  231. * @see http://php.net/manual/en/function.unset.php
  232. */
  233. public function __unset($name)
  234. {
  235. $setter = 'set' . $name;
  236. if (method_exists($this, $setter)) {
  237. $this->$setter(null);
  238. return;
  239. } else {
  240. // behavior property
  241. $this->ensureBehaviors();
  242. foreach ($this->_behaviors as $behavior) {
  243. if ($behavior->canSetProperty($name)) {
  244. $behavior->$name = null;
  245. return;
  246. }
  247. }
  248. }
  249. throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
  250. }
  251. /**
  252. * Calls the named method which is not a class method.
  253. *
  254. * This method will check if any attached behavior has
  255. * the named method and will execute it if available.
  256. *
  257. * Do not call this method directly as it is a PHP magic method that
  258. * will be implicitly called when an unknown method is being invoked.
  259. * @param string $name the method name
  260. * @param array $params method parameters
  261. * @return mixed the method return value
  262. * @throws UnknownMethodException when calling unknown method
  263. */
  264. public function __call($name, $params)
  265. {
  266. $this->ensureBehaviors();
  267. foreach ($this->_behaviors as $object) {
  268. if ($object->hasMethod($name)) {
  269. return call_user_func_array([$object, $name], $params);
  270. }
  271. }
  272. throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
  273. }
  274. /**
  275. * This method is called after the object is created by cloning an existing one.
  276. * It removes all behaviors because they are attached to the old object.
  277. */
  278. public function __clone()
  279. {
  280. $this->_events = [];
  281. $this->_behaviors = null;
  282. }
  283. /**
  284. * Returns a value indicating whether a property is defined for this component.
  285. * A property is defined if:
  286. *
  287. * - the class has a getter or setter method associated with the specified name
  288. * (in this case, property name is case-insensitive);
  289. * - the class has a member variable with the specified name (when `$checkVars` is true);
  290. * - an attached behavior has a property of the given name (when `$checkBehaviors` is true).
  291. *
  292. * @param string $name the property name
  293. * @param boolean $checkVars whether to treat member variables as properties
  294. * @param boolean $checkBehaviors whether to treat behaviors' properties as properties of this component
  295. * @return boolean whether the property is defined
  296. * @see canGetProperty()
  297. * @see canSetProperty()
  298. */
  299. public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
  300. {
  301. return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
  302. }
  303. /**
  304. * Returns a value indicating whether a property can be read.
  305. * A property can be read if:
  306. *
  307. * - the class has a getter method associated with the specified name
  308. * (in this case, property name is case-insensitive);
  309. * - the class has a member variable with the specified name (when `$checkVars` is true);
  310. * - an attached behavior has a readable property of the given name (when `$checkBehaviors` is true).
  311. *
  312. * @param string $name the property name
  313. * @param boolean $checkVars whether to treat member variables as properties
  314. * @param boolean $checkBehaviors whether to treat behaviors' properties as properties of this component
  315. * @return boolean whether the property can be read
  316. * @see canSetProperty()
  317. */
  318. public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
  319. {
  320. if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
  321. return true;
  322. } elseif ($checkBehaviors) {
  323. $this->ensureBehaviors();
  324. foreach ($this->_behaviors as $behavior) {
  325. if ($behavior->canGetProperty($name, $checkVars)) {
  326. return true;
  327. }
  328. }
  329. }
  330. return false;
  331. }
  332. /**
  333. * Returns a value indicating whether a property can be set.
  334. * A property can be written if:
  335. *
  336. * - the class has a setter method associated with the specified name
  337. * (in this case, property name is case-insensitive);
  338. * - the class has a member variable with the specified name (when `$checkVars` is true);
  339. * - an attached behavior has a writable property of the given name (when `$checkBehaviors` is true).
  340. *
  341. * @param string $name the property name
  342. * @param boolean $checkVars whether to treat member variables as properties
  343. * @param boolean $checkBehaviors whether to treat behaviors' properties as properties of this component
  344. * @return boolean whether the property can be written
  345. * @see canGetProperty()
  346. */
  347. public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
  348. {
  349. if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
  350. return true;
  351. } elseif ($checkBehaviors) {
  352. $this->ensureBehaviors();
  353. foreach ($this->_behaviors as $behavior) {
  354. if ($behavior->canSetProperty($name, $checkVars)) {
  355. return true;
  356. }
  357. }
  358. }
  359. return false;
  360. }
  361. /**
  362. * Returns a value indicating whether a method is defined.
  363. * A method is defined if:
  364. *
  365. * - the class has a method with the specified name
  366. * - an attached behavior has a method with the given name (when `$checkBehaviors` is true).
  367. *
  368. * @param string $name the property name
  369. * @param boolean $checkBehaviors whether to treat behaviors' methods as methods of this component
  370. * @return boolean whether the property is defined
  371. */
  372. public function hasMethod($name, $checkBehaviors = true)
  373. {
  374. if (method_exists($this, $name)) {
  375. return true;
  376. } elseif ($checkBehaviors) {
  377. $this->ensureBehaviors();
  378. foreach ($this->_behaviors as $behavior) {
  379. if ($behavior->hasMethod($name)) {
  380. return true;
  381. }
  382. }
  383. }
  384. return false;
  385. }
  386. /**
  387. * Returns a list of behaviors that this component should behave as.
  388. *
  389. * Child classes may override this method to specify the behaviors they want to behave as.
  390. *
  391. * The return value of this method should be an array of behavior objects or configurations
  392. * indexed by behavior names. A behavior configuration can be either a string specifying
  393. * the behavior class or an array of the following structure:
  394. *
  395. * ```php
  396. * 'behaviorName' => [
  397. * 'class' => 'BehaviorClass',
  398. * 'property1' => 'value1',
  399. * 'property2' => 'value2',
  400. * ]
  401. * ```
  402. *
  403. * Note that a behavior class must extend from [[Behavior]]. Behavior names can be strings
  404. * or integers. If the former, they uniquely identify the behaviors. If the latter, the corresponding
  405. * behaviors are anonymous and their properties and methods will NOT be made available via the component
  406. * (however, the behaviors can still respond to the component's events).
  407. *
  408. * Behaviors declared in this method will be attached to the component automatically (on demand).
  409. *
  410. * @return array the behavior configurations.
  411. */
  412. public function behaviors()
  413. {
  414. return [];
  415. }
  416. /**
  417. * Returns a value indicating whether there is any handler attached to the named event.
  418. * @param string $name the event name
  419. * @return boolean whether there is any handler attached to the event.
  420. */
  421. public function hasEventHandlers($name)
  422. {
  423. $this->ensureBehaviors();
  424. return !empty($this->_events[$name]) || Event::hasHandlers($this, $name);
  425. }
  426. /**
  427. * Attaches an event handler to an event.
  428. *
  429. * The event handler must be a valid PHP callback. The following are
  430. * some examples:
  431. *
  432. * ```
  433. * function ($event) { ... } // anonymous function
  434. * [$object, 'handleClick'] // $object->handleClick()
  435. * ['Page', 'handleClick'] // Page::handleClick()
  436. * 'handleClick' // global function handleClick()
  437. * ```
  438. *
  439. * The event handler must be defined with the following signature,
  440. *
  441. * ```
  442. * function ($event)
  443. * ```
  444. *
  445. * where `$event` is an [[Event]] object which includes parameters associated with the event.
  446. *
  447. * @param string $name the event name
  448. * @param callable $handler the event handler
  449. * @param mixed $data the data to be passed to the event handler when the event is triggered.
  450. * When the event handler is invoked, this data can be accessed via [[Event::data]].
  451. * @param boolean $append whether to append new event handler to the end of the existing
  452. * handler list. If false, the new handler will be inserted at the beginning of the existing
  453. * handler list.
  454. * @see off()
  455. */
  456. public function on($name, $handler, $data = null, $append = true)
  457. {
  458. $this->ensureBehaviors();
  459. if ($append || empty($this->_events[$name])) {
  460. $this->_events[$name][] = [$handler, $data];
  461. } else {
  462. array_unshift($this->_events[$name], [$handler, $data]);
  463. }
  464. }
  465. /**
  466. * Detaches an existing event handler from this component.
  467. * This method is the opposite of [[on()]].
  468. * @param string $name event name
  469. * @param callable $handler the event handler to be removed.
  470. * If it is null, all handlers attached to the named event will be removed.
  471. * @return boolean if a handler is found and detached
  472. * @see on()
  473. */
  474. public function off($name, $handler = null)
  475. {
  476. $this->ensureBehaviors();
  477. if (empty($this->_events[$name])) {
  478. return false;
  479. }
  480. if ($handler === null) {
  481. unset($this->_events[$name]);
  482. return true;
  483. } else {
  484. $removed = false;
  485. foreach ($this->_events[$name] as $i => $event) {
  486. if ($event[0] === $handler) {
  487. unset($this->_events[$name][$i]);
  488. $removed = true;
  489. }
  490. }
  491. if ($removed) {
  492. $this->_events[$name] = array_values($this->_events[$name]);
  493. }
  494. return $removed;
  495. }
  496. }
  497. /**
  498. * Triggers an event.
  499. * This method represents the happening of an event. It invokes
  500. * all attached handlers for the event including class-level handlers.
  501. * @param string $name the event name
  502. * @param Event $event the event parameter. If not set, a default [[Event]] object will be created.
  503. */
  504. public function trigger($name, Event $event = null)
  505. {
  506. $this->ensureBehaviors();
  507. if (!empty($this->_events[$name])) {
  508. if ($event === null) {
  509. $event = new Event;
  510. }
  511. if ($event->sender === null) {
  512. $event->sender = $this;
  513. }
  514. $event->handled = false;
  515. $event->name = $name;
  516. foreach ($this->_events[$name] as $handler) {
  517. $event->data = $handler[1];
  518. call_user_func($handler[0], $event);
  519. // stop further handling if the event is handled
  520. if ($event->handled) {
  521. return;
  522. }
  523. }
  524. }
  525. // invoke class-level attached handlers
  526. Event::trigger($this, $name, $event);
  527. }
  528. /**
  529. * Returns the named behavior object.
  530. * @param string $name the behavior name
  531. * @return null|Behavior the behavior object, or null if the behavior does not exist
  532. */
  533. public function getBehavior($name)
  534. {
  535. $this->ensureBehaviors();
  536. return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
  537. }
  538. /**
  539. * Returns all behaviors attached to this component.
  540. * @return Behavior[] list of behaviors attached to this component
  541. */
  542. public function getBehaviors()
  543. {
  544. $this->ensureBehaviors();
  545. return $this->_behaviors;
  546. }
  547. /**
  548. * Attaches a behavior to this component.
  549. * This method will create the behavior object based on the given
  550. * configuration. After that, the behavior object will be attached to
  551. * this component by calling the [[Behavior::attach()]] method.
  552. * @param string $name the name of the behavior.
  553. * @param string|array|Behavior $behavior the behavior configuration. This can be one of the following:
  554. *
  555. * - a [[Behavior]] object
  556. * - a string specifying the behavior class
  557. * - an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
  558. *
  559. * @return Behavior the behavior object
  560. * @see detachBehavior()
  561. */
  562. public function attachBehavior($name, $behavior)
  563. {
  564. $this->ensureBehaviors();
  565. return $this->attachBehaviorInternal($name, $behavior);
  566. }
  567. /**
  568. * Attaches a list of behaviors to the component.
  569. * Each behavior is indexed by its name and should be a [[Behavior]] object,
  570. * a string specifying the behavior class, or an configuration array for creating the behavior.
  571. * @param array $behaviors list of behaviors to be attached to the component
  572. * @see attachBehavior()
  573. */
  574. public function attachBehaviors($behaviors)
  575. {
  576. $this->ensureBehaviors();
  577. foreach ($behaviors as $name => $behavior) {
  578. $this->attachBehaviorInternal($name, $behavior);
  579. }
  580. }
  581. /**
  582. * Detaches a behavior from the component.
  583. * The behavior's [[Behavior::detach()]] method will be invoked.
  584. * @param string $name the behavior's name.
  585. * @return null|Behavior the detached behavior. Null if the behavior does not exist.
  586. */
  587. public function detachBehavior($name)
  588. {
  589. $this->ensureBehaviors();
  590. if (isset($this->_behaviors[$name])) {
  591. $behavior = $this->_behaviors[$name];
  592. unset($this->_behaviors[$name]);
  593. $behavior->detach();
  594. return $behavior;
  595. } else {
  596. return null;
  597. }
  598. }
  599. /**
  600. * Detaches all behaviors from the component.
  601. */
  602. public function detachBehaviors()
  603. {
  604. $this->ensureBehaviors();
  605. foreach ($this->_behaviors as $name => $behavior) {
  606. $this->detachBehavior($name);
  607. }
  608. }
  609. /**
  610. * Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
  611. */
  612. public function ensureBehaviors()
  613. {
  614. if ($this->_behaviors === null) {
  615. $this->_behaviors = [];
  616. foreach ($this->behaviors() as $name => $behavior) {
  617. $this->attachBehaviorInternal($name, $behavior);
  618. }
  619. }
  620. }
  621. /**
  622. * Attaches a behavior to this component.
  623. * @param string|integer $name the name of the behavior. If this is an integer, it means the behavior
  624. * is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name
  625. * will be detached first.
  626. * @param string|array|Behavior $behavior the behavior to be attached
  627. * @return Behavior the attached behavior.
  628. */
  629. private function attachBehaviorInternal($name, $behavior)
  630. {
  631. if (!($behavior instanceof Behavior)) {
  632. $behavior = Yii::createObject($behavior);
  633. }
  634. if (is_int($name)) {
  635. $behavior->attach($this);
  636. $this->_behaviors[] = $behavior;
  637. } else {
  638. if (isset($this->_behaviors[$name])) {
  639. $this->_behaviors[$name]->detach();
  640. }
  641. $behavior->attach($this);
  642. $this->_behaviors[$name] = $behavior;
  643. }
  644. return $behavior;
  645. }
  646. }