Completed
Push — master ( e23c69...c00970 )
by Eric
8s
created

Jarvis::offsetSet()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 16
nc 5
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jarvis;
6
7
use FastRoute\Dispatcher;
8
use Jarvis\Skill\DependencyInjection\Container;
9
use Jarvis\Skill\DependencyInjection\ContainerProvider;
10
use Jarvis\Skill\DependencyInjection\ContainerProviderInterface;
11
use Jarvis\Skill\EventBroadcaster\BroadcasterInterface;
12
use Jarvis\Skill\EventBroadcaster\ControllerEvent;
13
use Jarvis\Skill\EventBroadcaster\EventInterface;
14
use Jarvis\Skill\EventBroadcaster\ExceptionEvent;
15
use Jarvis\Skill\EventBroadcaster\PermanentEventInterface;
16
use Jarvis\Skill\EventBroadcaster\ResponseEvent;
17
use Jarvis\Skill\EventBroadcaster\RunEvent;
18
use Jarvis\Skill\EventBroadcaster\SimpleEvent;
19
use Symfony\Component\HttpFoundation\ParameterBag;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\Response;
22
23
/**
24
 * Jarvis. Minimalist dependency injection container.
25
 *
26
 * @property boolean $debug
27
 * @property Request $request
28
 * @property \Jarvis\Skill\Routing\Router $router
29
 * @property \Symfony\Component\HttpFoundation\Session\Session $session
30
 * @property \Jarvis\Skill\Core\CallbackResolver $callbackResolver
31
 *
32
 * @author Eric Chau <[email protected]>
33
 */
