Passed
Pull Request — 2.2 (#20357)
by Wilmer
13:33 queued 05:55
created

Component::hasEventHandlers()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

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