SetupGacela::setPropertyWithTracking()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 4
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework\Bootstrap;
6
7
use Closure;
8
use Gacela\Framework\Bootstrap\Setup\BuilderExecutor;
9
use Gacela\Framework\Bootstrap\Setup\GacelaConfigExtender;
10
use Gacela\Framework\Bootstrap\Setup\Properties;
11
use Gacela\Framework\Bootstrap\Setup\PropertyChangeTracker;
12
use Gacela\Framework\Bootstrap\Setup\PropertyMerger;
13
use Gacela\Framework\Bootstrap\Setup\SetupInitializer;
14
use Gacela\Framework\Bootstrap\Setup\SetupMerger;
15
use Gacela\Framework\Config\GacelaConfigBuilder\AppConfigBuilder;
16
use Gacela\Framework\Config\GacelaConfigBuilder\BindingsBuilder;
17
use Gacela\Framework\Config\GacelaConfigBuilder\SuffixTypesBuilder;
18
use Gacela\Framework\Event\Dispatcher\EventDispatcherInterface;
19
use RuntimeException;
20
21
use function is_callable;
22
use function sprintf;
23
24
/**
25
 * @psalm-suppress ArgumentTypeCoercion,MixedArgumentTypeCoercion
26
 */
27
final class SetupGacela extends AbstractSetupGacela
28
{
29
    private readonly Properties $properties;
30
31
    private readonly PropertyChangeTracker $changeTracker;
32
33
    private readonly BuilderExecutor $builderExecutor;
34
35
    private readonly PropertyMerger $propertyMerger;
36
37
    public function __construct()
38
    {
39
        $this->properties = new Properties();
40
        $this->changeTracker = new PropertyChangeTracker();
41
        $this->builderExecutor = new BuilderExecutor($this->properties);
42
        $this->propertyMerger = new PropertyMerger($this);
43
    }
44
45
    /**
46
     * @codeCoverageIgnore
47
     */
48
    public static function fromFile(string $gacelaFilePath): self
49
    {
50
        if (!is_file($gacelaFilePath)) {
51
            throw new RuntimeException(sprintf("Invalid file path: '%s'", $gacelaFilePath));
52
        }
53
54
        /** @var callable(GacelaConfig):void|null $setupGacelaFileFn */
55
        $setupGacelaFileFn = include $gacelaFilePath;
56
        if (!is_callable($setupGacelaFileFn)) {
57
            return new self();
58
        }
59
60
        return self::fromCallable($setupGacelaFileFn);
61
    }
62
63
    /**
64
     * @param callable(GacelaConfig):void $setupGacelaFileFn
65
     */
66
    public static function fromCallable(callable $setupGacelaFileFn): self
67
    {
68
        $gacelaConfig = new GacelaConfig();
69
        $setupGacelaFileFn($gacelaConfig);
70
71
        return self::fromGacelaConfig($gacelaConfig);
72
    }
73
74
    public static function fromGacelaConfig(GacelaConfig $gacelaConfig): self
75
    {
76
        (new GacelaConfigExtender())->extend($gacelaConfig);
77
78
        $dto = $gacelaConfig->toTransfer();
79
        $setup = new self();
80
81
        return (new SetupInitializer($setup))->initializeFromTransfer($dto);
82
    }
83
84
    /**
85
     * @param array<string,class-string|object|callable> $array
86
     */
87
    public function setExternalServices(?array $array): self
88
    {
89
        $this->markPropertyAsChanged(self::externalServices, $array !== null);
90
        $this->properties->externalServices = $array; // No default fallback for external services
91
92
        return $this;
93
    }
94
95
    public function setAppConfigBuilder(AppConfigBuilder $builder): self
96
    {
97
        $this->properties->appConfigBuilder = $builder;
98
99
        return $this;
100
    }
101
102
    public function setSuffixTypesBuilder(SuffixTypesBuilder $builder): self
103
    {
104
        $this->properties->suffixTypesBuilder = $builder;
105
106
        return $this;
107
    }
108
109
    public function setBindingsBuilder(BindingsBuilder $builder): self
110
    {
111
        $this->properties->bindingsBuilder = $builder;
112
113
        return $this;
114
    }
115
116
    /**
117
     * @param callable(AppConfigBuilder):void $callable
118
     */
119
    public function setAppConfigFn(callable $callable): self
120
    {
121
        $this->properties->appConfigFn = $callable;
122
123
        return $this;
124
    }
125
126
    public function buildAppConfig(AppConfigBuilder $builder): AppConfigBuilder
127
    {
128
        $builder = parent::buildAppConfig($builder);
129
130
        return $this->builderExecutor->buildAppConfig($builder);
131
    }
132
133
    /**
134
     * @param callable(BindingsBuilder,array<string,mixed>):void $callable
135
     */
136
    public function setBindingsFn(callable $callable): self
137
    {
138
        $this->properties->bindingsFn = $callable;
139
140
        return $this;
141
    }
142
143
    /**
144
     * Define the mapping between interfaces and concretions, so Gacela services will auto-resolve them automatically.
145
     *
146
     * @param array<string,class-string|object|callable> $externalServices
147
     */
148
    public function buildBindings(
149
        BindingsBuilder $builder,
150
        array $externalServices,
151
    ): BindingsBuilder {
152
        $builder = parent::buildBindings($builder, $externalServices);
153
154
        return $this->builderExecutor->buildBindings($builder, $externalServices);
155
    }
156
157
    /**
158
     * @param callable(SuffixTypesBuilder):void $callable
159
     */
160
    public function setSuffixTypesFn(callable $callable): self
161
    {
162
        $this->properties->suffixTypesFn = $callable;
163
164
        return $this;
165
    }
166
167
    /**
168
     * Allow overriding gacela resolvable types.
169
     */
170
    public function buildSuffixTypes(SuffixTypesBuilder $builder): SuffixTypesBuilder
171
    {
172
        $builder = parent::buildSuffixTypes($builder);
173
174
        return $this->builderExecutor->buildSuffixTypes($builder);
175
    }
176
177
    /**
178
     * @return array<string, class-string|object|callable>
179
     */
180
    public function externalServices(): array
181
    {
182
        return array_merge(
183
            parent::externalServices(),
184
            $this->properties->externalServices ?? [],
185
        );
186
    }
187
188
    public function setShouldResetInMemoryCache(?bool $flag): self
189
    {
190
        $this->properties->shouldResetInMemoryCache = $this->setPropertyWithTracking(
191
            self::shouldResetInMemoryCache,
192
            $flag,
193
            self::DEFAULT_SHOULD_RESET_IN_MEMORY_CACHE,
194
        );
195
196
        return $this;
197
    }
198
199
    public function shouldResetInMemoryCache(): bool
200
    {
201
        return $this->properties->shouldResetInMemoryCache ?? self::DEFAULT_SHOULD_RESET_IN_MEMORY_CACHE;
202
    }
203
204
    public function isFileCacheEnabled(): bool
205
    {
206
        return $this->properties->fileCacheEnabled ?? self::DEFAULT_FILE_CACHE_ENABLED;
207
    }
208
209
    public function getFileCacheDirectory(): string
210
    {
211
        return $this->properties->fileCacheDirectory ?? '';
212
    }
213
214
    public function setFileCacheDirectory(?string $dir): self
215
    {
216
        $this->properties->fileCacheDirectory = $this->setPropertyWithTracking(
217
            self::fileCacheDirectory,
218
            $dir,
219
            self::DEFAULT_FILE_CACHE_DIRECTORY,
220
        );
221
222
        return $this;
223
    }
224
225
    /**
226
     * @param ?list<string> $list
227
     */
228
    public function setProjectNamespaces(?array $list): self
229
    {
230
        $this->properties->projectNamespaces = $this->setPropertyWithTracking(
231
            self::projectNamespaces,
232
            $list,
233
            self::DEFAULT_PROJECT_NAMESPACES,
234
        );
235
236
        return $this;
237
    }
238
239
    /**
240
     * @return list<string>
241
     */
242
    public function getProjectNamespaces(): array
243
    {
244
        return $this->properties->projectNamespaces ?? self::DEFAULT_PROJECT_NAMESPACES;
245
    }
246
247
    /**
248
     * @return array<string,mixed>
249
     */
250
    public function getConfigKeyValues(): array
251
    {
252
        return $this->properties->configKeyValues ?? self::DEFAULT_CONFIG_KEY_VALUES;
253
    }
254
255
    public function getEventDispatcher(): EventDispatcherInterface
256
    {
257
        return $this->properties->eventDispatcher ??= SetupEventDispatcher::getDispatcher($this);
258
    }
259
260
    /**
261
     * @return array<string,list<Closure>>
262
     */
263
    public function getServicesToExtend(): array
264
    {
265
        return $this->properties->servicesToExtend ?? self::DEFAULT_SERVICES_TO_EXTEND;
266
    }
267
268
    /**
269
     * @return array<string,Closure>
270
     */
271
    public function getFactories(): array
272
    {
273
        return $this->properties->factories ?? self::DEFAULT_FACTORIES;
274
    }
275
276
    /**
277
     * @return array<string,Closure>
278
     */
279
    public function getProtectedServices(): array
280
    {
281
        return $this->properties->protectedServices ?? self::DEFAULT_PROTECTED_SERVICES;
282
    }
283
284
    /**
285
     * @return array<string,string>
286
     */
287
    public function getAliases(): array
288
    {
289
        return $this->properties->aliases ?? self::DEFAULT_ALIASES;
290
    }
291
292
    public function setFileCacheEnabled(?bool $flag): self
293
    {
294
        $this->properties->fileCacheEnabled = $this->setPropertyWithTracking(
295
            self::fileCacheEnabled,
296
            $flag,
297
            self::DEFAULT_FILE_CACHE_ENABLED,
298
        );
299
300
        return $this;
301
    }
302
303
    public function canCreateEventDispatcher(): bool
304
    {
305
        return $this->properties->areEventListenersEnabled === true
306
            && $this->hasEventListeners();
307
    }
308
309
    /**
310
     * @param ?array<string,mixed> $configKeyValues
311
     */
312
    public function setConfigKeyValues(?array $configKeyValues): self
313
    {
314
        $this->properties->configKeyValues = $this->setPropertyWithTracking(
315
            self::configKeyValues,
316
            $configKeyValues,
317
            self::DEFAULT_CONFIG_KEY_VALUES,
318
        );
319
320
        return $this;
321
    }
322
323
    /**
324
     * @return array<class-string,list<callable>>|null
325
     */
326
    public function getSpecificListeners(): ?array
327
    {
328
        return $this->properties->specificListeners;
329
    }
330
331
    /**
332
     * @return list<callable>|null
333
     */
334
    public function getGenericListeners(): ?array
335
    {
336
        return $this->properties->genericListeners;
337
    }
338
339
    public function isPropertyChanged(string $name): bool
340
    {
341
        return $this->changeTracker->isChanged($name);
342
    }
343
344
    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): self
