Completed
Pull Request — master (#67)
by Eric
02:05
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\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\BroadcasterTrait;
12
use Jarvis\Skill\EventBroadcaster\ControllerEvent;
13
use Jarvis\Skill\EventBroadcaster\EventInterface;
14
use Jarvis\Skill\EventBroadcaster\ExceptionEvent;
15
use Jarvis\Skill\EventBroadcaster\ResponseEvent;
16
use Jarvis\Skill\EventBroadcaster\RunEvent;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Response;
19
20
/**
21
 * Jarvis. Minimalist dependency injection container.
22
 *
23
 * @property bool                                              $debug
24
 * @property Request                                           $request
25
 * @property \Jarvis\Skill\Routing\Router                      $router
26
 * @property \Symfony\Component\HttpFoundation\Session\Session $session
27
 * @property \Jarvis\Skill\Core\CallbackResolver               $callbackResolver
28
 *
29
 * @author Eric Chau <[email protected]>
30
 */
31
class Jarvis extends Container implements BroadcasterInterface
32
{
33
    use BroadcasterTrait {
34
        broadcast as traitBroadcast;
35
    }
36
37
    const DEFAULT_DEBUG = false;
38
    const CONTAINER_PROVIDER_FQCN = ContainerProvider::class;
39
40
    private $masterSetter = false;
41
42
    /**
43
     * Creates an instance of Jarvis. It can take settings as first argument.
44
     * List of accepted options:
45
     *   - providers (type: string|array): fqcn of your container provider
46
     *   - extra
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 (array_unique($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($key, $this[$key]);
82
83
        return $this->$key;
84
    }
85
86
    /**
87
     * Sets new attributes to Jarvis. Note that this method is reserved to Jarvis itself only.
88
     *
89
     * @param string $key   The key name of the new attribute
90
     * @param mixed  $value The value to associate to provided key
91
     * @throws \LogicException if this method is not called by Jarvis itself
92
     */
93
    public function __set(string $key, $value)
94
    {
95
        if (!$this->masterSetter) {
96
            throw new \LogicException('You are not allowed to set new attribute into Jarvis.');
97
        }
98
99
        $this->$key = $value;
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105
    public function offsetSet($id, $v): void
106
    {
107
        parent::offsetSet($id, $v);
108
109
        if (!($v instanceof \Closure)) {
110
            return;
111
        }
112
113
        $refMethod = new \ReflectionMethod($v, '__invoke');
114
        if (null === $returntype = $refMethod->getReturnType()) {
115
            return;
116
        }
117
118
        $alias = $returntype->getName();
119
        if (
120
            $alias === $id
121
            || (!class_exists($alias) && !interface_exists($alias))
122
        ) {
123
            return;
124
        }
125
126
        if (!isset($this[$alias])) {
127
            $this->alias($alias, $id);
128
        } else {
129
            unset($this[$alias]);
130
        }
131
    }
132
133
134
    /**
135
     * @param  ContainerProviderInterface $provider
136
     */
137
    public function hydrate(ContainerProviderInterface $provider): void
138
    {
139
        $provider->hydrate($this);
140
    }
141
142
    /**
143
     * @param  Request|null $request
144
     * @return Response
145
     */
146
    public function run(Request $request = null): Response
147
    {
148
        $request = $request ?? $this['request'];
149
        $event = $event = new RunEvent($request);
150
151
        try {
152
            $this->masterBroadcast(BroadcasterInterface::RUN_EVENT, $event);
153
            if ($response = $event->response()) {
154
                return $response;
155
            }
156
157
            [$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...
158
            $event = new ControllerEvent($this['callbackResolver']->resolve($callback), $arguments);
159
            $this->masterBroadcast(BroadcasterInterface::CONTROLLER_EVENT, $event);
160
161
            $response = $this['callbackResolver']->resolveAndCall($event->callback(), $event->arguments());
162
            $event = new ResponseEvent($request, $response);
163
            $this->masterBroadcast(BroadcasterInterface::RESPONSE_EVENT, $event);
164
        } catch (\Throwable $throwable) {
165
            $event = new ExceptionEvent($throwable);
166
            $this->masterBroadcast(BroadcasterInterface::EXCEPTION_EVENT, $event);
167
        }
168
169
        return $event->response();
170
    }
171
172
    /**
173
     * {@inheritdoc}
174
     */
175
    public function broadcast(string $name, EventInterface $event = null): void
176
    {
177
        if (!$this->masterEmitter && in_array($name, BroadcasterInterface::RESERVED_EVENT_NAMES)) {
178
            throw new \LogicException(sprintf(
179
                'You\'re trying to broadcast "$name" but "%s" are reserved event names.',
180
                implode('|', BroadcasterInterface::RESERVED_EVENT_NAMES)
181
            ));
182
        }
183
184
        $this->traitBroadcast($name, $event);
185
    }
186
187
    /**
188
     * Sets new attribute into Jarvis.
189
     *
190
     * @param  string $key   The name of the new attribute
191
     * @param  mixed  $value The value of the new attribute
192
     */
193
    private function masterSet(string $key, $value): void
194
    {
195
        $this->masterSetter = true;
196
        $this->$key = $value;
197
        $this->masterSetter = false;
198
    }
199
200
    /**
201
     * Enables master emitter mode.
202
     */
203
    private function masterBroadcast(string $name, EventInterface $event = null): void
204
    {
205
        $this->masterEmitter = true;
206
        $this->broadcast($name, $event);
207
        $this->masterEmitter = false;
208
    }
209
}
210