Component.php 27 KB

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