Passed
Push — master ( 2679fa...d40e27 )
by Jesús
01:00 queued 13s
created

SetupGacela   C

Complexity

Total Complexity 54

Size/Duplication

Total Lines 460
Duplicated Lines 0 %

Test Coverage

Coverage 98.87%

Importance

Changes 9
Bugs 1 Features 0
Metric Value
eloc 152
dl 0
loc 460
ccs 175
cts 177
cp 0.9887
rs 6.4799
c 9
b 1
f 0
wmc 54

43 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A fromGacelaConfig() 0 18 1
A fromCallable() 0 6 1
A setExternalServices() 0 6 1
A fromFile() 0 13 3
A markPropertyChanged() 0 3 1
A setGenericListeners() 0 5 1
A setSuffixTypesBuilder() 0 5 1
A setAreEventListenersEnabled() 0 5 1
A setServicesToExtend() 0 6 1
A getFileCacheDirectory() 0 3 1
A getConfigKeyValues() 0 3 1
A hasEventListeners() 0 4 2
A buildConfig() 0 9 2
A setFileCacheEnabled() 0 6 1
A isFileCacheEnabled() 0 3 1
A setConfigBuilder() 0 5 1
A isPropertyChanged() 0 3 1
A setMappingInterfacesBuilder() 0 5 1
A addServicesToExtend() 0 9 1
A combineConfigKeyValues() 0 3 1
A setSuffixTypesFn() 0 5 1
A buildMappingInterfaces() 0 14 2
A combineProjectNamespaces() 0 3 1
A getSpecificListeners() 0 3 1
A setMappingInterfacesFn() 0 5 1
A setConfigKeyValues() 0 6 1
A getEventDispatcher() 0 20 5
A getProjectNamespaces() 0 3 1
A setSpecificListeners() 0 5 1
A canCreateEventDispatcher() 0 4 2
A setShouldResetInMemoryCache() 0 6 1
A shouldResetInMemoryCache() 0 3 1
A getGenericListeners() 0 3 1
A setConfigFn() 0 5 1
A externalServices() 0 3 1
A setFileCacheDirectory() 0 6 1
A combine() 0 3 1
A getServicesToExtend() 0 3 1
A setEventDispatcher() 0 5 1
A combineExternalServices() 0 3 1
A setProjectNamespaces() 0 6 1
A buildSuffixTypes() 0 9 2

How to fix   Complexity   

Complex Class

Complex classes like SetupGacela often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SetupGacela, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework\Bootstrap;
6
7
use Closure;
8
use Gacela\Framework\ClassResolver\Cache\GacelaFileCache;
9
use Gacela\Framework\Config\GacelaConfigBuilder\ConfigBuilder;
10
use Gacela\Framework\Config\GacelaConfigBuilder\MappingInterfacesBuilder;
11
use Gacela\Framework\Config\GacelaConfigBuilder\SuffixTypesBuilder;
12
use Gacela\Framework\Event\Dispatcher\ConfigurableEventDispatcher;
13
use Gacela\Framework\Event\Dispatcher\EventDispatcherInterface;
14
use Gacela\Framework\Event\Dispatcher\NullEventDispatcher;
15
use RuntimeException;
16
17
use function is_callable;
18
19
/**
20
 * @psalm-suppress ArgumentTypeCoercion,MixedArgumentTypeCoercion
21
 */