345
    {
346
        $this->properties->eventDispatcher = $eventDispatcher;
347
348
        return $this;
349
    }
350
351
    public function merge(self $other): self
352
    {
353
        return (new SetupMerger($this))->merge($other);
354
    }
355
356
    /**
357
     * @param list<Closure> $servicesToExtend
358
     */
359
    public function addServicesToExtend(string $serviceId, array $servicesToExtend): self
360
    {
361
        $this->properties->servicesToExtend[$serviceId] ??= [];
362
        $this->properties->servicesToExtend[$serviceId] = [...$this->properties->servicesToExtend[$serviceId], ...$servicesToExtend];
363
364
        return $this;
365
    }
366
367
    /**
368
     * @param array<string,class-string|object|callable> $list
369
     */
370
    public function mergeExternalServices(array $list): void
371
    {
372
        $this->propertyMerger->mergeExternalServices($list);
373
    }
374
375
    /**
376
     * @param list<string> $list
377
     */
378
    public function mergeProjectNamespaces(array $list): void
379
    {
380
        $this->propertyMerger->mergeProjectNamespaces($list);
381
    }
382
383
    /**
384
     * @param array<string,mixed> $list
385
     */
386
    public function mergeConfigKeyValues(array $list): void
387
    {
388
        $this->propertyMerger->mergeConfigKeyValues($list);
389
    }
