Component.php 28 KB

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