Completed
Push — master ( a40d75...04d300 )
by Eric
12s
created

Jarvis::masterSet()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jarvis;
6
7
use Jarvis\Skill\Core\CallbackResolver;
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\BroadcasterTrait;
13
use Jarvis\Skill\EventBroadcaster\ControllerEvent;
14
use Jarvis\Skill\EventBroadcaster\EventInterface;
15
use Jarvis\Skill\EventBroadcaster\ExceptionEvent;
16
use Jarvis\Skill\EventBroadcaster\ResponseEvent;
17
use Jarvis\Skill\EventBroadcaster\RunEvent;
18
use Jarvis\Skill\Routing\Router;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpFoundation\Response;
21
22
/**
23
 * Jarvis. Minimalist dependency injection container.
24
 *
25
 * @property bool                                              $debug
26
 * @property Router                                            $router
27
 * @property Request                                           $request
28
 * @property \Symfony\Component\HttpFoundation\Session\Session $session
29
 * @property CallbackResolver                                  $callbackResolver
30
 *
31
 * @author Eric Chau <[email protected]>
32
 */
33
class Jarvis extends Container implements BroadcasterInterface
34
{
35
    use BroadcasterTrait {
36
        broadcast as traitBroadcast;
37
    }
38
39
    const DEFAULT_DEBUG = false;
40
    const CONTAINER_PROVIDER_FQCN = ContainerProvider::class;
41
42
    private $masterSetter = false;
43
44
    /**
45
     * Creates an instance of Jarvis. It can take settings as first argument.
46
     * List of accepted options:
47
     *   - providers (type: string|array): fqcn of your container provider
48
     *   - extra
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 (array_unique($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->masterSet($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->masterSetter) {
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
    /**
137
     * @param  ContainerProviderInterface $provider
138
     */
139
    public function hydrate(ContainerProviderInterface $provider): void
140
    {
141
        $provider->hydrate($this);
142
    }
143
144
    /**
145
     * @param  Request|null $request
146
     * @return Response
147
     */
148
    public function run(Request $request = null): Response
149
    {
150
        $request = $request ?? $this[Request::class];
151
        $event = $event = new RunEvent($request);
152
153
        try {
154
            $this->masterBroadcast(BroadcasterInterface::RUN_EVENT, $event);
155
            if ($response = $event->response()) {
156
                return $response;
157
            }
158
159
            [$callback, $arguments] = $this[Router::class]->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...
160
            $event = new ControllerEvent($this[CallbackResolver::class]->resolveReference($callback), $arguments);
161
            $this->masterBroadcast(BroadcasterInterface::CONTROLLER_EVENT, $event);
162
163
            $response = call_user_func_array($event->callback(), $event->arguments());
164
            $event = new ResponseEvent($request, $response);
165
            $this->masterBroadcast(BroadcasterInterface::RESPONSE_EVENT, $event);
166
        } catch (\Throwable $throwable) {
167
            $event = new ExceptionEvent($throwable);
168
            $this->masterBroadcast(BroadcasterInterface::EXCEPTION_EVENT, $event);
169
        }
170
171
        return $event->response();
172
    }
173
174
    /**
175
     * {@inheritdoc}
176
     */
177
    public function broadcast(string $name, EventInterface $event = null): void
178
    {
179
        if (!$this->masterEmitter && in_array($name, BroadcasterInterface::RESERVED_EVENT_NAMES)) {
180
            throw new \LogicException(sprintf(
181
                'You\'re trying to broadcast "$name" but "%s" are reserved event names.',
182
                implode('|', BroadcasterInterface::RESERVED_EVENT_NAMES)
183
            ));
184
        }
185
186
        $this->traitBroadcast($name, $event);
187
    }
188
189
    /**
190
     * {@inheritdoc}
191
     */
192
    protected function runReceiverCallback($receiver, EventInterface $event)
193
    {
194
        $this[CallbackResolver::class]->resolveAndCall($receiver, ['event' => $event]);
195
    }
196
197
    /**
198
     * Sets new attribute into Jarvis.
199
     *
200
     * @param  string $key   The name of the new attribute
201
     * @param  mixed  $value The value of the new attribute
202
     */
203
    private function masterSet(string $key, $value): void
204
    {
205
        $this->masterSetter = true;
206
        $this->$key = $value;
207
        $this->masterSetter = false;
208
    }
209
210
    /**
211
     * Enables master emitter mode.
212
     */
213
    private function masterBroadcast(string $name, EventInterface $event = null): void
214
    {
215
        $this->masterEmitter = true;
216
        $this->broadcast($name, $event);
217
        $this->masterEmitter = false;
218
    }
219
}
220