Completed
Branch 4.0 (52c68b)
by Marc André
02:54
created

Events::prioritySort()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 3
eloc 4
nc 3
nop 2
1
<?php
2
3
4
/**
5
 *
6
 * Copyright (c) 2010-2016 Nevraxe inc. & Marc André Audet <[email protected]>. All rights reserved.
7
 *
8
 * Redistribution and use in source and binary forms, with or without modification, are
9
 * permitted provided that the following conditions are met:
10
 *
11
 *   1. Redistributions of source code must retain the above copyright notice, this list of
12
 *       conditions and the following disclaimer.
13
 *
14
 *   2. Redistributions in binary form must reproduce the above copyright notice, this list
15
 *       of conditions and the following disclaimer in the documentation and/or other materials
16
 *       provided with the distribution.
17
 *
18
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
 * DISCLAIMED. IN NO EVENT SHALL MARC ANDRÉ "MANHIM" AUDET BE LIABLE FOR ANY
22
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 *
29
 */
30
31
32
namespace Cervo\Libraries;
33
34
35
use Cervo\Core as _;
36
37
38
/**
39
 * Events manager for Cervo.
40
 *
41
 * @author Marc André Audet <[email protected]>
42
 */
43
class Events
44
{
45
    /**
46
     * Holds all the events and their callbacks.
47
     * @var array
48
     */
49
    protected $events = [];
50
51
    /**
52
     * True while an event is fired.
53
     * @var string|bool
54
     */
55
    protected $inProgress = false;
56
57
    /**
58
     * Custom sort for priority.
59
     *
60
     * @param array $a
61
     * @param array $b
62
     *
63
     * @return int
64
     */
65
    public static function prioritySort($a, $b)
66
    {
67
        if ($a['priority'] == $b['priority']) {
68
            return 0;
69
        }
70
71
        return $a['priority'] < $b['priority'] ? -1 : 1;
72
    }
73
74
    /**
75
     * Include all the events files that may register and/or hook to events.
76
     */
77
    public function __construct()
78
    {
79
        $config = _::getLibrary('Cervo/Config');
80
81 View Code Duplication
        foreach (glob($config->get('Cervo/Application/Directory') . '*' . \DS . $config->get('Cervo/Application/EventsPath') . '*.php', \GLOB_NOSORT | \GLOB_NOESCAPE) as $file) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
82
83
            $function = require $file;
84
85
            if (is_callable($function)) {
86
                $function($this);
87
            }
88
89
        }
90
    }
91
92
    /**
93
     * Register a new event.
94
     *
95
     * @param string $name
96
     *
97
     * @return bool
98
     */
99
    public function register($name)
100
    {
101
        if ($this->isRegistered($name)) {
102
            return false;
103
        }
104
105
        $this->events[$name] = [];
106
107
        return true;
108
    }
109
110
    /**
111
     * Check if the event exists by it's name.
112
     *
113
     * @param string $name
114
     *
115
     * @return bool
116
     */
117
    public function isRegistered($name)
118
    {
119
        return isset($this->events[$name]);
120
    }
121
122
    /**
123
     * Remove an event and un-hook everything related to it.
124
     *
125
     * @param string $name
126
     */
127
    public function unregister($name)
128
    {
129
        unset($this->events[$name]);
130
    }
131
132
    /**
133
     * Hook a callable to an event.
134
     * If the event is not registered, register it.
135
     *
136
     * @param string $name
137
     * @param callable $call
138
     * @param int $priority
139
     *
140
     * @return bool
141
     */
142
    public function hook($name, $call, $priority = 0)
143
    {
144
        if (!$this->isRegistered($name)) {
145
            $this->register($name);
146
        }
147
148
        $this->events[$name][] = [
149
            'call' => $call,
150
            'priority' => $priority
151
        ];
152
153
        return true;
154
    }
155
156
    /**
157
     * Fire an event and call all the hooked callables.
158
     *
159
     * @param string $name
160
     * @param array $params
161
     *
162
     * @return bool
163
     */
164
    public function fire($name, $params = [])
165
    {
166
        if (!is_array($params) || !$this->isRegistered($name)) {
167
            return false;
168
        }
169
170
        $this->inProgress = $name;
171
172
        usort($this->events[$name], '\\' . __CLASS__ . '::prioritySort');
173
174
        foreach ($this->events[$name] as $call) {
175
            call_user_func($call['call'], $name, $params);
176
        }
177
178
        $this->inProgress = false;
179
180
        return true;
181
    }
182
183
    /**
184
     * Returns the name of the event being fired, false otherwise.
185
     *
186
     * @return string|bool
187
     */
188
    public function isInProgress()
189
    {
190
        return $this->inProgress;
191
    }
192
}
193