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.

677 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]]. Behaviors can be attached using a name or anonymously.
  404. * When a name is used as the array key, using this name, the behavior can later be retrieved using [[getBehavior()]]
  405. * or be detached using [[detachBehavior()]]. Anonymous behaviors can not be retrieved or detached.
  406. *
  407. * Behaviors declared in this method will be attached to the component automatically (on demand).
  408. *
  409. * @return array the behavior configurations.
  410. */
  411. public function behaviors()
  412. {
  413. return [];
  414. }
  415. /**
  416. * Returns a value indicating whether there is any handler attached to the named event.
  417. * @param string $name the event name
  418. * @return boolean whether there is any handler attached to the event.
  419. */
  420. public function hasEventHandlers($name)
  421. {
  422. $this->ensureBehaviors();
  423. return !empty($this->_events[$name]) || Event::hasHandlers($this, $name);
  424. }
  425. /**
  426. * Attaches an event handler to an event.
  427. *
  428. * The event handler must be a valid PHP callback. The following are
  429. * some examples:
  430. *
  431. * ```
  432. * function ($event) { ... } // anonymous function
  433. * [$object, 'handleClick'] // $object->handleClick()
  434. * ['Page', 'handleClick'] // Page::handleClick()
  435. * 'handleClick' // global function handleClick()
  436. * ```
  437. *
  438. * The event handler must be defined with the following signature,
  439. *
  440. * ```
  441. * function ($event)
  442. * ```
  443. *
  444. * where `$event` is an [[Event]] object which includes parameters associated with the event.
  445. *
  446. * @param string $name the event name
  447. * @param callable $handler the event handler
  448. * @param mixed $data the data to be passed to the event handler when the event is triggered.
  449. * When the event handler is invoked, this data can be accessed via [[Event::data]].
  450. * @param boolean $append whether to append new event handler to the end of the existing
  451. * handler list. If false, the new handler will be inserted at the beginning of the existing
  452. * handler list.
  453. * @see off()
  454. */
  455. public function on($name, $handler, $data = null, $append = true)
  456. {
  457. $this->ensureBehaviors();
  458. if ($append || empty($this->_events[$name])) {
  459. $this->_events[$name][] = [$handler, $data];
  460. } else {
  461. array_unshift($this->_events[$name], [$handler, $data]);
  462. }
  463. }
  464. /**
  465. * Detaches an existing event handler from this component.
  466. * This method is the opposite of [[on()]].
  467. * @param string $name event name
  468. * @param callable $handler the event handler to be removed.
  469. * If it is null, all handlers attached to the named event will be removed.
  470. * @return boolean if a handler is found and detached
  471. * @see on()
  472. */
  473. public function off($name, $handler = null)
  474. {
  475. $this->ensureBehaviors();
  476. if (empty($this->_events[$name])) {
  477. return false;
  478. }
  479. if ($handler === null) {
  480. unset($this->_events[$name]);
  481. return true;
  482. } else {
  483. $removed = false;
  484. foreach ($this->_events[$name] as $i => $event) {
  485. if ($event[0] === $handler) {
  486. unset($this->_events[$name][$i]);
  487. $removed = true;
  488. }
  489. }
  490. if ($removed) {
  491. $this->_events[$name] = array_values($this->_events[$name]);
  492. }
  493. return $removed;
  494. }
  495. }
  496. /**
  497. * Triggers an event.
  498. * This method represents the happening of an event. It invokes
  499. * all attached handlers for the event including class-level handlers.
  500. * @param string $name the event name
  501. * @param Event $event the event parameter. If not set, a default [[Event]] object will be created.
  502. */
  503. public function trigger($name, Event $event = null)
  504. {
  505. $this->ensureBehaviors();
  506. if (!empty($this->_events[$name])) {
  507. if ($event === null) {
  508. $event = new Event;
  509. }
  510. if ($event->sender === null) {
  511. $event->sender = $this;
  512. }
  513. $event->handled = false;
  514. $event->name = $name;
  515. foreach ($this->_events[$name] as $handler) {
  516. $event->data = $handler[1];
  517. call_user_func($handler[0], $event);
  518. // stop further handling if the event is handled
  519. if ($event->handled) {
  520. return;
  521. }
  522. }
  523. }
  524. // invoke class-level attached handlers
  525. Event::trigger($this, $name, $event);
  526. }
  527. /**
  528. * Returns the named behavior object.
  529. * @param string $name the behavior name
  530. * @return null|Behavior the behavior object, or null if the behavior does not exist
  531. */
  532. public function getBehavior($name)
  533. {
  534. $this->ensureBehaviors();
  535. return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
  536. }
  537. /**
  538. * Returns all behaviors attached to this component.
  539. * @return Behavior[] list of behaviors attached to this component
  540. */
  541. public function getBehaviors()
  542. {
  543. $this->ensureBehaviors();
  544. return $this->_behaviors;
  545. }
  546. /**
  547. * Attaches a behavior to this component.
  548. * This method will create the behavior object based on the given
  549. * configuration. After that, the behavior object will be attached to
  550. * this component by calling the [[Behavior::attach()]] method.
  551. * @param string $name the name of the behavior.
  552. * @param string|array|Behavior $behavior the behavior configuration. This can be one of the following:
  553. *
  554. * - a [[Behavior]] object
  555. * - a string specifying the behavior class
  556. * - an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
  557. *
  558. * @return Behavior the behavior object
  559. * @see detachBehavior()
  560. */
  561. public function attachBehavior($name, $behavior)
  562. {
  563. $this->ensureBehaviors();
  564. return $this->attachBehaviorInternal($name, $behavior);
  565. }
  566. /**
  567. * Attaches a list of behaviors to the component.
  568. * Each behavior is indexed by its name and should be a [[Behavior]] object,
  569. * a string specifying the behavior class, or an configuration array for creating the behavior.
  570. * @param array $behaviors list of behaviors to be attached to the component
  571. * @see attachBehavior()
  572. */
  573. public function attachBehaviors($behaviors)
  574. {
  575. $this->ensureBehaviors();
  576. foreach ($behaviors as $name => $behavior) {
  577. $this->attachBehaviorInternal($name, $behavior);
  578. }
  579. }
  580. /**
  581. * Detaches a behavior from the component.
  582. * The behavior's [[Behavior::detach()]] method will be invoked.
  583. * @param string $name the behavior's name.
  584. * @return null|Behavior the detached behavior. Null if the behavior does not exist.
  585. */
  586. public function detachBehavior($name)
  587. {
  588. $this->ensureBehaviors();
  589. if (isset($this->_behaviors[$name])) {
  590. $behavior = $this->_behaviors[$name];
  591. unset($this->_behaviors[$name]);
  592. $behavior->detach();
  593. return $behavior;
  594. } else {
  595. return null;
  596. }
  597. }
  598. /**
  599. * Detaches all behaviors from the component.
  600. */
  601. public function detachBehaviors()
  602. {
  603. $this->ensureBehaviors();
  604. foreach ($this->_behaviors as $name => $behavior) {
  605. $this->detachBehavior($name);
  606. }
  607. }
  608. /**
  609. * Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
  610. */
  611. public function ensureBehaviors()
  612. {
  613. if ($this->_behaviors === null) {
  614. $this->_behaviors = [];
  615. foreach ($this->behaviors() as $name => $behavior) {
  616. $this->attachBehaviorInternal($name, $behavior);
  617. }
  618. }
  619. }
  620. /**
  621. * Attaches a behavior to this component.
  622. * @param string|integer $name the name of the behavior. If this is an integer, it means the behavior
  623. * is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name
  624. * will be detached first.
  625. * @param string|array|Behavior $behavior the behavior to be attached
  626. * @return Behavior the attached behavior.
  627. */
  628. private function attachBehaviorInternal($name, $behavior)
  629. {
  630. if (!($behavior instanceof Behavior)) {
  631. $behavior = Yii::createObject($behavior);
  632. }
  633. if (is_int($name)) {
  634. $behavior->attach($this);
  635. $this->_behaviors[] = $behavior;
  636. } else {
  637. if (isset($this->_behaviors[$name])) {
  638. $this->_behaviors[$name]->detach();
  639. }
  640. $behavior->attach($this);
  641. $this->_behaviors[$name] = $behavior;
  642. }
  643. return $behavior;
  644. }
  645. }