22
final class SetupGacela extends AbstractSetupGacela
23
{
24
    public const shouldResetInMemoryCache = 'shouldResetInMemoryCache';
25
    public const fileCacheEnabled = 'fileCacheEnabled';
26
    public const fileCacheDirectory = 'fileCacheDirectory';
27
    public const externalServices = 'externalServices';
28
    public const projectNamespaces = 'projectNamespaces';
29
    public const configKeyValues = 'configKeyValues';
30
    public const servicesToExtend = 'servicesToExtend';
31
32
    private const DEFAULT_ARE_EVENT_LISTENERS_ENABLED = true;
33
    private const DEFAULT_SHOULD_RESET_IN_MEMORY_CACHE = false;
34
    private const DEFAULT_FILE_CACHE_ENABLED = GacelaFileCache::DEFAULT_ENABLED_VALUE;
35
    private const DEFAULT_FILE_CACHE_DIRECTORY = GacelaFileCache::DEFAULT_DIRECTORY_VALUE;
36
    private const DEFAULT_PROJECT_NAMESPACES = [];
37
    private const DEFAULT_CONFIG_KEY_VALUES = [];
38
    private const DEFAULT_GENERIC_LISTENERS = [];
39
    private const DEFAULT_SPECIFIC_LISTENERS = [];
40
    private const DEFAULT_SERVICES_TO_EXTEND = [];
41
42
    /** @var callable(ConfigBuilder):void */
43
    private $configFn;
44
45
    /** @var callable(MappingInterfacesBuilder,array<string,mixed>):void */
46
    private $mappingInterfacesFn;
47
48
    /** @var callable(SuffixTypesBuilder):void */
49
    private $suffixTypesFn;
50
51
    /** @var ?array<string,class-string|object|callable> */
52
    private ?array $externalServices = null;
53
54
    private ?ConfigBuilder $configBuilder = null;
55
56
    private ?SuffixTypesBuilder $suffixTypesBuilder = null;
57
58
    private ?MappingInterfacesBuilder $mappingInterfacesBuilder = null;
59
60
    private ?bool $shouldResetInMemoryCache = null;
61
62
    private ?bool $fileCacheEnabled = null;
63
64
    private ?string $fileCacheDirectory = null;
65
66
    /** @var ?list<string> */
67
    private ?array $projectNamespaces = null;
68
69
    /** @var ?array<string,mixed> */
70
    private ?array $configKeyValues = null;
71
72
    private ?bool $areEventListenersEnabled = null;
73
74
    /** @var ?list<callable> */
75
    private ?array $genericListeners = null;
76
77 103
    /** @var ?array<class-string,list<callable>> */
78
    private ?array $specificListeners = null;
79 103
80
    private ?EventDispatcherInterface $eventDispatcher = null;
81 103
82
    /** @var ?array<string,bool> */
83 103
    private ?array $changedProperties = null;
84
85
    /** @var ?array<string,list<Closure>> */
1 ignored issue
show
Documentation Bug introduced by
The doc comment ?array<string,list<Closure>> at position 4 could not be parsed: Expected '>' at position 4, but found 'list'.
Loading history...
86
    private ?array $servicesToExtend = null;
87 10
88
    public function __construct()
89 10
    {
90
        $emptyFn = static function (): void {
91
        };
92
93
        $this->configFn = $emptyFn;
94 10
        $this->mappingInterfacesFn = $emptyFn;
95 10
        $this->suffixTypesFn = $emptyFn;
96
    }
97
98
    public static function fromFile(string $gacelaFilePath): self
99 10
    {
100
        if (!is_file($gacelaFilePath)) {
101
            throw new RuntimeException("Invalid file path: '{$gacelaFilePath}'");
102
        }
103
104
        /** @var callable(GacelaConfig):void|null $setupGacelaFileFn */
105 55
        $setupGacelaFileFn = include $gacelaFilePath;
106
        if (!is_callable($setupGacelaFileFn)) {
107 55
            return new self();
108 55
        }
109
110 55
        return self::fromCallable($setupGacelaFileFn);
111
    }
112
113 72
    /**
114
     * @param callable(GacelaConfig):void $setupGacelaFileFn
115 72
     */
116
    public static function fromCallable(callable $setupGacelaFileFn): self
117 72
    {
118 72
        $gacelaConfig = new GacelaConfig();
119 72
        $setupGacelaFileFn($gacelaConfig);
120 72
121 72
        return self::fromGacelaConfig($gacelaConfig);
122 72
    }
123 72
124 72
    public static function fromGacelaConfig(GacelaConfig $gacelaConfig): self
125 72
    {
126 72
        $build = $gacelaConfig->build();
127 72
128 72
        return (new self())
129 72
            ->setExternalServices($build['external-services'])
130 72
            ->setConfigBuilder($build['config-builder'])
131
            ->setSuffixTypesBuilder($build['suffix-types-builder'])
132
            ->setMappingInterfacesBuilder($build['mapping-interfaces-builder'])
133 72
            ->setShouldResetInMemoryCache($build['should-reset-in-memory-cache'])
134
            ->setFileCacheEnabled($build['file-cache-enabled'])
135 72
            ->setFileCacheDirectory($build['file-cache-directory'])
136 72
            ->setProjectNamespaces($build['project-namespaces'])
137
            ->setConfigKeyValues($build['config-key-values'])
138 72
            ->setAreEventListenersEnabled($build['are-event-listeners-enabled'])
139
            ->setGenericListeners($build['generic-listeners'])
140
            ->setSpecificListeners($build['specific-listeners'])
141 72
            ->setServicesToExtend($build['services-to-extend']);
142
    }
143 72
144 72
    /**
145
     * @param array<string,class-string|object|callable> $array
1 ignored issue
show
Documentation Bug introduced by
The doc comment array<string,class-string|object|callable> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<string,class-string|object|callable>.
Loading history...
146 72
     */
147
    public function setExternalServices(array $array): self
148
    {
149 72
        $this->markPropertyChanged(self::externalServices, true);
150
        $this->externalServices = $array;
151 72
152 72
        return $this;
153
    }
154 72
155
    public function setConfigBuilder(ConfigBuilder $builder): self
156
    {
157
        $this->configBuilder = $builder;
158
159
        return $this;
160 3
    }
161
162 3
    public function setSuffixTypesBuilder(SuffixTypesBuilder $builder): self
163 3
    {
164
        $this->suffixTypesBuilder = $builder;
165 3
166
        return $this;
167
    }
168 94
169
    public function setMappingInterfacesBuilder(MappingInterfacesBuilder $builder): self
170 94
    {
171 63
        $this->mappingInterfacesBuilder = $builder;
172
173
        return $this;
174 94
    }
175
176 94
    /**
177
     * @param callable(ConfigBuilder):void $callable
178
     */
179
    public function setConfigFn(callable $callable): self
180
    {
181
        $this->configFn = $callable;
182 3
183
        return $this;
184 3
    }
185 3
186
    public function buildConfig(ConfigBuilder $builder): ConfigBuilder
187 3
    {
188
        if ($this->configBuilder) {
189
            $builder = $this->configBuilder;
190
        }
191
192
        ($this->configFn)($builder);
193
194
        return $builder;
195 94
    }
196
197
    /**
198
     * @param callable(MappingInterfacesBuilder,array<string,mixed>):void $callable
199 94
     */
200 63
    public function setMappingInterfacesFn(callable $callable): self
201
    {
202
        $this->mappingInterfacesFn = $callable;
203 94
204
        return $this;
205 94
    }
206
207
    /**
208 94
     * Define the mapping between interfaces and concretions, so Gacela services will auto-resolve them automatically.
209
     *
210
     * @param array<string,class-string|object|callable> $externalServices
1 ignored issue
show
Documentation Bug introduced by
The doc comment array<string,class-string|object|callable> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<string,class-string|object|callable>.
Loading history...
211
     */
212
    public function buildMappingInterfaces(
213
        MappingInterfacesBuilder $builder,
214 3
        array $externalServices,
215
    ): MappingInterfacesBuilder {
216 3
        if ($this->mappingInterfacesBuilder) {
217 3
            $builder = $this->mappingInterfacesBuilder;
218
        }
219 3
220
        ($this->mappingInterfacesFn)(
221
            $builder,
222
            array_merge($this->externalServices ?? [], $externalServices)
223
        );
224
225 94
        return $builder;
226
    }
227 94
228 63
    /**
229
     * @param callable(SuffixTypesBuilder):void $callable
230
     */
231 94
    public function setSuffixTypesFn(callable $callable): self
232
    {
233 94
        $this->suffixTypesFn = $callable;
234
235
        return $this;
236
    }
237
238
    /**
239 75
     * Allow overriding gacela resolvable types.
240
     */
241 75
    public function buildSuffixTypes(SuffixTypesBuilder $builder): SuffixTypesBuilder
242 75
    {
243
        if ($this->suffixTypesBuilder) {
244 75
            $builder = $this->suffixTypesBuilder;
245
        }
246
247
        ($this->suffixTypesFn)($builder);
248
249
        return $builder;
250 26
    }
251
252 26
    /**
253
     * @return array<string,class-string|object|callable>
1 ignored issue
show
Documentation Bug introduced by
The doc comment array<string,class-string|object|callable> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<string,class-string|object|callable>.
Loading history...
254
     */
255 72
    public function externalServices(): array
256
    {
257 72
        return (array)$this->externalServices;
258 72
    }
259
260 72
    public function setShouldResetInMemoryCache(?bool $flag): self
261
    {
262
        $this->markPropertyChanged(self::shouldResetInMemoryCache, $flag);
263 80
        $this->shouldResetInMemoryCache = $flag ?? self::DEFAULT_SHOULD_RESET_IN_MEMORY_CACHE;
264
265 80
        return $this;
266
    }
267
268 24
    public function shouldResetInMemoryCache(): bool
269
    {
270 24
        return (bool)$this->shouldResetInMemoryCache;
271
    }
272
273 6
    public function isFileCacheEnabled(): bool
274
    {
275 6
        return (bool)$this->fileCacheEnabled;
276
    }
277
278 72
    public function getFileCacheDirectory(): string
279
    {
280 72
        return (string)$this->fileCacheDirectory;
281 72
    }
282
283 72
    public function setFileCacheDirectory(?string $dir): self
284
    {
285
        $this->markPropertyChanged(self::fileCacheDirectory, $dir);
286
        $this->fileCacheDirectory = $dir ?? self::DEFAULT_FILE_CACHE_DIRECTORY;
287
288
        return $this;
289 72
    }
290
291 72
    /**
292 72
     * @param ?list<string> $list
293
     */
294 72
    public function setProjectNamespaces(?array $list): self
295
    {
296
        $this->markPropertyChanged(self::projectNamespaces, $list);
297
        $this->projectNamespaces = $list ?? self::DEFAULT_PROJECT_NAMESPACES;
1 ignored issue
show
Documentation Bug introduced by
It seems like $list ?? self::DEFAULT_PROJECT_NAMESPACES of type array is incompatible with the declared type Gacela\Framework\Bootstrap\list|null of property $projectNamespaces.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
298
299
        return $this;
300 24
    }
301
302 24
    /**
303
     * @return list<string>
304
     */
305
    public function getProjectNamespaces(): array
306
    {
307
        return (array)$this->projectNamespaces;
308 80
    }
309
310 80
    /**
311
     * @return array<string,mixed>
312
     */
313 32
    public function getConfigKeyValues(): array
314
    {
315 32
        return (array)$this->configKeyValues;
316 8
    }
317
318
    public function getEventDispatcher(): EventDispatcherInterface
319 28
    {
320 11
        if ($this->eventDispatcher !== null) {
321 11
            return $this->eventDispatcher;
322
        }
323 11
324 5
        if ($this->canCreateEventDispatcher()) {
325 5
            $this->eventDispatcher = new ConfigurableEventDispatcher();
326
            $this->eventDispatcher->registerGenericListeners($this->genericListeners ?? []);
1 ignored issue
show
Bug introduced by
The method registerGenericListeners() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

326
            $this->eventDispatcher->/** @scrutinizer ignore-call */ 
327
                                    registerGenericListeners($this->genericListeners ?? []);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
327
328
            foreach ($this->specificListeners ?? [] as $event => $listeners) {
329 17
                foreach ($listeners as $callable) {
330
                    $this->eventDispatcher->registerSpecificListener($event, $callable);
331
                }
332 28
            }
333
        } else {
334
            $this->eventDispatcher = new NullEventDispatcher();
335 26
        }
336
337 26
        return $this->eventDispatcher;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->eventDispatcher returns the type null which is incompatible with the type-hinted return Gacela\Framework\Event\D...ventDispatcherInterface.
Loading history...
338 26
    }
339
340 26
    /**
341 26
     * @return array<string,list<Closure>>
1 ignored issue
show
Documentation Bug introduced by
The doc comment array<string,list<Closure>> at position 4 could not be parsed: Expected '>' at position 4, but found 'list'.
Loading history...
342 26
     */
343 26
    public function getServicesToExtend(): array
344 26
    {
345
        return (array)$this->servicesToExtend;
346 26
    }
347
348
    public function setFileCacheEnabled(?bool $flag): self
349
    {
350
        $this->markPropertyChanged(self::fileCacheEnabled, $flag);
351
        $this->fileCacheEnabled = $flag ?? self::DEFAULT_FILE_CACHE_ENABLED;
352 33
353
        return $this;
354 33
    }
355
356
    public function canCreateEventDispatcher(): bool
357 72
    {
358
        return $this->areEventListenersEnabled
359 72
            && $this->hasEventListeners();
360 72
    }
361
362 72
    /**
363
     * @param ?array<string,mixed> $configKeyValues
364
     */
365 72
    public function setConfigKeyValues(?array $configKeyValues): self
366
    {
367 72
        $this->markPropertyChanged(self::configKeyValues, $configKeyValues);
368 72
        $this->configKeyValues = $configKeyValues ?? self::DEFAULT_CONFIG_KEY_VALUES;
369
370 72
        return $this;
371
    }
372
373 26
    /**
374
     * @return array<class-string,list<callable>>|null
1 ignored issue
show
Documentation Bug introduced by
The doc comment array<class-string,list<callable>>|null at position 2 could not be parsed: Unknown type name 'class-string' at position 2 in array<class-string,list<callable>>|null.
Loading history...
375 26
     */
376 26
    public function getSpecificListeners(): ?array
377
    {
378
        return $this->specificListeners;
379
    }
380 26
381
    /**
382 26
     * @return list<callable>|null
383 1
     */
384
    public function getGenericListeners(): ?array
385
    {
386
        return $this->genericListeners;
1 ignored issue
show
Bug Best Practice introduced by
The expression return $this->genericListeners also could return the type array which is incompatible with the documented return type Gacela\Framework\Bootstrap\list.
Loading history...
387 26
    }
388
389 26
    public function isPropertyChanged(string $name): bool
390 1
    {
391
        return $this->changedProperties[$name] ?? false;
392 26
    }
393 1
394
    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): self
