-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathAdminRouteGenerator.php
More file actions
865 lines (728 loc) · 43 KB
/
AdminRouteGenerator.php
File metadata and controls
865 lines (728 loc) · 43 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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
<?php
namespace EasyCorp\Bundle\EasyAdminBundle\Router;
use EasyCorp\Bundle\EasyAdminBundle\Attribute\AdminDashboard;
use EasyCorp\Bundle\EasyAdminBundle\Attribute\AdminRoute;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Option\CacheKey;
use EasyCorp\Bundle\EasyAdminBundle\Config\Option\EA;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Controller\CrudControllerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Controller\DashboardControllerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Router\AdminRouteGeneratorInterface;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Config\Resource\ReflectionClassResource;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
final class AdminRouteGenerator implements AdminRouteGeneratorInterface
{
/**
* @deprecated Since easycorp/easyadmin-bundle 5.0.0 and will be removed in EasyAdmin 5.1.0.
* @see CacheKey::ROUTE_NAME_TO_ATTRIBUTES
*/
public const CACHE_KEY_ROUTE_TO_FQCN = 'easyadmin.routes.route_to_fqcn';
/**
* @deprecated Since easycorp/easyadmin-bundle 5.0.0 and will be removed in EasyAdmin 5.1.0.
* @see CacheKey::ROUTE_ATTRIBUTES_TO_NAME
*/
public const CACHE_KEY_FQCN_TO_ROUTE = 'easyadmin.routes.fqcn_to_route';
public const BUILT_IN_ACTION_NAMES = [
Action::INDEX, Action::NEW, Action::EDIT, Action::DETAIL, Action::DELETE,
Action::BATCH_DELETE, Action::SAVE_AND_ADD_ANOTHER, Action::SAVE_AND_CONTINUE,
Action::SAVE_AND_RETURN, 'autocomplete', 'renderFilters',
];
private const DEFAULT_ROUTES_CONFIG = [
Action::INDEX => [
'actionName' => Action::INDEX,
'routePath' => '/',
'routeName' => 'index',
'methods' => ['GET'],
],
Action::NEW => [
'actionName' => Action::NEW,
'routePath' => '/new',
'routeName' => 'new',
'methods' => ['GET', 'POST'],
],
Action::BATCH_DELETE => [
'actionName' => Action::BATCH_DELETE,
'routePath' => '/batch-delete',
'routeName' => 'batch_delete',
'methods' => ['POST'],
],
'autocomplete' => [
'actionName' => 'autocomplete',
'routePath' => '/autocomplete',
'routeName' => 'autocomplete',
'methods' => ['GET'],
],
'renderFilters' => [
'actionName' => 'renderFilters',
'routePath' => '/render-filters',
'routeName' => 'render_filters',
'methods' => ['GET'],
],
Action::EDIT => [
'actionName' => Action::EDIT,
'routePath' => '/{entityId}/edit',
'routeName' => 'edit',
'methods' => ['GET', 'POST', 'PATCH'],
],
Action::DELETE => [
'actionName' => Action::DELETE,
'routePath' => '/{entityId}/delete',
'routeName' => 'delete',
'methods' => ['POST'],
],
Action::DETAIL => [
'actionName' => Action::DETAIL,
'routePath' => '/{entityId}',
'routeName' => 'detail',
'methods' => ['GET'],
],
];
/**
* @param iterable<DashboardControllerInterface> $dashboardControllers
* @param iterable<CrudControllerInterface> $crudControllers
* @param iterable<object> $adminRouteControllers Controllers with the #[AdminRoute] attribute
*/
public function __construct(
private readonly iterable $dashboardControllers,
private readonly iterable $crudControllers,
private readonly CacheItemPoolInterface $cache,
private readonly iterable $adminRouteControllers = [],
) {
}
public function generateAll(): RouteCollection
{
$collection = new RouteCollection();
$adminRoutes = $this->generateAdminRoutes();
foreach ($adminRoutes as $routeName => $route) {
$collection->add($routeName, $route);
}
// track controller files as resources so Symfony's routing cache
// is rebuilt automatically when adding/changing route attributes
foreach ($this->dashboardControllers as $dashboardController) {
$collection->addResource(new ReflectionClassResource(new \ReflectionClass($dashboardController)));
}
foreach ($this->crudControllers as $crudController) {
$collection->addResource(new ReflectionClassResource(new \ReflectionClass($crudController)));
}
foreach ($this->adminRouteControllers as $adminRouteController) {
$collection->addResource(new ReflectionClassResource(new \ReflectionClass($adminRouteController)));
}
// this dumps all admin routes in a performance-optimized format to later
// find them quickly without having to use Symfony's router service
$this->saveAdminRoutesInCache($adminRoutes);
$this->saveCrudControllersAndEntityFqcnMapInCache($this->crudControllers);
return $collection;
}
/**
* @deprecated Since easycorp/easyadmin-bundle 5.0.0 and will be removed in EasyAdmin 5.1.0.
*/
public function usesPrettyUrls(): bool
{
@trigger_deprecation('easycorp/easyadmin-bundle', '5.0.0', 'The "%s()" method is deprecated and will be removed in EasyAdmin 5.1.0. This method always returns true.', __METHOD__);
return true;
}
public function findRouteName(?string $dashboardFqcn = null, ?string $crudControllerFqcn = null, ?string $actionName = null): ?string
{
$routeAttributesToRouteName = $this->cache->getItem(CacheKey::ROUTE_ATTRIBUTES_TO_NAME)->get();
if (null === $dashboardFqcn) {
$dashboardControllers = iterator_to_array($this->dashboardControllers);
$dashboardFqcn = $dashboardControllers[array_key_first($dashboardControllers)]::class;
}
return $routeAttributesToRouteName[$dashboardFqcn][$crudControllerFqcn ?? ''][$actionName ?? ''] ?? null;
}
/**
* @return array<class-string, string>
*/
public function getDashboardRoutes(): array
{
return $this->cache->getItem(CacheKey::DASHBOARD_FQCN_TO_ROUTE)->get() ?? [];
}
/**
* @return array<string, Route>
*/
private function generateAdminRoutes(): array
{
/** @var array<string, Route> $adminRoutes Stores the collection of admin routes created for the app */
$adminRoutes = [];
/** @var array<string> $addedRouteNames Temporary cache that stores the route names to ensure that we don't add duplicated admin routes */
$addedRouteNames = [];
// create the routes for the CRUD controllers and actions
foreach ($this->dashboardControllers as $dashboardController) {
$dashboardFqcn = $dashboardController::class;
[$allowedCrudControllers, $deniedCrudControllers] = $this->getAllowedAndDeniedControllers($dashboardFqcn);
$defaultRoutesConfig = $this->getDefaultRoutesConfig($dashboardFqcn);
$dashboardRouteConfig = $this->getDashboardsRouteConfig()[$dashboardFqcn];
// first, create the Symfony route for the dashboards based on its #[AdminDashboard] attribute
$dashboardRouteName = $dashboardRouteConfig['routeName'];
$dashboardRoutePath = $dashboardRouteConfig['routePath'];
$dashboardRouteOptions = $dashboardRouteConfig['routeOptions'];
$adminRoute = $this->createDashboardRoute($dashboardRoutePath, $dashboardRouteOptions, $dashboardFqcn);
$adminRoutes[$dashboardRouteName] = $adminRoute;
$addedRouteNames[] = $dashboardRouteName;
// then, create the routes of the CRUD controllers associated with the dashboard
foreach ($this->crudControllers as $crudController) {
$crudControllerFqcn = $crudController::class;
if (null !== $allowedCrudControllers && !\in_array($crudControllerFqcn, $allowedCrudControllers, true)) {
continue;
}
if (null !== $deniedCrudControllers && \in_array($crudControllerFqcn, $deniedCrudControllers, true)) {
continue;
}
$crudControllerRouteConfig = $this->getCrudControllerRouteConfig($crudControllerFqcn);
$actionsRouteConfig = array_replace_recursive($defaultRoutesConfig, $this->getCustomActionsConfig($crudControllerFqcn));
// if a controller overrides the name of a route for a built-in action (e.g. 'update' for edit() action)
// remove the default route config for that built-in action (e.g. 'edit'); otherwise, we'd generate two
// different routes for the same built-in action: the custom one ('update') and the default one ('edit')
$builtInActionKeys = array_keys(self::DEFAULT_ROUTES_CONFIG);
foreach ($actionsRouteConfig as $key => $config) {
// $actionsRouteConfig contains both the built-in and custom routes; skip entries that are built-in
if (\in_array($key, $builtInActionKeys, true)) {
continue;
}
$actionName = $config['actionName'];
// if this custom route is for a built-in action (e.g. 'edit'), remove the default route entry associated to it
if (isset($actionsRouteConfig[$actionName]) && \in_array($actionName, $builtInActionKeys, true)) {
unset($actionsRouteConfig[$actionName]);
}
}
// by default, the 'detail' route uses a catch-all route pattern (/{entityId});
// so, if the user hasn't customized the 'detail' route path, we need to sort the actions
// to make sure that the 'detail' action is always the last one
if (isset($actionsRouteConfig['detail']) && '/{entityId}' === $actionsRouteConfig['detail']['routePath']) {
uasort($actionsRouteConfig, static function ($a, $b) {
$aRouteName = $a['routeName'] ?? '';
$bRouteName = $b['routeName'] ?? '';
return match (true) {
'detail' === $aRouteName => 1,
'detail' === $bRouteName => -1,
default => 0,
};
});
}
foreach (array_keys($actionsRouteConfig) as $actionName) {
$actionRouteConfig = $actionsRouteConfig[$actionName];
$actionNameSnakeCase = strtolower(preg_replace('/[A-Z]/', '_$0', $actionRouteConfig['actionName']));
$actionNameSlug = strtolower(preg_replace('/[A-Z]/', '-$0', $actionRouteConfig['actionName']));
$adminRoutePath = rtrim(sprintf('%s/%s/%s', $dashboardRouteConfig['routePath'], $crudControllerRouteConfig['routePath'], ltrim($actionRouteConfig['routePath'] ?? $actionNameSlug, '/')), '/');
$adminRouteName = sprintf('%s_%s_%s', $dashboardRouteConfig['routeName'], $crudControllerRouteConfig['routeName'], $actionRouteConfig['routeName'] ?? $actionNameSnakeCase);
if (\in_array($adminRouteName, $addedRouteNames, true)) {
throw new \RuntimeException(sprintf('The EasyAdmin CRUD controllers defined in your application must have unique PHP class names in order to generate unique route names. However, your application has at least two controllers with the FQCN "%s", generating the route "%s". Even if both CRUD controllers are in different namespaces, they cannot have the same class name. Rename one of these controllers to resolve the issue.', $crudControllerFqcn, $adminRouteName));
}
$defaults = [
'_controller' => $crudControllerFqcn.'::'.$actionRouteConfig['actionName'],
EA::ROUTE_CREATED_BY_EASYADMIN => true,
EA::DASHBOARD_CONTROLLER_FQCN => $dashboardFqcn,
EA::CRUD_CONTROLLER_FQCN => $crudControllerFqcn,
EA::CRUD_ACTION => $actionRouteConfig['actionName'],
];
$adminRoute = new Route($adminRoutePath);
// the framework-computed methods are applied first; if the user defined
// an explicit "methods" key in the #[AdminRoute] options, applyAdminRouteOptions()
// will overwrite them below
$adminRoute->setMethods($actionRouteConfig['methods']);
self::applyAdminRouteOptions($adminRoute, $actionRouteConfig['adminRouteOptions'] ?? [], $defaults);
$adminRoutes[$adminRouteName] = $adminRoute;
$addedRouteNames[] = $adminRouteName;
}
}
}
// create the routes for the controllers that use the #[AdminRoute] attribute
foreach ($this->adminRouteControllers as $controller) {
$controllerFqcn = \is_object($controller) ? $controller::class : $controller;
$reflectionClass = new \ReflectionClass($controllerFqcn);
// if the class is a CRUD controller, skip it because all the routes (default and custom) were already
// created before when creating the regular CRUD controller routes
if ($reflectionClass->implementsInterface(CrudControllerInterface::class)) {
continue;
}
// check first for class-level attributes
$classAttributes = $reflectionClass->getAttributes(AdminRoute::class);
$classAdminRoute = null;
$hasMethodRoutes = false;
// Check if there are any method-level routes
foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
if ([] !== $method->getAttributes(AdminRoute::class)) {
$hasMethodRoutes = true;
break;
}
}
if ([] !== $classAttributes) {
// Only create routes for class-level attributes if there are NO method-level routes
// If there are method routes, the class attribute is used only as a prefix
if (!$hasMethodRoutes) {
// the controller must be invokable when using class-level routes without method routes
if (!method_exists($controller, '__invoke')) {
throw new \RuntimeException(sprintf('When applying the #[AdminRoute] attribute only to the controller class (as in "%s") without any methods having #[AdminRoute], the controller must be invokable (i.e. it must define the "__invoke()" method).', $controllerFqcn));
}
// AdminRoute attribute is repeatable, so there can be more than one
foreach ($classAttributes as $classAttribute) {
/** @var AdminRoute $currentClassAdminRoute */
$currentClassAdminRoute = $classAttribute->newInstance();
// both name and path must be defined to create a route
if (null === $currentClassAdminRoute->name || null === $currentClassAdminRoute->path) {
throw new \RuntimeException(sprintf('The #[AdminRoute] attribute applied to the "%s" controller class must define both "name" and "path" arguments to generate its route (because the controller has no other methods with #[AdminRoute] and therefore, the class-level attribute doesn\'t work as a path/name prefix of other actions but as a standalone route).', $controllerFqcn));
}
// create route for the entire controller
foreach ($this->dashboardControllers as $dashboardController) {
$dashboardFqcn = $dashboardController::class;
$allowedDashboards = $currentClassAdminRoute->allowedDashboards;
$deniedDashboards = $currentClassAdminRoute->deniedDashboards;
// skip if not in allowed dashboards (when restrictions are set)
if (\is_array($allowedDashboards) && !\in_array($dashboardFqcn, $allowedDashboards, true)) {
continue;
}
// skip if in denied dashboards (when restrictions are set)
if (\is_array($deniedDashboards) && \in_array($dashboardFqcn, $deniedDashboards, true)) {
continue;
}
$dashboardRouteConfig = $this->getDashboardsRouteConfig()[$dashboardFqcn];
$adminRoutePath = rtrim(sprintf('%s/%s', $dashboardRouteConfig['routePath'], ltrim($currentClassAdminRoute->path, '/')), '/');
$adminRouteName = sprintf('%s_%s', $dashboardRouteConfig['routeName'], ltrim($currentClassAdminRoute->name, '_'));
if (\in_array($adminRouteName, $addedRouteNames, true)) {
throw new \RuntimeException(sprintf('The #[AdminRoute] attribute applied to the "%s" controller would create an admin route called "%s", which already exists. You must change the "routeName" argument to generate a different route name.', $controllerFqcn, $adminRouteName));
}
$adminRoute = $this->createRouteForAdminAttribute($currentClassAdminRoute, $adminRoutePath, $dashboardFqcn, $controllerFqcn, '__invoke');
$adminRoutes[$adminRouteName] = $adminRoute;
$addedRouteNames[] = $adminRouteName;
}
}
}
// store the first class attribute for use as a prefix with method routes
/** @var AdminRoute $classAdminRoute */
$classAdminRoute = $classAttributes[0]->newInstance();
}
// now, check for method-level attributes
foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
$methodAttributes = $method->getAttributes(AdminRoute::class);
if ([] === $methodAttributes) {
continue;
}
foreach ($methodAttributes as $methodAttribute) {
/** @var AdminRoute $methodAdminRoute */
$methodAdminRoute = $methodAttribute->newInstance();
// create route for the method
foreach ($this->dashboardControllers as $dashboardController) {
$dashboardFqcn = $dashboardController::class;
// Dashboard restrictions inheritance:
// - false: Not set - inherit from class attribute
// - null: Explicitly allow all (for allowed) or deny none (for denied)
// - []: Explicitly allow/deny none
// - [...]: Allow/deny specific dashboards
$allowedDashboards = false !== $methodAdminRoute->allowedDashboards
? $methodAdminRoute->allowedDashboards
: $classAdminRoute?->allowedDashboards;
$deniedDashboards = false !== $methodAdminRoute->deniedDashboards
? $methodAdminRoute->deniedDashboards
: $classAdminRoute?->deniedDashboards;
// skip if not in allowed dashboards (when restrictions are set)
if (\is_array($allowedDashboards) && !\in_array($dashboardFqcn, $allowedDashboards, true)) {
continue;
}
// skip if in denied dashboards (when restrictions are set)
if (\is_array($deniedDashboards) && \in_array($dashboardFqcn, $deniedDashboards, true)) {
continue;
}
$dashboardRouteConfig = $this->getDashboardsRouteConfig()[$dashboardFqcn];
// build the route path: dashboard + class prefix (if any) + method path
$routePathParts = [$dashboardRouteConfig['routePath']];
if (null !== $classAdminRoute?->path) {
// Use the explicit class-level AdminRoute path
$routePathParts[] = ltrim($classAdminRoute->path, '/');
}
if (null !== $methodAdminRoute->path) {
$routePathParts[] = ltrim($methodAdminRoute->path, '/');
}
$adminRoutePath = rtrim(implode('/', $routePathParts), '/');
// build the route name: dashboard + class prefix (if any) + method name
$routeNameParts = [$dashboardRouteConfig['routeName']];
if (null !== $classAdminRoute?->name) {
// Use the explicit class-level AdminRoute name
$routeNameParts[] = ltrim($classAdminRoute->name, '_');
}
if (null !== $methodAdminRoute->name) {
$routeNameParts[] = ltrim($methodAdminRoute->name, '_');
}
$adminRouteName = implode('_', $routeNameParts);
if (\in_array($adminRouteName, $addedRouteNames, true)) {
throw new \RuntimeException(sprintf('The #[AdminRoute] attribute applied to the "%s" method of the "%s" controller would create an admin route called "%s", which already exists. You must change the "routeName" argument to generate a different route name.', $method->name, $controllerFqcn, $adminRouteName));
}
// merge route options: method options override class options
$mergedRouteOptions = array_merge(
$classAdminRoute->options ?? [],
$methodAdminRoute->options
);
// create a new AdminRoute with merged configuration
$mergedAdminRoute = new AdminRoute(
path: $methodAdminRoute->path,
name: $methodAdminRoute->name,
options: $mergedRouteOptions,
allowedDashboards: $allowedDashboards,
deniedDashboards: $deniedDashboards
);
$adminRoute = $this->createRouteForAdminAttribute($mergedAdminRoute, $adminRoutePath, $dashboardFqcn, $controllerFqcn, $method->name);
$adminRoutes[$adminRouteName] = $adminRoute;
$addedRouteNames[] = $adminRouteName;
}
}
}
}
return $adminRoutes;
}
private function createRouteForAdminAttribute(AdminRoute $adminRouteAttribute, string $routePath, string $dashboardFqcn, string $controllerFqcn, string $methodName): Route
{
$route = new Route($routePath);
$defaults = [
'_controller' => $controllerFqcn.'::'.$methodName,
EA::ROUTE_CREATED_BY_EASYADMIN => true,
EA::DASHBOARD_CONTROLLER_FQCN => $dashboardFqcn,
EA::CRUD_CONTROLLER_FQCN => $controllerFqcn,
EA::CRUD_ACTION => $methodName,
];
self::applyAdminRouteOptions($route, $adminRouteAttribute->options, $defaults);
return $route;
}
/**
* Applies the options passed to an #[AdminRoute] attribute on a Symfony Route.
*
* The given $defaults are merged on top of any "defaults" defined in $options,
* so the framework-managed defaults (such as the controller FQCN) always win.
*
* @param array<string, mixed> $options
* @param array<string, mixed> $defaults
*/
private static function applyAdminRouteOptions(Route $route, array $options, array $defaults): void
{
if (isset($options['requirements'])) {
$route->setRequirements($options['requirements']);
}
if (isset($options['host'])) {
$route->setHost($options['host']);
}
if (isset($options['methods'])) {
$route->setMethods($options['methods']);
}
if (isset($options['schemes'])) {
$route->setSchemes($options['schemes']);
}
if (isset($options['condition'])) {
$route->setCondition($options['condition']);
}
$mergedDefaults = array_merge($options['defaults'] ?? [], $defaults);
if (isset($options['locale'])) {
$mergedDefaults['_locale'] = $options['locale'];
}
if (isset($options['format'])) {
$mergedDefaults['_format'] = $options['format'];
}
if (isset($options['stateless'])) {
$mergedDefaults['_stateless'] = $options['stateless'];
}
$route->setDefaults($mergedDefaults);
$nativeRouteOptions = $options['options'] ?? [];
if (isset($options['utf8'])) {
$nativeRouteOptions['utf8'] = $options['utf8'];
}
if ([] !== $nativeRouteOptions) {
$route->setOptions($nativeRouteOptions);
}
}
/**
* @param class-string<DashboardControllerInterface> $dashboardFqcn
*
* @return array{0: class-string[]|null, 1: class-string[]|null}
*/
private function getAllowedAndDeniedControllers(string $dashboardFqcn): array
{
if (null === $attribute = $this->getPhpAttributeInstance($dashboardFqcn, AdminDashboard::class)) {
return [null, null];
}
if (null !== $attribute->allowedControllers && null !== $attribute->deniedControllers) {
throw new \RuntimeException(sprintf('In the #[AdminDashboard] attribute of the "%s" dashboard controller, you cannot define both "allowedControllers" and "deniedControllers" at the same time because they are the exact opposite. Use only one of them.', $dashboardFqcn));
}
return [$attribute->allowedControllers, $attribute->deniedControllers];
}
/**
* @param class-string<DashboardControllerInterface> $dashboardFqcn
*
* @return array<string, array{routeName: string, routePath: string, methods?: array<string>}>
*/
private function getDefaultRoutesConfig(string $dashboardFqcn): array
{
if (null === $dashboardAttribute = $this->getPhpAttributeInstance($dashboardFqcn, AdminDashboard::class)) {
return self::DEFAULT_ROUTES_CONFIG;
}
if (null === $customRoutesConfig = $dashboardAttribute->routes) {
return self::DEFAULT_ROUTES_CONFIG;
}
foreach ($customRoutesConfig as $action => $customRouteConfig) {
if (\count(array_diff(array_keys($customRouteConfig), ['routePath', 'routeName'])) > 0) {
throw new \RuntimeException(sprintf('In the #[AdminDashboard] attribute of the "%s" dashboard controller, the route configuration for the "%s" action defines some unsupported keys. You can only define these keys: "routePath" and "routeName".', $dashboardFqcn, $action));
}
if (isset($customRouteConfig['routeName']) && 1 !== preg_match('/^[a-zA-Z0-9_-]+$/', $customRouteConfig['routeName'])) {
throw new \RuntimeException(sprintf('In the #[AdminDashboard] attribute of the "%s" dashboard controller, the route name "%s" for the "%s" action is not valid. It can only contain letter, numbers, dashes, and underscores.', $dashboardFqcn, $customRouteConfig['routeName'], $action));
}
if (isset($customRouteConfig['routePath']) && \in_array($action, [Action::EDIT, Action::DETAIL, Action::DELETE], true) && !str_contains($customRouteConfig['routePath'], '{entityId}')) {
throw new \RuntimeException(sprintf('In the #[AdminDashboard] attribute of the "%s" dashboard controller, the path for the "%s" action must contain the "{entityId}" placeholder.', $action, $dashboardFqcn));
}
}
return array_replace_recursive(self::DEFAULT_ROUTES_CONFIG, $customRoutesConfig);
}
/**
* @return array<class-string, array{routeName: string, routePath: string, routeOptions: array<string, mixed>}>
*/
private function getDashboardsRouteConfig(): array
{
$config = [];
foreach ($this->dashboardControllers as $dashboardController) {
$reflectionClass = new \ReflectionClass($dashboardController);
$attributes = $reflectionClass->getAttributes(AdminDashboard::class);
if ([] === $attributes) {
throw new \RuntimeException(sprintf('The "%s" dashboard controller must apply the #[AdminDashboard] attribute to define the route path and route name of the dashboard (e.g. #[AdminDashboard(routePath: \'/admin\', routeName: \'admin\')]). Using the default #[Route] attribute from Symfony on the "index()" method of the dashboard does no longer work.', $reflectionClass->getName()));
}
$adminDashboardAttribute = $attributes[0]->newInstance();
$routeName = $adminDashboardAttribute->routeName;
$routePath = $adminDashboardAttribute->routePath;
$routeOptions = $adminDashboardAttribute->routeOptions;
if (null !== $routePath) {
$routePath = rtrim($adminDashboardAttribute->routePath, '/');
}
if (null === $routeName || null === $routePath) {
throw new \RuntimeException(sprintf('The "%s" dashboard controller applies the #[AdminDashboard] attribute but it\'s missing either the "routePath" or "routeName" arguments or both. Check that you define both to properly configure the main route of your dashboard (e.g. #[AdminDashboard(routePath: \'/admin\', routeName: \'admin\')]). Using the default #[Route] attribute from Symfony on the "index()" method of the dashboard does no longer work.', $reflectionClass->getName()));
}
$config[$reflectionClass->getName()] = [
'routeName' => $routeName,
'routePath' => $routePath,
'routeOptions' => $routeOptions,
];
}
return $config;
}
/**
* @param class-string<CrudControllerInterface> $crudControllerFqcn
*
* @return array{routeName: string, routePath: string}
*/
private function getCrudControllerRouteConfig(string $crudControllerFqcn): array
{
$crudControllerConfig = [];
$reflectionClass = new \ReflectionClass($crudControllerFqcn);
// first, check for #[AdminRoute] attribute
$adminRouteAttributes = $reflectionClass->getAttributes(AdminRoute::class);
if ([] !== $adminRouteAttributes) {
/** @var AdminRoute $adminRouteInstance */
$adminRouteInstance = $adminRouteAttributes[0]->newInstance();
if (null !== $adminRouteInstance->path) {
$crudControllerConfig['routePath'] = trim($adminRouteInstance->path, '/');
}
if (null !== $adminRouteInstance->name) {
if (1 !== preg_match('/^[a-zA-Z0-9_-]+$/', $adminRouteInstance->name)) {
throw new \RuntimeException(sprintf('In the #[AdminRoute] attribute of the "%s" CRUD controller, the route name "%s" is not valid. It can only contain letters, numbers, dashes, and underscores.', $crudControllerFqcn, $adminRouteInstance->name));
}
$crudControllerConfig['routeName'] = trim($adminRouteInstance->name, '_');
}
}
// if the CRUD controller doesn't define any or all of the route configuration,
// use the default values based on the controller's class name
if (!\array_key_exists('routePath', $crudControllerConfig)) {
$crudControllerConfig['routePath'] = trim($this->transformCrudControllerNameToKebabCase($crudControllerFqcn), '/');
}
if (!\array_key_exists('routeName', $crudControllerConfig)) {
$crudControllerConfig['routeName'] = trim($this->transformCrudControllerNameToSnakeCase($crudControllerFqcn), '_');
}
return $crudControllerConfig;
}
/**
* @param class-string<CrudControllerInterface> $crudControllerFqcn
*
* @return array<string, array{routeName?: string, routePath?: string, methods?: array<string>}>
*/
private function getCustomActionsConfig(string $crudControllerFqcn): array
{
$customActionsConfig = [];
$reflectionClass = new \ReflectionClass($crudControllerFqcn);
$methods = $reflectionClass->getMethods();
foreach ($methods as $method) {
$action = $method->getName();
$adminRouteAttributes = $method->getAttributes(AdminRoute::class);
// process each AdminRoute attribute separately to support multiple routes per action
foreach ($adminRouteAttributes as $index => $adminRouteAttribute) {
/** @var AdminRoute $adminRouteInstance */
$adminRouteInstance = $adminRouteAttribute->newInstance();
// each route can define more than one route, so we cannot use the action name as the array key
$routeId = $action.'_route_'.++$index;
if (null !== $adminRouteInstance->path) {
if (\in_array($action, [Action::EDIT, Action::DETAIL, Action::DELETE], true) && !str_contains($adminRouteInstance->path, '{entityId}')) {
throw new \RuntimeException(sprintf('In the "%s" CRUD controller, the #[AdminRoute] attribute applied to the "%s()" action is missing the "{entityId}" placeholder in its route path.', $crudControllerFqcn, $action));
}
$customActionsConfig[$routeId]['routePath'] = $adminRouteInstance->path;
} else {
$customActionsConfig[$routeId]['routePath'] = null;
}
if (null !== $adminRouteInstance->name) {
if (1 !== preg_match('/^[a-zA-Z0-9_-]+$/', $adminRouteInstance->name)) {
throw new \RuntimeException(sprintf('In the "%s" CRUD controller, the #[AdminRoute] attribute applied to the "%s()" action defines an invalid route name: "%s". Valid route names can only contain letters, numbers, dashes, and underscores.', $crudControllerFqcn, $action, $adminRouteInstance->name));
}
$customActionsConfig[$routeId]['routeName'] = trim($adminRouteInstance->name, '_');
} else {
$customActionsConfig[$routeId]['routeName'] = null;
}
// handle methods from routeOptions or use smart defaults
$methods = $adminRouteInstance->options['methods'] ?? null;
if (null === $methods) {
// smart defaults: built-in actions have fixed methods, custom actions default to GET and POST
if (\in_array($action, [Action::INDEX, Action::DETAIL], true)) {
$methods = ['GET'];
} elseif (\in_array($action, [Action::NEW, Action::EDIT, Action::DELETE, Action::BATCH_DELETE], true)) {
$methods = ['GET', 'POST'];
} else {
// custom actions default to GET and POST
$methods = ['GET', 'POST'];
}
}
if (\is_string($methods)) {
$methods = [$methods];
}
// validate HTTP methods
$allowedMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD'];
foreach ($methods as $httpMethod) {
if (!\in_array(strtoupper($httpMethod), $allowedMethods, true)) {
throw new \RuntimeException(sprintf('In the "%s" CRUD controller, the #[AdminRoute] attribute applied to the "%s()" action includes "%s" as part of its HTTP methods. However, the only allowed HTTP methods are: %s', $crudControllerFqcn, $action, $httpMethod, implode(', ', $allowedMethods)));
}
}
$customActionsConfig[$routeId]['methods'] = array_map('strtoupper', $methods);
// store the actual action name for the route generation
$customActionsConfig[$routeId]['actionName'] = $action;
// keep the full set of options so they can be applied to the generated
// Symfony Route later (requirements, host, schemes, condition, etc.)
$customActionsConfig[$routeId]['adminRouteOptions'] = $adminRouteInstance->options;
}
}
return $customActionsConfig;
}
/**
* @param array<string, mixed> $routeOptions
* @param class-string<DashboardControllerInterface> $dashboardFqcn
*/
private function createDashboardRoute(string $routePath, array $routeOptions, string $dashboardFqcn): Route
{
$route = new Route($routePath);
$defaults = [
'_controller' => $dashboardFqcn.'::index',
EA::ROUTE_CREATED_BY_EASYADMIN => true,
EA::DASHBOARD_CONTROLLER_FQCN => $dashboardFqcn,
EA::CRUD_CONTROLLER_FQCN => null,
EA::CRUD_ACTION => null,
];
self::applyAdminRouteOptions($route, $routeOptions, $defaults);
return $route;
}
/**
* @template T of object
*
* @param class-string $classFqcn
* @param class-string<T> $attributeFqcn
*
* @return T|null
*/
private function getPhpAttributeInstance(string $classFqcn, string $attributeFqcn): ?object
{
$reflectionClass = new \ReflectionClass($classFqcn);
if ([] === $attributes = $reflectionClass->getAttributes($attributeFqcn)) {
return null;
}
return $attributes[0]->newInstance();
}
/**
* Transforms 'App\Controller\Admin\FooBarBazCrudController' into 'foo-bar-baz'.
*
* @param class-string<CrudControllerInterface> $crudControllerFqcn
*/
private function transformCrudControllerNameToKebabCase(string $crudControllerFqcn): string
{
$cleanShortName = preg_replace('/(?:Crud)?Controller$/', '', (new \ReflectionClass($crudControllerFqcn))->getShortName());
$snakeCaseName = strtolower(preg_replace('/(?<!^)[A-Z]/', '-$0', $cleanShortName));
return $snakeCaseName;
}
/**
* Transforms 'App\Controller\Admin\FooBarBazCrudController' into 'foo_bar_baz'.
*
* @param class-string<CrudControllerInterface> $crudControllerFqcn
*/
private function transformCrudControllerNameToSnakeCase(string $crudControllerFqcn): string
{
$shortName = preg_replace('/(?:Crud)?Controller$/', '', (new \ReflectionClass($crudControllerFqcn))->getShortName());
return strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $shortName));
}
/**
* @param Route[] $adminRoutes
*/
private function saveAdminRoutesInCache(array $adminRoutes): void
{
// to speedup the look up of routes in different parts of the bundle,
// we cache the admin routes in two different maps:
// 1) Routes related to dashboard controllers only
// 2) All admin routes (including the dashboard controller routes)
//
// for each cache, we store the data in the following maps to optimize lookups:
// 1) for Dashboard routes:
// $cache[dashboard fqcn] => dashboard_route_name
// 2) for all admin routes:
// 2.1) $cache[route_name] => [dashboard fqcn, CRUD controller fqcn, action]
// 2.2) $cache[dashboard fqcn][CRUD controller fqcn][action] => route_name
// first, add the routes of all the application dashboards; this is needed because in
// applications with multiple dashboards, EasyAdmin must be able to find the route data associated
// to each dashboard; otherwise, the URLs of the menu items when visiting the dashboard route will be wrong
$dashboardFqcnToRouteName = [];
foreach ($this->getDashboardsRouteConfig() as $dashboardFqcn => $dashboardRouteConfig) {
$dashboardFqcnToRouteName[$dashboardFqcn] = $dashboardRouteConfig['routeName'];
}
$dashboardFqcnToRouteNameItem = $this->cache->getItem(CacheKey::DASHBOARD_FQCN_TO_ROUTE);
$dashboardFqcnToRouteNameItem->set($dashboardFqcnToRouteName);
$this->cache->save($dashboardFqcnToRouteNameItem);
// then, add all the generated admin routes
$routeNameToRouteAttributes = [];
$routeFqcnToRouteName = [];
foreach ($adminRoutes as $routeName => $route) {
$routeNameToRouteAttributes[$routeName] = [
EA::DASHBOARD_CONTROLLER_FQCN => $route->getDefault(EA::DASHBOARD_CONTROLLER_FQCN),
EA::CRUD_CONTROLLER_FQCN => $route->getDefault(EA::CRUD_CONTROLLER_FQCN),
EA::CRUD_ACTION => $route->getDefault(EA::CRUD_ACTION),
];
$routeFqcnToRouteName[$route->getDefault(EA::DASHBOARD_CONTROLLER_FQCN)][$route->getDefault(EA::CRUD_CONTROLLER_FQCN) ?? ''][$route->getDefault(EA::CRUD_ACTION) ?? ''] = $routeName;
}
$routeNameToFqcnItem = $this->cache->getItem(CacheKey::ROUTE_NAME_TO_ATTRIBUTES);
$routeNameToFqcnItem->set($routeNameToRouteAttributes);
$this->cache->save($routeNameToFqcnItem);
$fqcnToRouteNameItem = $this->cache->getItem(CacheKey::ROUTE_ATTRIBUTES_TO_NAME);
$fqcnToRouteNameItem->set($routeFqcnToRouteName);
$this->cache->save($fqcnToRouteNameItem);
}
// This replaces the ControllerRegistry that existed in previous EasyAdmin versions.
// It stores two maps between CRUD controllers and their associated entity FQCN:
// controller_to_entity: $cache['crud_controller_fqcn'] => 'entity_fqcn'
// entity_to_controller: $cache['entity_fqcn'] => ['crud_controller_fqcn1', 'crud_controller_fqcn2', ...]
/**
* @param iterable<CrudControllerInterface> $crudControllers
*/
private function saveCrudControllersAndEntityFqcnMapInCache(iterable $crudControllers): void
{
$crudToEntityMap = [];
$entityToCrudMap = [];
foreach ($crudControllers as $crudController) {
$entityFqcn = $crudController::getEntityFqcn();
$crudToEntityMap[$crudController::class] = $entityFqcn;
if (!isset($entityToCrudMap[$entityFqcn])) {
$entityToCrudMap[$entityFqcn] = [];
}
$entityToCrudMap[$entityFqcn][] = $crudController::class;
}
$crudToEntityCacheItem = $this->cache->getItem(CacheKey::CRUD_FQCN_TO_ENTITY_FQCN);
$crudToEntityCacheItem->set($crudToEntityMap);
$this->cache->save($crudToEntityCacheItem);
$entityToCrudCacheItem = $this->cache->getItem(CacheKey::ENTITY_FQCN_TO_CRUD_FQCN);
$entityToCrudCacheItem->set($entityToCrudMap);
$this->cache->save($entityToCrudCacheItem);
}
}