Events::on()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 8
rs 9.4286
cc 2
eloc 4
nc 2
nop 4
1
<?php
2
/**
3
 * Scabbia2 Events Component
4
 * https://github.com/eserozvataf/scabbia2
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 *
9
 * @link        https://github.com/eserozvataf/scabbia2-events for the canonical source repository
10
 * @copyright   2010-2016 Eser Ozvataf. (http://eser.ozvataf.com/)
11
 * @license     http://www.apache.org/licenses/LICENSE-2.0 - Apache License, Version 2.0
12
 */
13
14
namespace Scabbia\Events;
15
16
use Scabbia\Events\Delegate;
17
18
/**
19
 * Events
20
 *
21
 * @package     Scabbia\Events
22
 * @author      Eser Ozvataf <[email protected]>
23
 * @since       1.0.0
24
 */
25
class Events
26
{
27
    /** @type array      event delegates */
28
    public $delegates = [];
29
    /** @type array      event depth */
30
    public $eventDepth = [];
31
    /** @type bool       indicates the event manager is currently disabled or not */
32
    public $disabled = false;
33
34
35
    /**
36
     * Dispatches an event
37
     *
38
     * @param string     $uEvent     name of the event
39
     * @param array      $uEventArgs arguments for the event
40
     *
41
     * @return void
42
     */
43
    public function dispatch($uEvent, ...$uEventArgs)
44
    {
45
        if ($this->disabled) {
46
            return;
47
        }
48
49
        if (!isset($this->delegates[$uEvent])) {
50
            return;
51
        }
52
53
        $this->eventDepth[] = [$uEvent, $uEventArgs];
54
        $this->delegates[$uEvent]->invoke(...$uEventArgs);
55
        array_pop($this->eventDepth);
56
    }
57
58
    /**
59
     * Subscribes a callback method to specified event
60
     *
61
     * @param string   $uEvent    event
62
     * @param callable $uCallback callback
63
     * @param mixed    $uState    state object
64
     * @param null|int $uPriority priority
65
     *
66
     * @return void
67
     */
68
    public function on($uEvent, $uCallback, $uState = null, $uPriority = null)
69
    {
70
        if (!isset($this->delegates[$uEvent])) {
71
            $this->delegates[$uEvent] = new Delegate();
72
        }
73
74
        $this->delegates[$uEvent]->subscribe($uCallback, $uState, $uPriority);
75
    }
76
}
77