390
391
    /**
392
     * @param list<class-string> $list
393
     */
394
    public function mergeGacelaConfigsToExtend(array $list): void
395
    {
396
        $this->propertyMerger->mergeGacelaConfigsToExtend($list);
397
    }
398
399
    /**
400
     * @param list<class-string|callable> $list
401
     */
402
    public function mergePlugins(array $list): void
403
    {
404
        $this->propertyMerger->mergePlugins($list);
405
    }
406
407
    /**
408
     * @param array<string,Closure> $list
409
     */
410
    public function mergeFactories(array $list): void
411
    {
412
        $this->propertyMerger->mergeFactories($list);
413
    }
414
415
    /**
416
     * @param array<string,Closure> $list
417
     */
418
    public function mergeProtectedServices(array $list): void
419
    {
420
        $this->propertyMerger->mergeProtectedServices($list);
421
    }
422
423
    /**
424
     * @param array<string,string> $list
425
     */
426
    public function mergeAliases(array $list): void
427
    {
428
        $this->propertyMerger->mergeAliases($list);
429
    }
430
431
    /**
432
     * @return list<class-string>
433
     */
434
    public function getGacelaConfigsToExtend(): array
435
    {
436
        return $this->properties->gacelaConfigsToExtend ?? self::DEFAULT_GACELA_CONFIGS_TO_EXTEND;
437
    }
438
439
    /**
440
     * @return list<class-string|callable>
441
     */
442
    public function getPlugins(): array
443
    {
444
        return $this->properties->plugins ?? self::DEFAULT_PLUGINS;
445
    }
446
447
    /**
448
     * @internal Used by PropertyMerger - do not call directly
449
     *
450
     * @param ?list<class-string> $list
451
     */
