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