vendor/easycorp/easyadmin-bundle/src/Factory/AdminContextFactory.php line 235

  1. <?php
  2. namespace EasyCorp\Bundle\EasyAdminBundle\Factory;
  3. use EasyCorp\Bundle\EasyAdminBundle\Cache\CacheWarmer;
  4. use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
  5. use EasyCorp\Bundle\EasyAdminBundle\Config\Option\EA;
  6. use EasyCorp\Bundle\EasyAdminBundle\Config\Option\TextDirection;
  7. use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
  8. use EasyCorp\Bundle\EasyAdminBundle\Contracts\Controller\CrudControllerInterface;
  9. use EasyCorp\Bundle\EasyAdminBundle\Contracts\Controller\DashboardControllerInterface;
  10. use EasyCorp\Bundle\EasyAdminBundle\Dto\ActionConfigDto;
  11. use EasyCorp\Bundle\EasyAdminBundle\Dto\AssetsDto;
  12. use EasyCorp\Bundle\EasyAdminBundle\Dto\CrudDto;
  13. use EasyCorp\Bundle\EasyAdminBundle\Dto\DashboardDto;
  14. use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
  15. use EasyCorp\Bundle\EasyAdminBundle\Dto\FilterConfigDto;
  16. use EasyCorp\Bundle\EasyAdminBundle\Dto\I18nDto;
  17. use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
  18. use EasyCorp\Bundle\EasyAdminBundle\Registry\CrudControllerRegistry;
  19. use EasyCorp\Bundle\EasyAdminBundle\Registry\TemplateRegistry;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  22. use Symfony\Component\Security\Core\User\UserInterface;
  23. use function Symfony\Component\String\u;
  24. use function Symfony\Component\Translation\t;
  25. use Symfony\Contracts\Translation\TranslatableInterface;
  26. /**
  27.  * @author Javier Eguiluz <javier.eguiluz@gmail.com>
  28.  */
  29. final class AdminContextFactory
  30. {
  31.     private string $cacheDir;
  32.     private ?TokenStorageInterface $tokenStorage;
  33.     private MenuFactory $menuFactory;
  34.     private CrudControllerRegistry $crudControllers;
  35.     private EntityFactory $entityFactory;
  36.     public function __construct(string $cacheDir, ?TokenStorageInterface $tokenStorage, MenuFactory $menuFactory, CrudControllerRegistry $crudControllers, EntityFactory $entityFactory)
  37.     {
  38.         $this->cacheDir = $cacheDir;
  39.         $this->tokenStorage = $tokenStorage;
  40.         $this->menuFactory = $menuFactory;
  41.         $this->crudControllers = $crudControllers;
  42.         $this->entityFactory = $entityFactory;
  43.     }
  44.     public function create(Request $request, DashboardControllerInterface $dashboardController, ?CrudControllerInterface $crudController): AdminContext
  45.     {
  46.         $crudAction = $request->query->get(EA::CRUD_ACTION);
  47.         $validPageNames = [Crud::PAGE_INDEX, Crud::PAGE_DETAIL, Crud::PAGE_EDIT, Crud::PAGE_NEW];
  48.         $pageName = \in_array($crudAction, $validPageNames, true) ? $crudAction : null;
  49.         $dashboardDto = $this->getDashboardDto($request, $dashboardController);
  50.         $assetDto = $this->getAssetDto($dashboardController, $crudController, $pageName);
  51.         $actionConfigDto = $this->getActionConfig($dashboardController, $crudController, $pageName);
  52.         $filters = $this->getFilters($dashboardController, $crudController);
  53.         $crudDto = $this->getCrudDto($this->crudControllers, $dashboardController, $crudController, $actionConfigDto, $filters, $crudAction, $pageName);
  54.         $entityDto = $this->getEntityDto($request, $crudDto);
  55.         $searchDto = $this->getSearchDto($request, $crudDto);
  56.         $i18nDto = $this->getI18nDto($request, $dashboardDto, $crudDto, $entityDto);
  57.         $templateRegistry = $this->getTemplateRegistry($dashboardController, $crudDto);
  58.         $user = $this->getUser($this->tokenStorage);
  59.         return new AdminContext($request, $user, $i18nDto, $this->crudControllers, $dashboardDto, $dashboardController, $assetDto, $crudDto, $entityDto, $searchDto, $this->menuFactory, $templateRegistry);
  60.     }
  61.     private function getDashboardDto(Request $request, DashboardControllerInterface $dashboardControllerInstance): DashboardDto
  62.     {
  63.         $dashboardRoutesCachePath = $this->cacheDir.'/'.CacheWarmer::DASHBOARD_ROUTES_CACHE;
  64.         $dashboardControllerRoutes = !file_exists($dashboardRoutesCachePath) ? [] : require $dashboardRoutesCachePath;
  65.         $dashboardController = $dashboardControllerInstance::class.'::index';
  66.         $dashboardRouteName = null;
  67.         foreach ($dashboardControllerRoutes as $routeName => $controller) {
  68.             if ($controller === $dashboardController) {
  69.                 // if present, remove the suffix of i18n route names (it's a two-letter locale at the end
  70.                 // of the route name; e.g. 'dashboard.en' -> remove '.en', 'admin.index.es' -> remove '.es')
  71.                 $dashboardRouteName = preg_replace('~\.\w{2}$~', '', $routeName);
  72.                 break;
  73.             }
  74.         }
  75.         if (null === $dashboardRouteName) {
  76.             throw new \RuntimeException(sprintf('The name of the route associated to "%s" cannot be determined. Clear the application cache to run the EasyAdmin cache warmer, which generates the needed data to find this route.', $dashboardController));
  77.         }
  78.         $dashboardDto = $dashboardControllerInstance->configureDashboard()->getAsDto();
  79.         $dashboardDto->setRouteName($dashboardRouteName);
  80.         return $dashboardDto;
  81.     }
  82.     private function getAssetDto(DashboardControllerInterface $dashboardController, ?CrudControllerInterface $crudController, ?string $pageName): AssetsDto
  83.     {
  84.         $defaultAssets = $dashboardController->configureAssets();
  85.         if (null === $crudController) {
  86.             return $defaultAssets->getAsDto();
  87.         }
  88.         return $crudController->configureAssets($defaultAssets)->getAsDto()->loadedOn($pageName);
  89.     }
  90.     private function getCrudDto(CrudControllerRegistry $crudControllers, DashboardControllerInterface $dashboardController, ?CrudControllerInterface $crudController, ActionConfigDto $actionConfigDto, FilterConfigDto $filters, ?string $crudAction, ?string $pageName): ?CrudDto
  91.     {
  92.         if (null === $crudController) {
  93.             return null;
  94.         }
  95.         $defaultCrud = $dashboardController->configureCrud();
  96.         $crudDto = $crudController->configureCrud($defaultCrud)->getAsDto();
  97.         $entityFqcn = $crudControllers->findEntityFqcnByCrudFqcn($crudController::class);
  98.         $crudDto->setControllerFqcn($crudController::class);
  99.         $crudDto->setActionsConfig($actionConfigDto);
  100.         $crudDto->setFiltersConfig($filters);
  101.         $crudDto->setCurrentAction($crudAction);
  102.         $crudDto->setEntityFqcn($entityFqcn);
  103.         $crudDto->setPageName($pageName);
  104.         return $crudDto;
  105.     }
  106.     private function getActionConfig(DashboardControllerInterface $dashboardController, ?CrudControllerInterface $crudController, ?string $pageName): ActionConfigDto
  107.     {
  108.         if (null === $crudController) {
  109.             return new ActionConfigDto();
  110.         }
  111.         $defaultActionConfig = $dashboardController->configureActions();
  112.         return $crudController->configureActions($defaultActionConfig)->getAsDto($pageName);
  113.     }
  114.     private function getFilters(DashboardControllerInterface $dashboardController, ?CrudControllerInterface $crudController): FilterConfigDto
  115.     {
  116.         if (null === $crudController) {
  117.             return new FilterConfigDto();
  118.         }
  119.         $defaultFilterConfig = $dashboardController->configureFilters();
  120.         return $crudController->configureFilters($defaultFilterConfig)->getAsDto();
  121.     }
  122.     private function getTemplateRegistry(DashboardControllerInterface $dashboardController, ?CrudDto $crudDto): TemplateRegistry
  123.     {
  124.         $templateRegistry = TemplateRegistry::new();
  125.         $defaultCrudDto = $dashboardController->configureCrud()->getAsDto();
  126.         $templateRegistry->setTemplates($defaultCrudDto->getOverriddenTemplates());
  127.         if (null !== $crudDto) {
  128.             $templateRegistry->setTemplates($crudDto->getOverriddenTemplates());
  129.         }
  130.         return $templateRegistry;
  131.     }
  132.     private function getI18nDto(Request $request, DashboardDto $dashboardDto, ?CrudDto $crudDto, ?EntityDto $entityDto): I18nDto
  133.     {
  134.         $locale = $request->getLocale();
  135.         $configuredTextDirection = $dashboardDto->getTextDirection();
  136.         $localePrefix = strtolower(substr($locale, 0, 2));
  137.         $defaultTextDirection = \in_array($localePrefix, ['ar', 'fa', 'he'], true) ? TextDirection::RTL : TextDirection::LTR;
  138.         $textDirection = $configuredTextDirection ?? $defaultTextDirection;
  139.         $translationDomain = $dashboardDto->getTranslationDomain();
  140.         $translationParameters = [];
  141.         if (null !== $crudDto) {
  142.             $translationParameters['%entity_name%'] = $entityName = basename(str_replace('\\', '/', $crudDto->getEntityFqcn()));
  143.             $translationParameters['%entity_as_string%'] = null === $entityDto ? '' : $entityDto->toString();
  144.             $translationParameters['%entity_id%'] = $entityId = $request->query->get(EA::ENTITY_ID);
  145.             $translationParameters['%entity_short_id%'] = null === $entityId ? null : u($entityId)->truncate(7)->toString();
  146.             $entityInstance = null === $entityDto ? null : $entityDto->getInstance();
  147.             $pageName = $crudDto->getCurrentPage();
  148.             $singularLabel = $crudDto->getEntityLabelInSingular($entityInstance, $pageName);
  149.             if (!$singularLabel instanceof TranslatableInterface) {
  150.                 $singularLabel = t($singularLabel ?? $entityName, $translationParameters, $translationDomain);
  151.             }
  152.             $pluralLabel = $crudDto->getEntityLabelInPlural($entityInstance, $pageName);
  153.             if (!$pluralLabel instanceof TranslatableInterface) {
  154.                 $pluralLabel = t($pluralLabel ?? $entityName, $translationParameters, $translationDomain);
  155.             }
  156.             $crudDto->setEntityLabelInSingular($singularLabel);
  157.             $crudDto->setEntityLabelInPlural($pluralLabel);
  158.             $translationParameters['%entity_label_singular%'] = $singularLabel;
  159.             $translationParameters['%entity_label_plural%'] = $pluralLabel;
  160.         }
  161.         return new I18nDto($locale, $textDirection, $translationDomain, $translationParameters);
  162.     }
  163.     public function getSearchDto(Request $request, ?CrudDto $crudDto): ?SearchDto
  164.     {
  165.         if (null === $crudDto) {
  166.             return null;
  167.         }
  168.         $queryParams = $request->query->all();
  169.         $searchableProperties = $crudDto->getSearchFields();
  170.         $query = $queryParams[EA::QUERY] ?? null;
  171.         $defaultSort = $crudDto->getDefaultSort();
  172.         $customSort = $queryParams[EA::SORT] ?? [];
  173.         $appliedFilters = $queryParams[EA::FILTERS] ?? [];
  174.         return new SearchDto($request, $searchableProperties, $query, $defaultSort, $customSort, $appliedFilters);
  175.     }
  176.     // Copied from https://github.com/symfony/twig-bridge/blob/master/AppVariable.php
  177.     // (c) Fabien Potencier <fabien@symfony.com> - MIT License
  178.     private function getUser(?TokenStorageInterface $tokenStorage): ?UserInterface
  179.     {
  180.         if (null === $token = $tokenStorage?->getToken()) {
  181.             return null;
  182.         }
  183.         $user = $token->getUser();
  184.         return \is_object($user) ? $user : null;
  185.     }
  186.     private function getEntityDto(Request $request, ?CrudDto $crudDto): ?EntityDto
  187.     {
  188.         if (null === $crudDto) {
  189.             return null;
  190.         }
  191.         return $this->entityFactory->create($crudDto->getEntityFqcn(), $request->query->get(EA::ENTITY_ID), $crudDto->getEntityPermission());
  192.     }
  193. }