452
    public function setGacelaConfigsToExtend(?array $list): self
453
    {
454
        $this->properties->gacelaConfigsToExtend = $this->setPropertyWithTracking(
455
            self::gacelaConfigsToExtend,
456
            $list,
457
            self::DEFAULT_GACELA_CONFIGS_TO_EXTEND,
458
        );
459
460
        return $this;
461
    }
462
463
    /**
464
     * @internal Used by PropertyMerger - do not call directly
465
     *
466
     * @param ?list<class-string|callable> $list
467
     */
468
    public function setPlugins(?array $list): self
469
    {
470
        $this->properties->plugins = $this->setPropertyWithTracking(
471
            self::plugins,
472
            $list,
473
            self::DEFAULT_PLUGINS,
474
        );
475
476
        return $this;
477
    }
478
479
    /**
480
     * @internal Used by SetupInitializer - do not call directly
481
     */
482
    public function setAreEventListenersEnabled(?bool $flag): self
483
    {
484
        $this->properties->areEventListenersEnabled = $flag ?? self::DEFAULT_ARE_EVENT_LISTENERS_ENABLED;
485
486
        return $this;
487
    }
488
489
    /**
490
     * @internal Used by SetupInitializer - do not call directly
491
     *
492
     * @param ?list<callable> $listeners
493
     */
494
    public function setGenericListeners(?array $listeners): self
495
    {
496
        $this->properties->genericListeners = $listeners ?? self::DEFAULT_GENERIC_LISTENERS;
0 ignored issues
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\Setup\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...
497
498
        return $this;
499
    }
500
501
    /**
502
     * @internal Used by SetupInitializer - do not call directly
503
     *
504
     * @param ?array<string,list<Closure>> $list
505
     */
506
    public function setServicesToExtend(?array $list): self
507
    {
508
        $this->properties->servicesToExtend = $this->setPropertyWithTracking(
509
            self::servicesToExtend,
510
            $list,
511
            self::DEFAULT_SERVICES_TO_EXTEND,
512
        );
513
514
        return $this;
515
    }
516
517
    /**
518
     * @internal Used by SetupInitializer - do not call directly
519
     *
520
     * @param ?array<string,Closure> $list
521
     */
522
    public function setFactories(?array $list): self
523
    {
524
        $this->properties->factories = $this->setPropertyWithTracking(
525
            self::factories,
526
            $list,
527
            self::DEFAULT_FACTORIES,
528
        );
529
530
        return $this;
531
    }
532
533
    /**
534
     * @internal Used by SetupInitializer - do not call directly
535
     *
536
     * @param ?array<string,Closure> $list
537
     */
538
    public function setProtectedServices(?array $list): self
539
    {
540
        $this->properties->protectedServices = $this->setPropertyWithTracking(
541
            self::protectedServices,
542
            $list,
543
            self::DEFAULT_PROTECTED_SERVICES,
544
        );
545
546
        return $this;
547
    }
548
549
    /**
550
     * @internal Used by SetupInitializer - do not call directly
551
     *
552
     * @param ?array<string,string> $list
553
     */
554
    public function setAliases(?array $list): self
555
    {
556
        $this->properties->aliases = $this->setPropertyWithTracking(
557
            self::aliases,
558
            $list,
559
            self::DEFAULT_ALIASES,
560
        );
561
562
        return $this;
563
    }
564
565
    /**
566
     * @internal Used by SetupInitializer - do not call directly
567
     *
568
     * @param ?array<class-string,list<callable>> $listeners
569
     */
570
    public function setSpecificListeners(?array $listeners): self
571
    {
572
        $this->properties->specificListeners = $listeners ?? self::DEFAULT_SPECIFIC_LISTENERS;
573
574
        return $this;
575
    }
576
577
    private function hasEventListeners(): bool
578
    {
579
        return ($this->properties->genericListeners !== null && $this->properties->genericListeners !== [])
580
            || ($this->properties->specificListeners !== null && $this->properties->specificListeners !== []);
581
    }
582
583
    /**
584
     * Helper method to set a property with change tracking and default value.
585
     *
586
     * @template T
587
     *
588
     * @param T $value
589
     * @param T $default
590
     *
591
     * @return T
592
     */
593
    private function setPropertyWithTracking(string $propertyName, mixed $value, mixed $default): mixed
594
    {
595
        $this->markPropertyAsChanged($propertyName, $value !== null);
596
        return $value ?? $default;
597
    }
598
599
    private function markPropertyAsChanged(string $name, bool $isChanged): void
600
    {
601
        if ($isChanged) {
602
            $this->changeTracker->markAsChanged($name);
603
        } else {
604
            $this->changeTracker->markAsUnchanged($name);
605
        }
606
    }
607
}
608