Component.php 28 KB

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