395
    {
396
        $this->eventDispatcher = $eventDispatcher;
397 26
398
        return $this;
399 26
    }
400 1
401
    public function combine(self $other): self
402
    {
403
        return (new SetupCombinator($this))->combine($other);
404 26
    }
405
406 26
    /**
407 1
     * @param list<Closure> $servicesToExtend
408
     */
409
    public function addServicesToExtend(string $serviceId, array $servicesToExtend): self
410
    {
411 26
        $this->servicesToExtend[$serviceId] ??= [];
412
        $this->servicesToExtend[$serviceId] = array_merge(
413 26
            $this->servicesToExtend[$serviceId],
414 3
            $servicesToExtend,
415 2
        );
416
417 3
        return $this;
418
    }
419 3
420 2
    public function combineExternalServices(array $list): void
421 2
    {
422
        $this->setExternalServices(array_merge($this->externalServices ?? [], $list));
423
    }
424
425 23
    public function combineProjectNamespaces(array $list): void
426
    {
427
        $this->setProjectNamespaces(array_merge($this->projectNamespaces ?? [], $list));
428
    }
429 26
430
    public function combineConfigKeyValues(array $list): void
431 26
    {
432 26
        $this->setConfigKeyValues(array_merge($this->configKeyValues ?? [], $list));
433 1
    }
