-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValksorBundle.php
More file actions
590 lines (480 loc) · 18.9 KB
/
Copy pathValksorBundle.php
File metadata and controls
590 lines (480 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
<?php declare(strict_types = 1);
/*
* This file is part of the Valksor package.
*
* (c) Davis Zalitis (k0d3r1s)
* (c) SIA Valksor <packages@valksor.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Valksor\Bundle;
use FilesystemIterator;
use Psr\Cache\InvalidArgumentException;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ReflectionException;
use RuntimeException;
use Seld\JsonLint\ParsingException;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Bundle\AbstractBundle;
use Symfony\Contracts\Cache\CacheInterface;
use Throwable;
use Valksor\Bundle\DependencyInjection\Dependency;
use Valksor\Bundle\DependencyInjection\ValksorConfiguration;
use Valksor\FullStack;
use Valksor\Functions\Iteration;
use Valksor\Functions\Local;
use Valksor\Functions\Memoize\MemoizeCache;
use function array_key_exists;
use function array_merge_recursive;
use function class_exists;
use function count;
use function dirname;
use function file_get_contents;
use function in_array;
use function is_a;
use function is_bool;
use function is_dir;
use function is_file;
use function ksort;
use function preg_replace;
use function rtrim;
use function sprintf;
use function str_ends_with;
use function str_replace;
use function str_starts_with;
use function strlen;
use function strtolower;
use function substr;
use const DIRECTORY_SEPARATOR;
final class ValksorBundle extends AbstractBundle
{
public const string VALKSOR = 'valksor';
private const array SELFS = [
'valksor',
'valksor-dev',
'valksor-plugin',
];
private ?MemoizeCache $cache = null;
/** @var array<string, array{class: string, available: bool}>|null */
private ?array $discoveredComponents = null;
private ?string $projectDir = null;
public function boot(): void
{
parent::boot();
$this->memoize();
}
/**
* @throws ParsingException
*/
public function build(
ContainerBuilder $container,
): void {
static $_helper = null;
if (null === $_helper) {
$_helper = new class {
use Local\Traits\_Exists;
use Local\Traits\_WillBeAvailable;
};
}
if (null === $this->projectDir) {
$bag = $container->getParameterBag();
if ($bag->has('kernel.project_dir')) {
$this->projectDir = $bag->get('kernel.project_dir');
}
}
foreach ($this->discoverComponents() as $component => $componentData) {
$this->callback($component, $componentData, static function (object $object) use ($container): void {
$object->build($container);
});
}
new ValksorConfiguration()->build($container);
}
/**
* @throws ParsingException
*/
public function configure(
DefinitionConfigurator $definition,
): void {
/** @var ArrayNodeDefinition $rootNode */
$rootNode = $definition
->rootNode();
static $_helper = null;
if (null === $_helper) {
$_helper = new class {
use Local\Traits\_Exists;
use Local\Traits\_WillBeAvailable;
};
}
$willBeAvailable = static function (string $package, string $class, ?string $parentPackage = null) use ($_helper) {
$parentPackages = (array) $parentPackage;
$parentPackages[] = sprintf('%s/bundle', self::VALKSOR);
return $_helper->willBeAvailable($package, $class, $parentPackages);
};
$enableIfStandalone = static fn (string $package, string $class) => !class_exists(FullStack::class) && $willBeAvailable($package, $class) ? 'canBeDisabled' : 'canBeEnabled';
$wrapper = static fn (string $package, string $componentClass) => $enableIfStandalone($package, '');
new ValksorConfiguration()->addSection($rootNode, $wrapper, '');
// Track which parent nodes need addDefaultsIfNotSet()
$parentNodeNeedsDefaults = [];
$allComponents = $this->discoverComponents();
// First pass: collect requirements from all components
foreach ($allComponents as $component => $componentData) {
$this->callback($component, $componentData, function (object $object, string $class, string $component) use (&$parentNodeNeedsDefaults): void {
$configPath = $this->getComponentConfigPath($class, $component);
// Track all parent nodes this component touches
for ($i = 0; $i < count($configPath) - 1; $i++) {
$pathPart = $configPath[$i];
if (!isset($parentNodeNeedsDefaults[$pathPart])) {
$parentNodeNeedsDefaults[$pathPart] = !$object->usesArrayPrototype();
} else {
// If ANY component needs defaults, mark it as needed
$parentNodeNeedsDefaults[$pathPart] = $parentNodeNeedsDefaults[$pathPart] || !$object->usesArrayPrototype();
}
}
});
}
$createdNodes = [];
// Second pass: build the configuration tree with collected requirements
foreach ($allComponents as $component => $componentData) {
$this->callback($component, $componentData, function (object $object, string $class, string $component) use ($enableIfStandalone, $rootNode, &$createdNodes, $parentNodeNeedsDefaults): void {
// Get namespace-based path
$configPath = $this->getComponentConfigPath($class, $component);
// Build nested structure
$currentNode = $rootNode;
// Navigate/create all parent nodes
for ($i = 0; $i < count($configPath) - 1; $i++) {
$pathPart = $configPath[$i];
if (!isset($createdNodes[$pathPart])) {
$node = $currentNode->children()
->arrayNode($pathPart);
// Apply addDefaultsIfNotSet() if any component needs it
if ($parentNodeNeedsDefaults[$pathPart] ?? false) {
$node->addDefaultsIfNotSet();
}
$currentNode = $node;
$createdNodes[$pathPart] = $currentNode;
} else {
$currentNode = $createdNodes[$pathPart];
}
}
// Add component at the final location
$wrapper = static fn (string $package, string $componentClass) => $enableIfStandalone($package, $class);
$object->addSection($currentNode, $wrapper, end($configPath));
});
}
}
/**
* Get all configuration defaults from discovered components.
*
* Uses auto-discovery to collect defaults from all configuration classes
* into a hierarchical array matching the configuration tree structure.
*
* @param CacheInterface|null $cache Optional cache pool for performance.
* Should be configured by the application using this bundle.
*
* @return array<string, mixed> Hierarchical array of all configuration defaults
*
* @throws InvalidArgumentException
* @throws ParsingException
*/
public function getAllConfigurationDefaults(
?CacheInterface $cache = null,
): array {
if (null === $cache) {
return $this->computeAllDefaults();
}
return $cache->get('valksor.bundle.defaults', fn () => $this->computeAllDefaults());
}
/**
* @param array<string, mixed> $config
*
* @throws ParsingException
*/
public function loadExtension(
array $config,
ContainerConfigurator $container,
ContainerBuilder $builder,
): void {
static $_helper = null;
if (null === $_helper) {
$_helper = new class {
use Iteration\Traits\_MakeOneDimension;
use Local\Traits\_Exists;
use Local\Traits\_WillBeAvailable;
};
}
foreach ($_helper->makeOneDimension([self::VALKSOR => $config]) as $key => $value) {
$builder->setParameter($key, $value);
}
foreach ($this->discoverComponents() as $component => $componentData) {
$this->callback($component, $componentData, static function (object $object, string $class, string $component) use ($container, $builder): void {
$object->registerConfiguration($container, $builder, $component);
}, $builder);
}
new ValksorConfiguration()->registerConfiguration($container, $builder, '');
}
/**
* @throws ParsingException
*/
public function prependExtension(
ContainerConfigurator $container,
ContainerBuilder $builder,
): void {
$valksor = new ValksorConfiguration();
$usesDoctrine = false;
static $_helper = null;
if (null === $_helper) {
$_helper = new class {
use Local\Traits\_Exists;
use Local\Traits\_WillBeAvailable;
};
}
if (null === $this->projectDir) {
$bag = $builder->getParameterBag();
if ($bag->has('kernel.project_dir')) {
$this->projectDir = $bag->get('kernel.project_dir');
}
}
foreach ($this->discoverComponents() as $component => $componentData) {
$this->callback($component, $componentData, static function (object $object, string $class, string $component) use ($container, $builder, &$usesDoctrine): void {
$object->registerPreConfiguration($container, $builder, $component);
$usesDoctrine = $usesDoctrine || $object->usesDoctrine();
}, $builder);
}
$valksor->registerPreConfiguration($container, $builder, '');
if ($usesDoctrine) {
$valksor->registerGlobalMigrations($container, $builder);
}
}
/**
* @return array<string, mixed>
*/
public static function getConfig(
string $package,
ContainerBuilder $builder,
): array {
return array_merge_recursive(...$builder->getExtensionConfig($package));
}
public static function p(
ContainerBuilder $builder,
string $component,
string $parameter,
): mixed {
return $builder->getParameter(sprintf('%s.%s.%s', self::VALKSOR, $component, $parameter));
}
/**
* @param array<string, mixed> $componentData
*/
private function callback(
string $component,
array $componentData,
callable $callback,
?ContainerBuilder $builder = null,
): void {
static $_helper = null;
if (null === $_helper) {
$_helper = new class {
use Local\Traits\_Exists;
use Local\Traits\_WillBeAvailable;
};
}
$class = $componentData['class'];
if (!$_helper->exists($class)) {
return;
}
if (!$componentData['available']) {
return;
}
$package = self::VALKSOR . '/' . $component;
if (!$_helper->willBeAvailable($package, $class, [sprintf('%s/bundle', self::VALKSOR)])) {
return;
}
$object = new $class();
if (is_a($object, Dependency::class)) {
if (null !== $builder) {
try {
$enabled = self::p($builder, $component, 'enabled');
if (!is_bool($enabled) || !$enabled) {
return;
}
} catch (Throwable) {
}
}
$callback($object, $class, $component);
}
}
/**
* Compute all configuration defaults from discovered components.
*
* @return array<string, mixed> Hierarchical array of all configuration defaults
*
* @throws ParsingException
*/
private function computeAllDefaults(): array
{
$defaults = [];
foreach ($this->discoverComponents() as $componentId => $componentData) {
$className = $componentData['class'];
$componentDefaults = $className::getDefaults();
if ([] === $componentDefaults) {
continue;
}
$current = &$defaults;
foreach ($this->getComponentConfigPath($className, $componentId) as $key) {
if (!isset($current[$key])) {
$current[$key] = [];
}
$current = &$current[$key];
}
$current = $componentDefaults;
}
return $defaults;
}
/**
* @return array<string, array{class: string, available: bool}> Array of component ID => {class, available}
*
* @throws ParsingException
*/
private function discoverComponents(): array
{
if (null !== $this->discoveredComponents) {
return $this->discoveredComponents;
}
$this->discoveredComponents = [];
$visitedClasses = [];
$autoloadPsr4 = require $this->findProjectRoot() . '/vendor/composer/autoload_psr4.php';
static $_helper = null;
if (null === $_helper) {
$_helper = new class {
use Traits\_LoadReflection;
};
}
foreach ($autoloadPsr4 as $namespacePrefix => $directories) {
if (!str_starts_with($namespacePrefix, 'Valksor\\') && !str_starts_with($namespacePrefix, 'ValksorDev\\')) {
continue;
}
foreach ($directories as $directory) {
foreach ($this->findConfigurationClasses($directory, $namespacePrefix) as $className) {
if (array_key_exists($className, $visitedClasses)) {
continue;
}
$visitedClasses[$className] = true;
try {
$reflection = $_helper->loadReflection($className, $this->memoize());
} catch (ReflectionException) {
continue;
}
if (!$reflection->implementsInterface(Dependency::class) || $reflection->isAbstract()) {
continue;
}
$componentName = substr($reflection->getShortName(), 0, -13);
$componentId = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $componentName));
if (self::VALKSOR === $componentId || isset($this->discoveredComponents[$componentId])) {
continue;
}
try {
$available = new $className()->autoDiscover();
} catch (Throwable) {
$available = false;
}
$this->discoveredComponents[$componentId] = [
'class' => $className,
'available' => $available,
];
}
}
}
ksort($this->discoveredComponents);
return $this->discoveredComponents;
}
/**
* @return iterable<string>
*/
private function findConfigurationClasses(
string $directory,
string $namespacePrefix,
): iterable {
$normalizedDirectory = rtrim($directory, DIRECTORY_SEPARATOR . '/');
if ('' === $normalizedDirectory || !is_dir($normalizedDirectory)) {
return;
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($normalizedDirectory, FilesystemIterator::SKIP_DOTS),
);
foreach ($iterator as $file) {
if (!$file->isFile() || 'php' !== $file->getExtension()) {
continue;
}
$basename = $file->getBasename('.php');
if (!str_ends_with($basename, 'Configuration')) {
continue;
}
$relativePath = substr($file->getPathname(), strlen($normalizedDirectory) + 1);
$relativeClass = substr($relativePath, 0, -4);
$relativeClass = str_replace(DIRECTORY_SEPARATOR, '\\', $relativeClass);
yield rtrim($namespacePrefix, '\\') . '\\' . $relativeClass;
}
}
/**
* Recursively find the project root by looking for composer.json.
*
* @throws ParsingException
*/
private function findProjectRoot(): string
{
if (null !== $this->projectDir) {
return $this->projectDir;
}
$dir = __DIR__;
static $_helper = null;
if (null === $_helper) {
$_helper = new class {
use Iteration\Traits\_JsonDecode;
};
}
while ($dir !== dirname($dir)) {
// Check if this is the actual project root (has vendor directory)
if (is_file($dir . '/composer.json')) {
$data = $_helper->jsonDecode(file_get_contents($dir . '/composer.json'), true);
if (is_dir($dir . '/vendor') && !in_array($data['name'], self::SELFS, true)) {
return $this->projectDir = $dir;
}
}
$dir = dirname($dir);
}
throw new RuntimeException('Could not find project root (composer.json with vendor directory)');
}
/**
* Extract configuration path from component namespace.
*
* Maps namespace structure to configuration path, e.g.:
* - Valksor\Component\FormType\CloudflareTurnstile\DependencyInjection\CloudflareTurnstileConfiguration
* → ['form_type', 'cloudflare_turnstile']
* - Valksor\Component\Sse\DependencyInjection\SseConfiguration
* → ['sse']
*/
private function getComponentConfigPath(
string $className,
string $componentName,
): array {
// Handle Valksor components: Valksor\Component\<Category>\...\<Component>Configuration
$valksorPattern = '#^Valksor\\\\Component\\\\([^\\\\]+)\\\\[^\\\\]+\\\\DependencyInjection\\\\[^\\\\]+$#';
if (preg_match($valksorPattern, $className, $matches)) {
$category = $matches[1]; // e.g., "FormType"
// Convert PascalCase to snake_case
$configSection = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $category));
return [$configSection, $componentName];
}
// Default: flat structure
return [$componentName];
// Default: flat structure
}
private function memoize(): MemoizeCache
{
return $this->cache ??= new MemoizeCache();
}
}