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.

675 satır
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. * ~~~
  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. * ~~~
  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. * ~~~
  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. * ~~~
  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. * ~~~
  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 value is 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 value is null
  195. * - a property of a behavior: return whether the property value is null
  196. *
  197. * Do not call this method directly as it is a PHP magic method that
  198. * will be implicitly called when executing `isset($component->property)`.
  199. * @param string $name the property name or the event name
  200. * @return boolean whether the named property is null
  201. */
  202. public function __isset($name)
  203. {
  204. $getter = 'get' . $name;
  205. if (method_exists($this, $getter)) {
  206. return $this->$getter() !== null;
  207. } else {
  208. // behavior property
  209. $this->ensureBehaviors();
  210. foreach ($this->_behaviors as $behavior) {
  211. if ($behavior->canGetProperty($name)) {
  212. return $behavior->$name !== null;
  213. }
  214. }
  215. }
  216. return false;
  217. }
  218. /**
  219. * Sets a component property to be null.
  220. * This method will check in the following order and act accordingly:
  221. *
  222. * - a property defined by a setter: set the property value to be null
  223. * - a property of a behavior: set the property value to be null
  224. *
  225. * Do not call this method directly as it is a PHP magic method that
  226. * will be implicitly called when executing `unset($component->property)`.
  227. * @param string $name the property name
  228. * @throws InvalidCallException if the property is read only.
  229. */
  230. public function __unset($name)
  231. {
  232. $setter = 'set' . $name;
  233. if (method_exists($this, $setter)) {
  234. $this->$setter(null);
  235. return;
  236. } else {
  237. // behavior property
  238. $this->ensureBehaviors();
  239. foreach ($this->_behaviors as $behavior) {
  240. if ($behavior->canSetProperty($name)) {
  241. $behavior->$name = null;
  242. return;
  243. }
  244. }
  245. }
  246. throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
  247. }
  248. /**
  249. * Calls the named method which is not a class method.
  250. *
  251. * This method will check if any attached behavior has
  252. * the named method and will execute it if available.
  253. *
  254. * Do not call this method directly as it is a PHP magic method that
  255. * will be implicitly called when an unknown method is being invoked.
  256. * @param string $name the method name
  257. * @param array $params method parameters
  258. * @return mixed the method return value
  259. * @throws UnknownMethodException when calling unknown method
  260. */
  261. public function __call($name, $params)
  262. {
  263. $this->ensureBehaviors();
  264. foreach ($this->_behaviors as $object) {
  265. if ($object->hasMethod($name)) {
  266. return call_user_func_array([$object, $name], $params);
  267. }
  268. }
  269. throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
  270. }
  271. /**
  272. * This method is called after the object is created by cloning an existing one.
  273. * It removes all behaviors because they are attached to the old object.
  274. */
  275. public function __clone()
  276. {
  277. $this->_events = [];
  278. $this->_behaviors = null;
  279. }
  280. /**
  281. * Returns a value indicating whether a property is defined for this component.
  282. * A property is defined if:
  283. *
  284. * - the class has a getter or setter method associated with the specified name
  285. * (in this case, property name is case-insensitive);
  286. * - the class has a member variable with the specified name (when `$checkVars` is true);
  287. * - an attached behavior has a property of the given name (when `$checkBehaviors` is true).
  288. *
  289. * @param string $name the property name
  290. * @param boolean $checkVars whether to treat member variables as properties
  291. * @param boolean $checkBehaviors whether to treat behaviors' properties as properties of this component
  292. * @return boolean whether the property is defined
  293. * @see canGetProperty()
  294. * @see canSetProperty()
  295. */
  296. public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
  297. {
  298. return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
  299. }
  300. /**
  301. * Returns a value indicating whether a property can be read.
  302. * A property can be read if:
  303. *
  304. * - the class has a getter method associated with the specified name
  305. * (in this case, property name is case-insensitive);
  306. * - the class has a member variable with the specified name (when `$checkVars` is true);
  307. * - an attached behavior has a readable property of the given name (when `$checkBehaviors` is true).
  308. *
  309. * @param string $name the property name
  310. * @param boolean $checkVars whether to treat member variables as properties
  311. * @param boolean $checkBehaviors whether to treat behaviors' properties as properties of this component
  312. * @return boolean whether the property can be read
  313. * @see canSetProperty()
  314. */
  315. public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
  316. {
  317. if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
  318. return true;
  319. } elseif ($checkBehaviors) {
  320. $this->ensureBehaviors();
  321. foreach ($this->_behaviors as $behavior) {
  322. if ($behavior->canGetProperty($name, $checkVars)) {
  323. return true;
  324. }
  325. }
  326. }
  327. return false;
  328. }
  329. /**
  330. * Returns a value indicating whether a property can be set.
  331. * A property can be written if:
  332. *
  333. * - the class has a setter method associated with the specified name
  334. * (in this case, property name is case-insensitive);
  335. * - the class has a member variable with the specified name (when `$checkVars` is true);
  336. * - an attached behavior has a writable property of the given name (when `$checkBehaviors` is true).
  337. *
  338. * @param string $name the property name
  339. * @param boolean $checkVars whether to treat member variables as properties
  340. * @param boolean $checkBehaviors whether to treat behaviors' properties as properties of this component
  341. * @return boolean whether the property can be written
  342. * @see canGetProperty()
  343. */
  344. public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
  345. {
  346. if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
  347. return true;
  348. } elseif ($checkBehaviors) {
  349. $this->ensureBehaviors();
  350. foreach ($this->_behaviors as $behavior) {
  351. if ($behavior->canSetProperty($name, $checkVars)) {
  352. return true;
  353. }
  354. }
  355. }
  356. return false;
  357. }
  358. /**
  359. * Returns a value indicating whether a method is defined.
  360. * A method is defined if:
  361. *
  362. * - the class has a method with the specified name
  363. * - an attached behavior has a method with the given name (when `$checkBehaviors` is true).
  364. *
  365. * @param string $name the property name
  366. * @param boolean $checkBehaviors whether to treat behaviors' methods as methods of this component
  367. * @return boolean whether the property is defined
  368. */
  369. public function hasMethod($name, $checkBehaviors = true)
  370. {
  371. if (method_exists($this, $name)) {
  372. return true;
  373. } elseif ($checkBehaviors) {
  374. $this->ensureBehaviors();
  375. foreach ($this->_behaviors as $behavior) {
  376. if ($behavior->hasMethod($name)) {
  377. return true;
  378. }
  379. }
  380. }
  381. return false;
  382. }
  383. /**
  384. * Returns a list of behaviors that this component should behave as.
  385. *
  386. * Child classes may override this method to specify the behaviors they want to behave as.
  387. *
  388. * The return value of this method should be an array of behavior objects or configurations
  389. * indexed by behavior names. A behavior configuration can be either a string specifying
  390. * the behavior class or an array of the following structure:
  391. *
  392. * ~~~
  393. * 'behaviorName' => [
  394. * 'class' => 'BehaviorClass',
  395. * 'property1' => 'value1',
  396. * 'property2' => 'value2',
  397. * ]
  398. * ~~~
  399. *
  400. * Note that a behavior class must extend from [[Behavior]]. Behavior names can be strings
  401. * or integers. If the former, they uniquely identify the behaviors. If the latter, the corresponding
  402. * behaviors are anonymous and their properties and methods will NOT be made available via the component
  403. * (however, the behaviors can still respond to the component's events).
  404. *
  405. * Behaviors declared in this method will be attached to the component automatically (on demand).
  406. *
  407. * @return array the behavior configurations.
  408. */
  409. public function behaviors()
  410. {
  411. return [];
  412. }
  413. /**
  414. * Returns a value indicating whether there is any handler attached to the named event.
  415. * @param string $name the event name
  416. * @return boolean whether there is any handler attached to the event.
  417. */
  418. public function hasEventHandlers($name)
  419. {
  420. $this->ensureBehaviors();
  421. return !empty($this->_events[$name]) || Event::hasHandlers($this, $name);
  422. }
  423. /**
  424. * Attaches an event handler to an event.
  425. *
  426. * The event handler must be a valid PHP callback. The followings are
  427. * some examples:
  428. *
  429. * ~~~
  430. * function ($event) { ... } // anonymous function
  431. * [$object, 'handleClick'] // $object->handleClick()
  432. * ['Page', 'handleClick'] // Page::handleClick()
  433. * 'handleClick' // global function handleClick()
  434. * ~~~
  435. *
  436. * The event handler must be defined with the following signature,
  437. *
  438. * ~~~
  439. * function ($event)
  440. * ~~~
  441. *
  442. * where `$event` is an [[Event]] object which includes parameters associated with the event.
  443. *
  444. * @param string $name the event name
  445. * @param callable $handler the event handler
  446. * @param mixed $data the data to be passed to the event handler when the event is triggered.
  447. * When the event handler is invoked, this data can be accessed via [[Event::data]].
  448. * @param boolean $append whether to append new event handler to the end of the existing
  449. * handler list. If false, the new handler will be inserted at the beginning of the existing
  450. * handler list.
  451. * @see off()
  452. */
  453. public function on($name, $handler, $data = null, $append = true)
  454. {
  455. $this->ensureBehaviors();
  456. if ($append || empty($this->_events[$name])) {
  457. $this->_events[$name][] = [$handler, $data];
  458. } else {
  459. array_unshift($this->_events[$name], [$handler, $data]);
  460. }
  461. }
  462. /**
  463. * Detaches an existing event handler from this component.
  464. * This method is the opposite of [[on()]].
  465. * @param string $name event name
  466. * @param callable $handler the event handler to be removed.
  467. * If it is null, all handlers attached to the named event will be removed.
  468. * @return boolean if a handler is found and detached
  469. * @see on()
  470. */
  471. public function off($name, $handler = null)
  472. {
  473. $this->ensureBehaviors();
  474. if (empty($this->_events[$name])) {
  475. return false;
  476. }
  477. if ($handler === null) {
  478. unset($this->_events[$name]);
  479. return true;
  480. } else {
  481. $removed = false;
  482. foreach ($this->_events[$name] as $i => $event) {
  483. if ($event[0] === $handler) {
  484. unset($this->_events[$name][$i]);
  485. $removed = true;
  486. }
  487. }
  488. if ($removed) {
  489. $this->_events[$name] = array_values($this->_events[$name]);
  490. }
  491. return $removed;
  492. }
  493. }
  494. /**
  495. * Triggers an event.
  496. * This method represents the happening of an event. It invokes
  497. * all attached handlers for the event including class-level handlers.
  498. * @param string $name the event name
  499. * @param Event $event the event parameter. If not set, a default [[Event]] object will be created.
  500. */
  501. public function trigger($name, Event $event = null)
  502. {
  503. $this->ensureBehaviors();
  504. if (!empty($this->_events[$name])) {
  505. if ($event === null) {
  506. $event = new Event;
  507. }
  508. if ($event->sender === null) {
  509. $event->sender = $this;
  510. }
  511. $event->handled = false;
  512. $event->name = $name;
  513. foreach ($this->_events[$name] as $handler) {
  514. $event->data = $handler[1];
  515. call_user_func($handler[0], $event);
  516. // stop further handling if the event is handled
  517. if ($event->handled) {
  518. return;
  519. }
  520. }
  521. }
  522. // invoke class-level attached handlers
  523. Event::trigger($this, $name, $event);
  524. }
  525. /**
  526. * Returns the named behavior object.
  527. * @param string $name the behavior name
  528. * @return Behavior the behavior object, or null if the behavior does not exist
  529. */
  530. public function getBehavior($name)
  531. {
  532. $this->ensureBehaviors();
  533. return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
  534. }
  535. /**
  536. * Returns all behaviors attached to this component.
  537. * @return Behavior[] list of behaviors attached to this component
  538. */
  539. public function getBehaviors()
  540. {
  541. $this->ensureBehaviors();
  542. return $this->_behaviors;
  543. }
  544. /**
  545. * Attaches a behavior to this component.
  546. * This method will create the behavior object based on the given
  547. * configuration. After that, the behavior object will be attached to
  548. * this component by calling the [[Behavior::attach()]] method.
  549. * @param string $name the name of the behavior.
  550. * @param string|array|Behavior $behavior the behavior configuration. This can be one of the following:
  551. *
  552. * - a [[Behavior]] object
  553. * - a string specifying the behavior class
  554. * - an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
  555. *
  556. * @return Behavior the behavior object
  557. * @see detachBehavior()
  558. */
  559. public function attachBehavior($name, $behavior)
  560. {
  561. $this->ensureBehaviors();
  562. return $this->attachBehaviorInternal($name, $behavior);
  563. }
  564. /**
  565. * Attaches a list of behaviors to the component.
  566. * Each behavior is indexed by its name and should be a [[Behavior]] object,
  567. * a string specifying the behavior class, or an configuration array for creating the behavior.
  568. * @param array $behaviors list of behaviors to be attached to the component
  569. * @see attachBehavior()
  570. */
  571. public function attachBehaviors($behaviors)
  572. {
  573. $this->ensureBehaviors();
  574. foreach ($behaviors as $name => $behavior) {
  575. $this->attachBehaviorInternal($name, $behavior);
  576. }
  577. }
  578. /**
  579. * Detaches a behavior from the component.
  580. * The behavior's [[Behavior::detach()]] method will be invoked.
  581. * @param string $name the behavior's name.
  582. * @return Behavior the detached behavior. Null if the behavior does not exist.
  583. */
  584. public function detachBehavior($name)
  585. {
  586. $this->ensureBehaviors();
  587. if (isset($this->_behaviors[$name])) {
  588. $behavior = $this->_behaviors[$name];
  589. unset($this->_behaviors[$name]);
  590. $behavior->detach();
  591. return $behavior;
  592. } else {
  593. return null;
  594. }
  595. }
  596. /**
  597. * Detaches all behaviors from the component.
  598. */
  599. public function detachBehaviors()
  600. {
  601. $this->ensureBehaviors();
  602. foreach ($this->_behaviors as $name => $behavior) {
  603. $this->detachBehavior($name);
  604. }
  605. }
  606. /**
  607. * Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
  608. */
  609. public function ensureBehaviors()
  610. {
  611. if ($this->_behaviors === null) {
  612. $this->_behaviors = [];
  613. foreach ($this->behaviors() as $name => $behavior) {
  614. $this->attachBehaviorInternal($name, $behavior);
  615. }
  616. }
  617. }
  618. /**
  619. * Attaches a behavior to this component.
  620. * @param string|integer $name the name of the behavior. If this is an integer, it means the behavior
  621. * is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name
  622. * will be detached first.
  623. * @param string|array|Behavior $behavior the behavior to be attached
  624. * @return Behavior the attached behavior.
  625. */
  626. private function attachBehaviorInternal($name, $behavior)
  627. {
  628. if (!($behavior instanceof Behavior)) {
  629. $behavior = Yii::createObject($behavior);
  630. }
  631. if (is_int($name)) {
  632. $behavior->attach($this);
  633. $this->_behaviors[] = $behavior;
  634. } else {
  635. if (isset($this->_behaviors[$name])) {
  636. $this->_behaviors[$name]->detach();
  637. }
  638. $behavior->attach($this);
  639. $this->_behaviors[$name] = $behavior;
  640. }
  641. return $behavior;
  642. }
  643. }