434 1
435 1
    private function setAreEventListenersEnabled(?bool $flag): self
436
    {
437
        $this->areEventListenersEnabled = $flag ?? self::DEFAULT_ARE_EVENT_LISTENERS_ENABLED;
438
439
        return $this;
440
    }
441
442 51
    private function hasEventListeners(): bool
443
    {
444 51
        return !empty($this->genericListeners)
445 51
            || !empty($this->specificListeners);
446
    }
447
448 51
    /**
449
     * @param ?list<callable> $listeners
450 51
     */
451 51
    private function setGenericListeners(?array $listeners): self
452
    {
453
        $this->genericListeners = $listeners ?? self::DEFAULT_GENERIC_LISTENERS;
1 ignored issue
show
Documentation Bug introduced by
It seems like $listeners ?? self::DEFAULT_GENERIC_LISTENERS of type array is incompatible with the declared type Gacela\Framework\Bootstrap\list|null of property $genericListeners.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
454
455
        return $this;
456
    }
457 72
458
    /**
459 72
     * @param ?array<string,list<Closure>> $list
1 ignored issue
show
Documentation Bug introduced by
The doc comment ?array<string,list<Closure>> at position 4 could not be parsed: Expected '>' at position 4, but found 'list'.
Loading history...
460 72
     */
461
    private function setServicesToExtend(?array $list): self
462 72
    {
463
        $this->markPropertyChanged(self::servicesToExtend, $list);
464
        $this->servicesToExtend = $list ?? self::DEFAULT_SERVICES_TO_EXTEND;
465
466
        return $this;
467
    }
468 72
469
    /**
470 72
     * @param ?array<class-string,list<callable>> $listeners
471 72
     */
472
    private function setSpecificListeners(?array $listeners): self
473 72
    {
474
        $this->specificListeners = $listeners ?? self::DEFAULT_SPECIFIC_LISTENERS;
475
476
        return $this;
477
    }
478
479 72
    private function markPropertyChanged(string $name, mixed $value): void
480
    {
481 72
        $this->changedProperties[$name] = ($value !== null);
482 72
    }
483
}
484