34
class Jarvis extends Container implements BroadcasterInterface
35
{
36
    const DEFAULT_DEBUG = false;
37
    const CONTAINER_PROVIDER_FQCN = ContainerProvider::class;
38
39
    private $receivers = [];
40
    private $permanentEvents = [];
41
    private $computedReceivers = [];
42
    private $masterEmitter = false;
43
    private $masterSet = false;
44
45
    /**
46
     * Creates an instance of Jarvis. It can take settings as first argument.
47
     * List of accepted options:
48
     *   - container_provider (type: string|array): fqcn of your container provider
49
     *
50
     * @param  array $settings Your own settings to modify Jarvis behavior
51
     */
52
    public function __construct(array $settings = [])
53
    {
54
        parent::__construct();
55
56
        $this['settings'] = $settings;
57
        $providers = array_merge([static::CONTAINER_PROVIDER_FQCN], (array) ($settings['providers'] ?? []));
58
        foreach ($providers as $classname) {
59
            $this->hydrate(new $classname());
60
        }
61
    }
62
63
    public function __destruct()
64
    {
65
        $this->masterBroadcast(BroadcasterInterface::TERMINATE_EVENT);
66
    }
67
68
    /**
69
     * This method is an another way to get a locked value.
70
     *
71
     * Example: $this['foo'] is equal to $this->foo, but it ONLY works for locked values.
72
     *
73
     * @param  string $key The key of the locked value
74
     * @return mixed
75
     * @throws \InvalidArgumentException if the requested key is not associated to a locked service
76
     */
77
    public function __get(string $key)
78
    {
79
        if (!isset($this->locked[$key])) {
80
            throw new \InvalidArgumentException(sprintf('"%s" is not a key of a locked value.', $key));
81
        }
82
83
        $this->masterSetter($key, $this[$key]);
84
85
        return $this->$key;
86
    }
87
88
    /**
89
     * Sets new attributes to Jarvis. Note that this method is reserved to Jarvis itself only.
90
     *
91
     * @param string $key   The key name of the new attribute
92
     * @param mixed  $value The value to associate to provided key
93
     * @throws \LogicException if this method is not called by Jarvis itself
94
     */
95
    public function __set(string $key, $value)
96
    {
97
        if (!$this->masterSet) {
98
            throw new \LogicException('You are not allowed to set new attribute into Jarvis.');
99
        }
100
101
        $this->$key = $value;
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107
    public function offsetSet($id, $v): void
108
    {
109
        parent::offsetSet($id, $v);
110
111
        if (!($v instanceof \Closure)) {
112
            return;
113
        }
114
115
        $refMethod = new \ReflectionMethod($v, '__invoke');
116
        if (null === $returntype = $refMethod->getReturnType()) {
117
            return;
118
        }
119
120
        $alias = $returntype->getName();
121
        if (
122
            $alias === $id
123
            || (!class_exists($alias) && !interface_exists($alias))
124
        ) {
125
            return;
126
        }
127
128
        if (!isset($this[$alias])) {
129
            $this->alias($alias, $id);
130
        } else {
131
            unset($this[$alias]);
132
        }
133
    }
134
135
    /**
136
     * @param  Request|null $request
137
     * @return Response
138
     */
139
    public function run(Request $request = null): Response
140
    {
141
        $request = $request ?? $this['request'];
142
        $event = null;
143
144
        try {
145
            $this->masterBroadcast(BroadcasterInterface::RUN_EVENT, $event = new RunEvent($request));
146
            if ($response = $event->response()) {
147
                return $response;
148
            }
149
150
            [$callback, $arguments] = $this['router']->match($request->getMethod(), $request->getPathInfo());
0 ignored issues
show
Bug introduced by
The variable $callback does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $arguments does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
151
            $event = new ControllerEvent($this['callbackResolver']->resolve($callback), $arguments);
152
            $this->masterBroadcast(BroadcasterInterface::CONTROLLER_EVENT, $event);
153
154
            $response = call_user_func_array($event->callback(), $event->arguments());
155
            $event = new ResponseEvent($request, $response);
156
            $this->masterBroadcast(BroadcasterInterface::RESPONSE_EVENT, $event);
157
        } catch (\Throwable $throwable) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
158
            $event = new ExceptionEvent($throwable);
159
            $this->masterBroadcast(BroadcasterInterface::EXCEPTION_EVENT, $event);
160
        }
161
162
        return $event->response();
163
    }
164
165
    /**
166
     * {@inheritdoc}
167
     */
168
    public function on(string $name, $receiver, int $priority = BroadcasterInterface::RECEIVER_NORMAL_PRIORITY): Jarvis
169
    {
170
        if (!isset($this->receivers[$name])) {
171
            $this->receivers[$name] = [
172
                BroadcasterInterface::RECEIVER_LOW_PRIORITY    => [],
173
                BroadcasterInterface::RECEIVER_NORMAL_PRIORITY => [],
174
                BroadcasterInterface::RECEIVER_HIGH_PRIORITY   => [],
175
            ];
176
        }
177
178
        $this->receivers[$name][$priority][] = $receiver;
179
        $this->computedReceivers[$name] = null;
180
        if (isset($this->permanentEvents[$name])) {
181
            $name = $this->permanentEvents[$name];
182
            call_user_func_array($this['callbackResolver']->resolve($receiver), [$name]);
183
        }
184
185
        return $this;
186
    }
187
188
    /**
189
     * {@inheritdoc}
190
     */
191
    public function broadcast(string $name, EventInterface $event = null): Jarvis
192
    {
193
        if (!$this->masterEmitter && in_array($name, BroadcasterInterface::RESERVED_EVENT_NAMES)) {
194
            throw new \LogicException(sprintf(
195
                'You\'re trying to broadcast "$name" but "%s" are reserved event names.',
196
                implode('|', BroadcasterInterface::RESERVED_EVENT_NAMES)
197
            ));
198
        }
199
200
        if (isset($this->permanentEvents[$name])) {
201
            throw new \LogicException('Permanent event cannot be broadcasted multiple times.');
202
        }
203
204
        $event = $event ?? new SimpleEvent();
205
        if ($event instanceof PermanentEventInterface && $event->isPermanent()) {
206
            $this->permanentEvents[$name] = $event;
207
        }
208
209
        if (isset($this->receivers[$name])) {
210
            foreach ($this->buildEventReceivers($name) as $receiver) {
211
                call_user_func_array($this['callbackResolver']->resolve($receiver), [$event]);
212
                if ($event->isPropagationStopped()) {
213
                    break;
214
                }
215
            }
216
        }
217
218
        return $this;
219
    }
220
221
    /**
222
     * @param  ContainerProviderInterface $provider
223
     * @return self
224
     */
225
    public function hydrate(ContainerProviderInterface $provider): Jarvis
226
    {
227
        $provider->hydrate($this);
228
229
        return $this;
230
    }
231
232
    /**
233
     * Enables master emitter mode.
234
     *
235
     * @return self
236
     */
237
    private function masterBroadcast(string $name, EventInterface $event = null): Jarvis
238
    {
239
        $this->masterEmitter = true;
240
        $this->broadcast($name, $event);
241
        $this->masterEmitter = false;
242
243
        return $this;
244
    }
245
246
    /**
247
     * Sets new attribute into Jarvis.
248
     *
249
     * @param  string $key   The name of the new attribute
250
     * @param  mixed  $value The value of the new attribute
251
     * @return self
252
     */
253
    private function masterSetter(string $key, $value): Jarvis
254
    {
255
        $this->masterSet = true;
256
        $this->$key = $value;
257
        $this->masterSet = false;
258
259
        return $this;
260
    }
261
262
    /**
263
     * Builds and returns well ordered receivers collection that match with provided event name.
264
     *
265
     * @param  string $name The event name we want to get its receivers
266
     * @return array
267
     */
268
    private function buildEventReceivers(string $name): array
269
    {
270
        return $this->computedReceivers[$name] = $this->computedReceivers[$name] ?? array_merge(
271
            $this->receivers[$name][BroadcasterInterface::RECEIVER_HIGH_PRIORITY],
272
            $this->receivers[$name][BroadcasterInterface::RECEIVER_NORMAL_PRIORITY],
273
            $this->receivers[$name][BroadcasterInterface::RECEIVER_LOW_PRIORITY]
274
        );
275
    }
276
}
277