Completed
Pull Request — master (#66)
by Eric
03:42
created

Jarvis::masterSetter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jarvis;
6
7
use Jarvis\Skill\DependencyInjection\Container;
8
use Jarvis\Skill\DependencyInjection\ContainerProvider;
9
use Jarvis\Skill\DependencyInjection\ContainerProviderInterface;
10
use Jarvis\Skill\EventBroadcaster\BroadcasterInterface;
11
use Jarvis\Skill\EventBroadcaster\ControllerEvent;
12
use Jarvis\Skill\EventBroadcaster\EventInterface;
13
use Jarvis\Skill\EventBroadcaster\ExceptionEvent;
14
use Jarvis\Skill\EventBroadcaster\PermanentEventInterface;
15
use Jarvis\Skill\EventBroadcaster\ResponseEvent;
16
use Jarvis\Skill\EventBroadcaster\RunEvent;
17
use Jarvis\Skill\EventBroadcaster\SimpleEvent;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpFoundation\Response;
20
21
/**
22
 * Jarvis. Minimalist dependency injection container.
23
 *
24
 * @property boolean $debug
25
 * @property Request $request
26
 * @property \Jarvis\Skill\Routing\Router $router
27
 * @property \Symfony\Component\HttpFoundation\Session\Session $session
28
 * @property \Jarvis\Skill\Core\CallbackResolver $callbackResolver
29
 *
30
 * @author Eric Chau <[email protected]>
31
 */
32
class Jarvis extends Container implements BroadcasterInterface
33
{
34
    const DEFAULT_DEBUG = false;
35
    const CONTAINER_PROVIDER_FQCN = ContainerProvider::class;
36
37
    private $receivers = [];
38
    private $permanentEvents = [];
39
    private $computedReceivers = [];
40
    private $masterEmitter = false;
41
    private $masterSet = false;
42
43
    /**
44
     * Creates an instance of Jarvis. It can take settings as first argument.
45
     * List of accepted options:
46
     *   - container_provider (type: string|array): fqcn of your container provider
47
     *
48
     * @param  array $settings Your own settings to modify Jarvis behavior
49
     */
50
    public function __construct(array $settings = [])
51
    {
52
        parent::__construct();
53
54
        $this['settings'] = $settings;
55
        $providers = array_merge([static::CONTAINER_PROVIDER_FQCN], (array) ($settings['providers'] ?? []));
56
        foreach ($providers as $classname) {
57
            $this->hydrate(new $classname());
58
        }
59
    }
60
61
    public function __destruct()
62
    {
63
        $this->masterBroadcast(BroadcasterInterface::TERMINATE_EVENT);
64
    }
65
66
    /**
67
     * This method is an another way to get a locked value.
68
     *
69
     * Example: $this['foo'] is equal to $this->foo, but it ONLY works for locked values.
70
     *
71
     * @param  string $key The key of the locked value
72
     * @return mixed
73
     * @throws \InvalidArgumentException if the requested key is not associated to a locked service
74
     */
75
    public function __get(string $key)
76
    {
77
        if (!isset($this->locked[$key])) {
78
            throw new \InvalidArgumentException(sprintf('"%s" is not a key of a locked value.', $key));
79
        }
80
81
        $this->masterSet = true;
82
        $this->$key = $this[$key];
83
        $this->masterSet = false;
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 = $event = new RunEvent($request);
143
144
        try {
145
            $this->masterBroadcast(BroadcasterInterface::RUN_EVENT, $event);
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 = $this['callbackResolver']->resolveAndCall($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): void
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
            $this['callbackResolver']->resolveAndCall($receiver, [
182
                'event' => $this->permanentEvents[$name],
183
            ]);
184
        }
185
    }
186
187
    /**
188
     * {@inheritdoc}
189
     */
190
    public function broadcast(string $name, EventInterface $event = null): void
191
    {
192
        if (!$this->masterEmitter && in_array($name, BroadcasterInterface::RESERVED_EVENT_NAMES)) {
193
            throw new \LogicException(sprintf(
194
                'You\'re trying to broadcast "$name" but "%s" are reserved event names.',
195
                implode('|', BroadcasterInterface::RESERVED_EVENT_NAMES)
196
            ));
197
        }
198
199
        if (isset($this->permanentEvents[$name])) {
200
            throw new \LogicException('Permanent event cannot be broadcasted multiple times.');
201
        }
202
203
        $event = $event ?? new SimpleEvent();
204
        if ($event instanceof PermanentEventInterface && $event->isPermanent()) {
205
            $this->permanentEvents[$name] = $event;
206
        }
207
208
        if (isset($this->receivers[$name])) {
209
            foreach ($this->buildEventReceivers($name) as $receiver) {
210
                $this['callbackResolver']->resolveAndCall($receiver, [
211
                    'event' => $event,
212
                ]);
213
                if ($event->isPropagationStopped()) {
214
                    break;
215
                }
216
            }
217
        }
218
    }
219
220
    /**
221
     * @param  ContainerProviderInterface $provider
222
     */
223
    public function hydrate(ContainerProviderInterface $provider): void
224
    {
225
        $provider->hydrate($this);
226
    }
227
228
    /**
229
     * Enables master emitter mode.
230
     */
231
    private function masterBroadcast(string $name, EventInterface $event = null): void
232
    {
233
        $this->masterEmitter = true;
234
        $this->broadcast($name, $event);
235
        $this->masterEmitter = false;
236
    }
237
238
    /**
239
     * Builds and returns well ordered receivers collection that match with provided event name.
240
     *
241
     * @param  string $name The event name we want to get its receivers
242
     * @return array
243
     */
244
    private function buildEventReceivers(string $name): array
245
    {
246
        return $this->computedReceivers[$name] = $this->computedReceivers[$name] ?? array_merge(
247
            $this->receivers[$name][BroadcasterInterface::RECEIVER_HIGH_PRIORITY],
248
            $this->receivers[$name][BroadcasterInterface::RECEIVER_NORMAL_PRIORITY],
249
            $this->receivers[$name][BroadcasterInterface::RECEIVER_LOW_PRIORITY]
250
        );
251
    }
252
}
253