vendor/symfony/framework-bundle/DependencyInjection/FrameworkExtension.php line 214

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Bundle\FrameworkBundle\DependencyInjection;
  11. use Doctrine\Common\Annotations\AnnotationRegistry;
  12. use Doctrine\Common\Annotations\Reader;
  13. use Http\Client\HttpClient;
  14. use Psr\Cache\CacheItemPoolInterface;
  15. use Psr\Container\ContainerInterface as PsrContainerInterface;
  16. use Psr\EventDispatcher\EventDispatcherInterface as PsrEventDispatcherInterface;
  17. use Psr\Http\Client\ClientInterface;
  18. use Psr\Log\LoggerAwareInterface;
  19. use Symfony\Bridge\Monolog\Processor\DebugProcessor;
  20. use Symfony\Bridge\Twig\Extension\CsrfExtension;
  21. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  22. use Symfony\Bundle\FrameworkBundle\Routing\AnnotatedRouteControllerLoader;
  23. use Symfony\Bundle\FrameworkBundle\Routing\RouteLoaderInterface;
  24. use Symfony\Bundle\FullStack;
  25. use Symfony\Component\Asset\PackageInterface;
  26. use Symfony\Component\BrowserKit\AbstractBrowser;
  27. use Symfony\Component\Cache\Adapter\AdapterInterface;
  28. use Symfony\Component\Cache\Adapter\ArrayAdapter;
  29. use Symfony\Component\Cache\Adapter\ChainAdapter;
  30. use Symfony\Component\Cache\Adapter\TagAwareAdapter;
  31. use Symfony\Component\Cache\DependencyInjection\CachePoolPass;
  32. use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
  33. use Symfony\Component\Cache\Marshaller\MarshallerInterface;
  34. use Symfony\Component\Cache\ResettableInterface;
  35. use Symfony\Component\Config\FileLocator;
  36. use Symfony\Component\Config\Loader\LoaderInterface;
  37. use Symfony\Component\Config\Resource\DirectoryResource;
  38. use Symfony\Component\Config\ResourceCheckerInterface;
  39. use Symfony\Component\Console\Application;
  40. use Symfony\Component\Console\Command\Command;
  41. use Symfony\Component\DependencyInjection\Alias;
  42. use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
  43. use Symfony\Component\DependencyInjection\ChildDefinition;
  44. use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
  45. use Symfony\Component\DependencyInjection\ContainerBuilder;
  46. use Symfony\Component\DependencyInjection\ContainerInterface;
  47. use Symfony\Component\DependencyInjection\Definition;
  48. use Symfony\Component\DependencyInjection\EnvVarLoaderInterface;
  49. use Symfony\Component\DependencyInjection\EnvVarProcessorInterface;
  50. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  51. use Symfony\Component\DependencyInjection\Exception\LogicException;
  52. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  53. use Symfony\Component\DependencyInjection\Parameter;
  54. use Symfony\Component\DependencyInjection\Reference;
  55. use Symfony\Component\DependencyInjection\ServiceLocator;
  56. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  57. use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
  58. use Symfony\Component\Finder\Finder;
  59. use Symfony\Component\Form\ChoiceList\Factory\CachingFactoryDecorator;
  60. use Symfony\Component\Form\FormTypeExtensionInterface;
  61. use Symfony\Component\Form\FormTypeGuesserInterface;
  62. use Symfony\Component\Form\FormTypeInterface;
  63. use Symfony\Component\HttpClient\ScopingHttpClient;
  64. use Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface;
  65. use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
  66. use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
  67. use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface;
  68. use Symfony\Component\HttpKernel\DependencyInjection\Extension;
  69. use Symfony\Component\Lock\Lock;
  70. use Symfony\Component\Lock\LockFactory;
  71. use Symfony\Component\Lock\LockInterface;
  72. use Symfony\Component\Lock\PersistingStoreInterface;
  73. use Symfony\Component\Lock\Store\StoreFactory;
  74. use Symfony\Component\Mailer\Bridge\Amazon\Transport\SesTransportFactory;
  75. use Symfony\Component\Mailer\Bridge\Google\Transport\GmailTransportFactory;
  76. use Symfony\Component\Mailer\Bridge\Mailchimp\Transport\MandrillTransportFactory;
  77. use Symfony\Component\Mailer\Bridge\Mailgun\Transport\MailgunTransportFactory;
  78. use Symfony\Component\Mailer\Bridge\Postmark\Transport\PostmarkTransportFactory;
  79. use Symfony\Component\Mailer\Bridge\Sendgrid\Transport\SendgridTransportFactory;
  80. use Symfony\Component\Mailer\Mailer;
  81. use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
  82. use Symfony\Component\Messenger\MessageBus;
  83. use Symfony\Component\Messenger\MessageBusInterface;
  84. use Symfony\Component\Messenger\Transport\TransportFactoryInterface;
  85. use Symfony\Component\Messenger\Transport\TransportInterface;
  86. use Symfony\Component\Mime\MimeTypeGuesserInterface;
  87. use Symfony\Component\Mime\MimeTypes;
  88. use Symfony\Component\Notifier\Bridge\Nexmo\NexmoTransportFactory;
  89. use Symfony\Component\Notifier\Bridge\Slack\SlackTransportFactory;
  90. use Symfony\Component\Notifier\Bridge\Telegram\TelegramTransportFactory;
  91. use Symfony\Component\Notifier\Bridge\Twilio\TwilioTransportFactory;
  92. use Symfony\Component\Notifier\Notifier;
  93. use Symfony\Component\Notifier\Recipient\AdminRecipient;
  94. use Symfony\Component\PropertyAccess\PropertyAccessor;
  95. use Symfony\Component\PropertyInfo\PropertyAccessExtractorInterface;
  96. use Symfony\Component\PropertyInfo\PropertyDescriptionExtractorInterface;
  97. use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
  98. use Symfony\Component\PropertyInfo\PropertyInitializableExtractorInterface;
  99. use Symfony\Component\PropertyInfo\PropertyListExtractorInterface;
  100. use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
  101. use Symfony\Component\Routing\Loader\AnnotationDirectoryLoader;
  102. use Symfony\Component\Routing\Loader\AnnotationFileLoader;
  103. use Symfony\Component\Security\Core\Security;
  104. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  105. use Symfony\Component\Serializer\Encoder\DecoderInterface;
  106. use Symfony\Component\Serializer\Encoder\EncoderInterface;
  107. use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
  108. use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
  109. use Symfony\Component\Stopwatch\Stopwatch;
  110. use Symfony\Component\String\Slugger\SluggerInterface;
  111. use Symfony\Component\Translation\Command\XliffLintCommand as BaseXliffLintCommand;
  112. use Symfony\Component\Translation\Translator;
  113. use Symfony\Component\Validator\ConstraintValidatorInterface;
  114. use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader;
  115. use Symfony\Component\Validator\ObjectInitializerInterface;
  116. use Symfony\Component\WebLink\HttpHeaderSerializer;
  117. use Symfony\Component\Workflow;
  118. use Symfony\Component\Workflow\WorkflowInterface;
  119. use Symfony\Component\Yaml\Command\LintCommand as BaseYamlLintCommand;
  120. use Symfony\Component\Yaml\Yaml;
  121. use Symfony\Contracts\Cache\CacheInterface;
  122. use Symfony\Contracts\Cache\TagAwareCacheInterface;
  123. use Symfony\Contracts\HttpClient\HttpClientInterface;
  124. use Symfony\Contracts\Service\ResetInterface;
  125. use Symfony\Contracts\Service\ServiceSubscriberInterface;
  126. use Symfony\Contracts\Translation\LocaleAwareInterface;
  127. /**
  128.  * FrameworkExtension.
  129.  *
  130.  * @author Fabien Potencier <fabien@symfony.com>
  131.  * @author Jeremy Mikola <jmikola@gmail.com>
  132.  * @author Kévin Dunglas <dunglas@gmail.com>
  133.  * @author Grégoire Pineau <lyrixx@lyrixx.info>
  134.  */
  135. class FrameworkExtension extends Extension
  136. {
  137.     private $formConfigEnabled false;
  138.     private $translationConfigEnabled false;
  139.     private $sessionConfigEnabled false;
  140.     private $annotationsConfigEnabled false;
  141.     private $validatorConfigEnabled false;
  142.     private $messengerConfigEnabled false;
  143.     private $mailerConfigEnabled false;
  144.     private $httpClientConfigEnabled false;
  145.     /**
  146.      * Responds to the app.config configuration parameter.
  147.      *
  148.      * @throws LogicException
  149.      */
  150.     public function load(array $configsContainerBuilder $container)
  151.     {
  152.         $loader = new XmlFileLoader($container, new FileLocator(\dirname(__DIR__).'/Resources/config'));
  153.         $loader->load('web.xml');
  154.         $loader->load('services.xml');
  155.         $loader->load('fragment_renderer.xml');
  156.         $loader->load('error_renderer.xml');
  157.         if (interface_exists(PsrEventDispatcherInterface::class)) {
  158.             $container->setAlias(PsrEventDispatcherInterface::class, 'event_dispatcher');
  159.         }
  160.         $container->registerAliasForArgument('parameter_bag'PsrContainerInterface::class);
  161.         if (class_exists(Application::class)) {
  162.             $loader->load('console.xml');
  163.             if (!class_exists(BaseXliffLintCommand::class)) {
  164.                 $container->removeDefinition('console.command.xliff_lint');
  165.             }
  166.             if (!class_exists(BaseYamlLintCommand::class)) {
  167.                 $container->removeDefinition('console.command.yaml_lint');
  168.             }
  169.         }
  170.         // Load Cache configuration first as it is used by other components
  171.         $loader->load('cache.xml');
  172.         $configuration $this->getConfiguration($configs$container);
  173.         $config $this->processConfiguration($configuration$configs);
  174.         $this->annotationsConfigEnabled $this->isConfigEnabled($container$config['annotations']);
  175.         $this->translationConfigEnabled $this->isConfigEnabled($container$config['translator']);
  176.         // A translator must always be registered (as support is included by
  177.         // default in the Form and Validator component). If disabled, an identity
  178.         // translator will be used and everything will still work as expected.
  179.         if ($this->isConfigEnabled($container$config['translator']) || $this->isConfigEnabled($container$config['form']) || $this->isConfigEnabled($container$config['validation'])) {
  180.             if (!class_exists('Symfony\Component\Translation\Translator') && $this->isConfigEnabled($container$config['translator'])) {
  181.                 throw new LogicException('Translation support cannot be enabled as the Translation component is not installed. Try running "composer require symfony/translation".');
  182.             }
  183.             if (class_exists(Translator::class)) {
  184.                 $loader->load('identity_translator.xml');
  185.             }
  186.         }
  187.         // If the slugger is used but the String component is not available, we should throw an error
  188.         if (!interface_exists(SluggerInterface::class)) {
  189.             $container->register('slugger''stdClass')
  190.                 ->addError('You cannot use the "slugger" service since the String component is not installed. Try running "composer require symfony/string".');
  191.         } else {
  192.             if (!interface_exists(LocaleAwareInterface::class)) {
  193.                 $container->register('slugger''stdClass')
  194.                     ->addError('You cannot use the "slugger" service since the Translation contracts are not installed. Try running "composer require symfony/translation".');
  195.             }
  196.             if (!\extension_loaded('intl') && !\defined('PHPUNIT_COMPOSER_INSTALL')) {
  197.                 @trigger_error('Please install the "intl" PHP extension for best performance.'E_USER_DEPRECATED);
  198.             }
  199.         }
  200.         if (isset($config['secret'])) {
  201.             $container->setParameter('kernel.secret'$config['secret']);
  202.         }
  203.         $container->setParameter('kernel.http_method_override'$config['http_method_override']);
  204.         $container->setParameter('kernel.trusted_hosts'$config['trusted_hosts']);
  205.         $container->setParameter('kernel.default_locale'$config['default_locale']);
  206.         $container->setParameter('kernel.error_controller'$config['error_controller']);
  207.         if (!$container->hasParameter('debug.file_link_format')) {
  208.             $links = [
  209.                 'textmate' => 'txmt://open?url=file://%%f&line=%%l',
  210.                 'macvim' => 'mvim://open?url=file://%%f&line=%%l',
  211.                 'emacs' => 'emacs://open?url=file://%%f&line=%%l',
  212.                 'sublime' => 'subl://open?url=file://%%f&line=%%l',
  213.                 'phpstorm' => 'phpstorm://open?file=%%f&line=%%l',
  214.                 'atom' => 'atom://core/open/file?filename=%%f&line=%%l',
  215.                 'vscode' => 'vscode://file/%%f:%%l',
  216.             ];
  217.             $ide $config['ide'];
  218.             // mark any env vars found in the ide setting as used
  219.             $container->resolveEnvPlaceholders($ide);
  220.             $container->setParameter('debug.file_link_format'str_replace('%''%%'ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format')) ?: (isset($links[$ide]) ? $links[$ide] : $ide));
  221.         }
  222.         if (!empty($config['test'])) {
  223.             $loader->load('test.xml');
  224.             if (!class_exists(AbstractBrowser::class)) {
  225.                 $container->removeDefinition('test.client');
  226.             }
  227.         }
  228.         // register cache before session so both can share the connection services
  229.         $this->registerCacheConfiguration($config['cache'], $container);
  230.         if ($this->isConfigEnabled($container$config['session'])) {
  231.             if (!\extension_loaded('session')) {
  232.                 throw new LogicException('Session support cannot be enabled as the session extension is not installed. See https://php.net/session.installation for instructions.');
  233.             }
  234.             $this->sessionConfigEnabled true;
  235.             $this->registerSessionConfiguration($config['session'], $container$loader);
  236.             if (!empty($config['test'])) {
  237.                 $container->getDefinition('test.session.listener')->setArgument(1'%session.storage.options%');
  238.             }
  239.         }
  240.         if ($this->isConfigEnabled($container$config['request'])) {
  241.             $this->registerRequestConfiguration($config['request'], $container$loader);
  242.         }
  243.         if (null === $config['csrf_protection']['enabled']) {
  244.             $config['csrf_protection']['enabled'] = $this->sessionConfigEnabled && !class_exists(FullStack::class) && interface_exists(CsrfTokenManagerInterface::class);
  245.         }
  246.         $this->registerSecurityCsrfConfiguration($config['csrf_protection'], $container$loader);
  247.         if ($this->isConfigEnabled($container$config['form'])) {
  248.             if (!class_exists('Symfony\Component\Form\Form')) {
  249.                 throw new LogicException('Form support cannot be enabled as the Form component is not installed. Try running "composer require symfony/form".');
  250.             }
  251.             $this->formConfigEnabled true;
  252.             $this->registerFormConfiguration($config$container$loader);
  253.             if (class_exists('Symfony\Component\Validator\Validation')) {
  254.                 $config['validation']['enabled'] = true;
  255.             } else {
  256.                 $container->setParameter('validator.translation_domain''validators');
  257.                 $container->removeDefinition('form.type_extension.form.validator');
  258.                 $container->removeDefinition('form.type_guesser.validator');
  259.             }
  260.         } else {
  261.             $container->removeDefinition('console.command.form_debug');
  262.         }
  263.         if ($this->isConfigEnabled($container$config['assets'])) {
  264.             if (!class_exists('Symfony\Component\Asset\Package')) {
  265.                 throw new LogicException('Asset support cannot be enabled as the Asset component is not installed. Try running "composer require symfony/asset".');
  266.             }
  267.             $this->registerAssetsConfiguration($config['assets'], $container$loader);
  268.         }
  269.         if ($this->messengerConfigEnabled $this->isConfigEnabled($container$config['messenger'])) {
  270.             $this->registerMessengerConfiguration($config['messenger'], $container$loader$config['validation']);
  271.         } else {
  272.             $container->removeDefinition('console.command.messenger_consume_messages');
  273.             $container->removeDefinition('console.command.messenger_debug');
  274.             $container->removeDefinition('console.command.messenger_stop_workers');
  275.             $container->removeDefinition('console.command.messenger_setup_transports');
  276.             $container->removeDefinition('console.command.messenger_failed_messages_retry');
  277.             $container->removeDefinition('console.command.messenger_failed_messages_show');
  278.             $container->removeDefinition('console.command.messenger_failed_messages_remove');
  279.         }
  280.         if ($this->httpClientConfigEnabled $this->isConfigEnabled($container$config['http_client'])) {
  281.             $this->registerHttpClientConfiguration($config['http_client'], $container$loader$config['profiler']);
  282.         }
  283.         if ($this->mailerConfigEnabled $this->isConfigEnabled($container$config['mailer'])) {
  284.             $this->registerMailerConfiguration($config['mailer'], $container$loader);
  285.         }
  286.         if ($this->isConfigEnabled($container$config['notifier'])) {
  287.             $this->registerNotifierConfiguration($config['notifier'], $container$loader);
  288.         }
  289.         $propertyInfoEnabled $this->isConfigEnabled($container$config['property_info']);
  290.         $this->registerValidationConfiguration($config['validation'], $container$loader$propertyInfoEnabled);
  291.         $this->registerEsiConfiguration($config['esi'], $container$loader);
  292.         $this->registerSsiConfiguration($config['ssi'], $container$loader);
  293.         $this->registerFragmentsConfiguration($config['fragments'], $container$loader);
  294.         $this->registerTranslatorConfiguration($config['translator'], $container$loader$config['default_locale']);
  295.         $this->registerProfilerConfiguration($config['profiler'], $container$loader);
  296.         $this->registerWorkflowConfiguration($config['workflows'], $container$loader);
  297.         $this->registerDebugConfiguration($config['php_errors'], $container$loader);
  298.         $this->registerRouterConfiguration($config['router'], $container$loader);
  299.         $this->registerAnnotationsConfiguration($config['annotations'], $container$loader);
  300.         $this->registerPropertyAccessConfiguration($config['property_access'], $container$loader);
  301.         $this->registerSecretsConfiguration($config['secrets'], $container$loader);
  302.         if ($this->isConfigEnabled($container$config['serializer'])) {
  303.             if (!class_exists('Symfony\Component\Serializer\Serializer')) {
  304.                 throw new LogicException('Serializer support cannot be enabled as the Serializer component is not installed. Try running "composer require symfony/serializer-pack".');
  305.             }
  306.             $this->registerSerializerConfiguration($config['serializer'], $container$loader);
  307.         }
  308.         if ($propertyInfoEnabled) {
  309.             $this->registerPropertyInfoConfiguration($container$loader);
  310.         }
  311.         if ($this->isConfigEnabled($container$config['lock'])) {
  312.             $this->registerLockConfiguration($config['lock'], $container$loader);
  313.         }
  314.         if ($this->isConfigEnabled($container$config['web_link'])) {
  315.             if (!class_exists(HttpHeaderSerializer::class)) {
  316.                 throw new LogicException('WebLink support cannot be enabled as the WebLink component is not installed. Try running "composer require symfony/weblink".');
  317.             }
  318.             $loader->load('web_link.xml');
  319.         }
  320.         $this->addAnnotatedClassesToCompile([
  321.             '**\\Controller\\',
  322.             '**\\Entity\\',
  323.             // Added explicitly so that we don't rely on the class map being dumped to make it work
  324.             'Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController',
  325.         ]);
  326.         if (class_exists(MimeTypes::class)) {
  327.             $loader->load('mime_type.xml');
  328.         }
  329.         $container->registerForAutoconfiguration(Command::class)
  330.             ->addTag('console.command');
  331.         $container->registerForAutoconfiguration(ResourceCheckerInterface::class)
  332.             ->addTag('config_cache.resource_checker');
  333.         $container->registerForAutoconfiguration(EnvVarLoaderInterface::class)
  334.             ->addTag('container.env_var_loader');
  335.         $container->registerForAutoconfiguration(EnvVarProcessorInterface::class)
  336.             ->addTag('container.env_var_processor');
  337.         $container->registerForAutoconfiguration(ServiceLocator::class)
  338.             ->addTag('container.service_locator');
  339.         $container->registerForAutoconfiguration(ServiceSubscriberInterface::class)
  340.             ->addTag('container.service_subscriber');
  341.         $container->registerForAutoconfiguration(ArgumentValueResolverInterface::class)
  342.             ->addTag('controller.argument_value_resolver');
  343.         $container->registerForAutoconfiguration(AbstractController::class)
  344.             ->addTag('controller.service_arguments');
  345.         $container->registerForAutoconfiguration('Symfony\Bundle\FrameworkBundle\Controller\Controller')
  346.             ->addTag('controller.service_arguments');
  347.         $container->registerForAutoconfiguration(DataCollectorInterface::class)
  348.             ->addTag('data_collector');
  349.         $container->registerForAutoconfiguration(FormTypeInterface::class)
  350.             ->addTag('form.type');
  351.         $container->registerForAutoconfiguration(FormTypeGuesserInterface::class)
  352.             ->addTag('form.type_guesser');
  353.         $container->registerForAutoconfiguration(FormTypeExtensionInterface::class)
  354.             ->addTag('form.type_extension');
  355.         $container->registerForAutoconfiguration(CacheClearerInterface::class)
  356.             ->addTag('kernel.cache_clearer');
  357.         $container->registerForAutoconfiguration(CacheWarmerInterface::class)
  358.             ->addTag('kernel.cache_warmer');
  359.         $container->registerForAutoconfiguration(EventSubscriberInterface::class)
  360.             ->addTag('kernel.event_subscriber');
  361.         $container->registerForAutoconfiguration(LocaleAwareInterface::class)
  362.             ->addTag('kernel.locale_aware');
  363.         $container->registerForAutoconfiguration(ResetInterface::class)
  364.             ->addTag('kernel.reset', ['method' => 'reset']);
  365.         if (!interface_exists(MarshallerInterface::class)) {
  366.             $container->registerForAutoconfiguration(ResettableInterface::class)
  367.                 ->addTag('kernel.reset', ['method' => 'reset']);
  368.         }
  369.         $container->registerForAutoconfiguration(PropertyListExtractorInterface::class)
  370.             ->addTag('property_info.list_extractor');
  371.         $container->registerForAutoconfiguration(PropertyTypeExtractorInterface::class)
  372.             ->addTag('property_info.type_extractor');
  373.         $container->registerForAutoconfiguration(PropertyDescriptionExtractorInterface::class)
  374.             ->addTag('property_info.description_extractor');
  375.         $container->registerForAutoconfiguration(PropertyAccessExtractorInterface::class)
  376.             ->addTag('property_info.access_extractor');
  377.         $container->registerForAutoconfiguration(PropertyInitializableExtractorInterface::class)
  378.             ->addTag('property_info.initializable_extractor');
  379.         $container->registerForAutoconfiguration(EncoderInterface::class)
  380.             ->addTag('serializer.encoder');
  381.         $container->registerForAutoconfiguration(DecoderInterface::class)
  382.             ->addTag('serializer.encoder');
  383.         $container->registerForAutoconfiguration(NormalizerInterface::class)
  384.             ->addTag('serializer.normalizer');
  385.         $container->registerForAutoconfiguration(DenormalizerInterface::class)
  386.             ->addTag('serializer.normalizer');
  387.         $container->registerForAutoconfiguration(ConstraintValidatorInterface::class)
  388.             ->addTag('validator.constraint_validator');
  389.         $container->registerForAutoconfiguration(ObjectInitializerInterface::class)
  390.             ->addTag('validator.initializer');
  391.         $container->registerForAutoconfiguration(MessageHandlerInterface::class)
  392.             ->addTag('messenger.message_handler');
  393.         $container->registerForAutoconfiguration(TransportFactoryInterface::class)
  394.             ->addTag('messenger.transport_factory');
  395.         $container->registerForAutoconfiguration(MimeTypeGuesserInterface::class)
  396.             ->addTag('mime.mime_type_guesser');
  397.         $container->registerForAutoconfiguration(LoggerAwareInterface::class)
  398.             ->addMethodCall('setLogger', [new Reference('logger')]);
  399.         if (!$container->getParameter('kernel.debug')) {
  400.             // remove tagged iterator argument for resource checkers
  401.             $container->getDefinition('config_cache_factory')->setArguments([]);
  402.         }
  403.         if (!$config['disallow_search_engine_index'] ?? false) {
  404.             $container->removeDefinition('disallow_search_engine_index_response_listener');
  405.         }
  406.         $container->registerForAutoconfiguration(RouteLoaderInterface::class)
  407.             ->addTag('routing.route_loader');
  408.     }
  409.     /**
  410.      * {@inheritdoc}
  411.      */
  412.     public function getConfiguration(array $configContainerBuilder $container)
  413.     {
  414.         return new Configuration($container->getParameter('kernel.debug'));
  415.     }
  416.     private function registerFormConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  417.     {
  418.         $loader->load('form.xml');
  419.         if (null === $config['form']['csrf_protection']['enabled']) {
  420.             $config['form']['csrf_protection']['enabled'] = $config['csrf_protection']['enabled'];
  421.         }
  422.         if ($this->isConfigEnabled($container$config['form']['csrf_protection'])) {
  423.             $loader->load('form_csrf.xml');
  424.             $container->setParameter('form.type_extension.csrf.enabled'true);
  425.             $container->setParameter('form.type_extension.csrf.field_name'$config['form']['csrf_protection']['field_name']);
  426.         } else {
  427.             $container->setParameter('form.type_extension.csrf.enabled'false);
  428.         }
  429.         if (!class_exists(Translator::class)) {
  430.             $container->removeDefinition('form.type_extension.upload.validator');
  431.         }
  432.         if (!method_exists(CachingFactoryDecorator::class, 'reset')) {
  433.             $container->getDefinition('form.choice_list_factory.cached')
  434.                 ->clearTag('kernel.reset')
  435.             ;
  436.         }
  437.     }
  438.     private function registerEsiConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  439.     {
  440.         if (!$this->isConfigEnabled($container$config)) {
  441.             $container->removeDefinition('fragment.renderer.esi');
  442.             return;
  443.         }
  444.         $loader->load('esi.xml');
  445.     }
  446.     private function registerSsiConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  447.     {
  448.         if (!$this->isConfigEnabled($container$config)) {
  449.             $container->removeDefinition('fragment.renderer.ssi');
  450.             return;
  451.         }
  452.         $loader->load('ssi.xml');
  453.     }
  454.     private function registerFragmentsConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  455.     {
  456.         if (!$this->isConfigEnabled($container$config)) {
  457.             $container->removeDefinition('fragment.renderer.hinclude');
  458.             return;
  459.         }
  460.         $container->setParameter('fragment.renderer.hinclude.global_template'$config['hinclude_default_template']);
  461.         $loader->load('fragment_listener.xml');
  462.         $container->setParameter('fragment.path'$config['path']);
  463.     }
  464.     private function registerProfilerConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  465.     {
  466.         if (!$this->isConfigEnabled($container$config)) {
  467.             // this is needed for the WebProfiler to work even if the profiler is disabled
  468.             $container->setParameter('data_collector.templates', []);
  469.             return;
  470.         }
  471.         $loader->load('profiling.xml');
  472.         $loader->load('collectors.xml');
  473.         $loader->load('cache_debug.xml');
  474.         if ($this->formConfigEnabled) {
  475.             $loader->load('form_debug.xml');
  476.         }
  477.         if ($this->validatorConfigEnabled) {
  478.             $loader->load('validator_debug.xml');
  479.         }
  480.         if ($this->translationConfigEnabled) {
  481.             $loader->load('translation_debug.xml');
  482.             $container->getDefinition('translator.data_collector')->setDecoratedService('translator');
  483.         }
  484.         if ($this->messengerConfigEnabled) {
  485.             $loader->load('messenger_debug.xml');
  486.         }
  487.         if ($this->mailerConfigEnabled) {
  488.             $loader->load('mailer_debug.xml');
  489.         }
  490.         if ($this->httpClientConfigEnabled) {
  491.             $loader->load('http_client_debug.xml');
  492.         }
  493.         $container->setParameter('profiler_listener.only_exceptions'$config['only_exceptions']);
  494.         $container->setParameter('profiler_listener.only_master_requests'$config['only_master_requests']);
  495.         // Choose storage class based on the DSN
  496.         list($class) = explode(':'$config['dsn'], 2);
  497.         if ('file' !== $class) {
  498.             throw new \LogicException(sprintf('Driver "%s" is not supported for the profiler.'$class));
  499.         }
  500.         $container->setParameter('profiler.storage.dsn'$config['dsn']);
  501.         $container->getDefinition('profiler')
  502.             ->addArgument($config['collect'])
  503.             ->addTag('kernel.reset', ['method' => 'reset']);
  504.     }
  505.     private function registerWorkflowConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  506.     {
  507.         if (!$config['enabled']) {
  508.             $container->removeDefinition('console.command.workflow_dump');
  509.             return;
  510.         }
  511.         if (!class_exists(Workflow\Workflow::class)) {
  512.             throw new LogicException('Workflow support cannot be enabled as the Workflow component is not installed. Try running "composer require symfony/workflow".');
  513.         }
  514.         $loader->load('workflow.xml');
  515.         $registryDefinition $container->getDefinition('workflow.registry');
  516.         foreach ($config['workflows'] as $name => $workflow) {
  517.             $type $workflow['type'];
  518.             $workflowId sprintf('%s.%s'$type$name);
  519.             // Process Metadata (workflow + places (transition is done in the "create transition" block))
  520.             $metadataStoreDefinition = new Definition(Workflow\Metadata\InMemoryMetadataStore::class, [[], [], null]);
  521.             if ($workflow['metadata']) {
  522.                 $metadataStoreDefinition->replaceArgument(0$workflow['metadata']);
  523.             }
  524.             $placesMetadata = [];
  525.             foreach ($workflow['places'] as $place) {
  526.                 if ($place['metadata']) {
  527.                     $placesMetadata[$place['name']] = $place['metadata'];
  528.                 }
  529.             }
  530.             if ($placesMetadata) {
  531.                 $metadataStoreDefinition->replaceArgument(1$placesMetadata);
  532.             }
  533.             // Create transitions
  534.             $transitions = [];
  535.             $guardsConfiguration = [];
  536.             $transitionsMetadataDefinition = new Definition(\SplObjectStorage::class);
  537.             // Global transition counter per workflow
  538.             $transitionCounter 0;
  539.             foreach ($workflow['transitions'] as $transition) {
  540.                 if ('workflow' === $type) {
  541.                     $transitionDefinition = new Definition(Workflow\Transition::class, [$transition['name'], $transition['from'], $transition['to']]);
  542.                     $transitionDefinition->setPublic(false);
  543.                     $transitionId sprintf('%s.transition.%s'$workflowId$transitionCounter++);
  544.                     $container->setDefinition($transitionId$transitionDefinition);
  545.                     $transitions[] = new Reference($transitionId);
  546.                     if (isset($transition['guard'])) {
  547.                         $configuration = new Definition(Workflow\EventListener\GuardExpression::class);
  548.                         $configuration->addArgument(new Reference($transitionId));
  549.                         $configuration->addArgument($transition['guard']);
  550.                         $configuration->setPublic(false);
  551.                         $eventName sprintf('workflow.%s.guard.%s'$name$transition['name']);
  552.                         $guardsConfiguration[$eventName][] = $configuration;
  553.                     }
  554.                     if ($transition['metadata']) {
  555.                         $transitionsMetadataDefinition->addMethodCall('attach', [
  556.                             new Reference($transitionId),
  557.                             $transition['metadata'],
  558.                         ]);
  559.                     }
  560.                 } elseif ('state_machine' === $type) {
  561.                     foreach ($transition['from'] as $from) {
  562.                         foreach ($transition['to'] as $to) {
  563.                             $transitionDefinition = new Definition(Workflow\Transition::class, [$transition['name'], $from$to]);
  564.                             $transitionDefinition->setPublic(false);
  565.                             $transitionId sprintf('%s.transition.%s'$workflowId$transitionCounter++);
  566.                             $container->setDefinition($transitionId$transitionDefinition);
  567.                             $transitions[] = new Reference($transitionId);
  568.                             if (isset($transition['guard'])) {
  569.                                 $configuration = new Definition(Workflow\EventListener\GuardExpression::class);
  570.                                 $configuration->addArgument(new Reference($transitionId));
  571.                                 $configuration->addArgument($transition['guard']);
  572.                                 $configuration->setPublic(false);
  573.                                 $eventName sprintf('workflow.%s.guard.%s'$name$transition['name']);
  574.                                 $guardsConfiguration[$eventName][] = $configuration;
  575.                             }
  576.                             if ($transition['metadata']) {
  577.                                 $transitionsMetadataDefinition->addMethodCall('attach', [
  578.                                     new Reference($transitionId),
  579.                                     $transition['metadata'],
  580.                                 ]);
  581.                             }
  582.                         }
  583.                     }
  584.                 }
  585.             }
  586.             $metadataStoreDefinition->replaceArgument(2$transitionsMetadataDefinition);
  587.             // Create places
  588.             $places array_column($workflow['places'], 'name');
  589.             $initialMarking $workflow['initial_marking'] ?? [];
  590.             // Create a Definition
  591.             $definitionDefinition = new Definition(Workflow\Definition::class);
  592.             $definitionDefinition->setPublic(false);
  593.             $definitionDefinition->addArgument($places);
  594.             $definitionDefinition->addArgument($transitions);
  595.             $definitionDefinition->addArgument($initialMarking);
  596.             $definitionDefinition->addArgument($metadataStoreDefinition);
  597.             $definitionDefinition->addTag('workflow.definition', [
  598.                 'name' => $name,
  599.                 'type' => $type,
  600.             ]);
  601.             // Create MarkingStore
  602.             if (isset($workflow['marking_store']['type'])) {
  603.                 $markingStoreDefinition = new ChildDefinition('workflow.marking_store.method');
  604.                 $markingStoreDefinition->setArguments([
  605.                     'state_machine' === $type//single state
  606.                     $workflow['marking_store']['property'],
  607.                 ]);
  608.             } elseif (isset($workflow['marking_store']['service'])) {
  609.                 $markingStoreDefinition = new Reference($workflow['marking_store']['service']);
  610.             }
  611.             // Create Workflow
  612.             $workflowDefinition = new ChildDefinition(sprintf('%s.abstract'$type));
  613.             $workflowDefinition->replaceArgument(0, new Reference(sprintf('%s.definition'$workflowId)));
  614.             if (isset($markingStoreDefinition)) {
  615.                 $workflowDefinition->replaceArgument(1$markingStoreDefinition);
  616.             }
  617.             $workflowDefinition->replaceArgument(3$name);
  618.             // Store to container
  619.             $container->setDefinition($workflowId$workflowDefinition);
  620.             $container->setDefinition(sprintf('%s.definition'$workflowId), $definitionDefinition);
  621.             $container->registerAliasForArgument($workflowIdWorkflowInterface::class, $name.'.'.$type);
  622.             // Validate Workflow
  623.             if ('state_machine' === $workflow['type']) {
  624.                 $validator = new Workflow\Validator\StateMachineValidator();
  625.             } else {
  626.                 $validator = new Workflow\Validator\WorkflowValidator();
  627.             }
  628.             $trs array_map(function (Reference $ref) use ($container): Workflow\Transition {
  629.                 return $container->get((string) $ref);
  630.             }, $transitions);
  631.             $realDefinition = new Workflow\Definition($places$trs$initialMarking);
  632.             $validator->validate($realDefinition$name);
  633.             // Add workflow to Registry
  634.             if ($workflow['supports']) {
  635.                 foreach ($workflow['supports'] as $supportedClassName) {
  636.                     $strategyDefinition = new Definition(Workflow\SupportStrategy\InstanceOfSupportStrategy::class, [$supportedClassName]);
  637.                     $strategyDefinition->setPublic(false);
  638.                     $registryDefinition->addMethodCall('addWorkflow', [new Reference($workflowId), $strategyDefinition]);
  639.                 }
  640.             } elseif (isset($workflow['support_strategy'])) {
  641.                 $registryDefinition->addMethodCall('addWorkflow', [new Reference($workflowId), new Reference($workflow['support_strategy'])]);
  642.             }
  643.             // Enable the AuditTrail
  644.             if ($workflow['audit_trail']['enabled']) {
  645.                 $listener = new Definition(Workflow\EventListener\AuditTrailListener::class);
  646.                 $listener->setPrivate(true);
  647.                 $listener->addTag('monolog.logger', ['channel' => 'workflow']);
  648.                 $listener->addTag('kernel.event_listener', ['event' => sprintf('workflow.%s.leave'$name), 'method' => 'onLeave']);
  649.                 $listener->addTag('kernel.event_listener', ['event' => sprintf('workflow.%s.transition'$name), 'method' => 'onTransition']);
  650.                 $listener->addTag('kernel.event_listener', ['event' => sprintf('workflow.%s.enter'$name), 'method' => 'onEnter']);
  651.                 $listener->addArgument(new Reference('logger'));
  652.                 $container->setDefinition(sprintf('%s.listener.audit_trail'$workflowId), $listener);
  653.             }
  654.             // Add Guard Listener
  655.             if ($guardsConfiguration) {
  656.                 if (!class_exists(ExpressionLanguage::class)) {
  657.                     throw new LogicException('Cannot guard workflows as the ExpressionLanguage component is not installed. Try running "composer require symfony/expression-language".');
  658.                 }
  659.                 if (!class_exists(Security::class)) {
  660.                     throw new LogicException('Cannot guard workflows as the Security component is not installed. Try running "composer require symfony/security-core".');
  661.                 }
  662.                 $guard = new Definition(Workflow\EventListener\GuardListener::class);
  663.                 $guard->setPrivate(true);
  664.                 $guard->setArguments([
  665.                     $guardsConfiguration,
  666.                     new Reference('workflow.security.expression_language'),
  667.                     new Reference('security.token_storage'),
  668.                     new Reference('security.authorization_checker'),
  669.                     new Reference('security.authentication.trust_resolver'),
  670.                     new Reference('security.role_hierarchy'),
  671.                     new Reference('validator'ContainerInterface::NULL_ON_INVALID_REFERENCE),
  672.                 ]);
  673.                 foreach ($guardsConfiguration as $eventName => $config) {
  674.                     $guard->addTag('kernel.event_listener', ['event' => $eventName'method' => 'onTransition']);
  675.                 }
  676.                 $container->setDefinition(sprintf('%s.listener.guard'$workflowId), $guard);
  677.                 $container->setParameter('workflow.has_guard_listeners'true);
  678.             }
  679.         }
  680.     }
  681.     private function registerDebugConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  682.     {
  683.         $loader->load('debug_prod.xml');
  684.         if (class_exists(Stopwatch::class)) {
  685.             $container->register('debug.stopwatch'Stopwatch::class)
  686.                 ->addArgument(true)
  687.                 ->setPrivate(true)
  688.                 ->addTag('kernel.reset', ['method' => 'reset']);
  689.             $container->setAlias(Stopwatch::class, new Alias('debug.stopwatch'false));
  690.         }
  691.         $debug $container->getParameter('kernel.debug');
  692.         if ($debug) {
  693.             $container->setParameter('debug.container.dump''%kernel.cache_dir%/%kernel.container_class%.xml');
  694.         }
  695.         if ($debug && class_exists(Stopwatch::class)) {
  696.             $loader->load('debug.xml');
  697.         }
  698.         $definition $container->findDefinition('debug.debug_handlers_listener');
  699.         if (false === $config['log']) {
  700.             $definition->replaceArgument(1null);
  701.         } elseif (true !== $config['log']) {
  702.             $definition->replaceArgument(2$config['log']);
  703.         }
  704.         if (!$config['throw']) {
  705.             $container->setParameter('debug.error_handler.throw_at'0);
  706.         }
  707.         if ($debug && class_exists(DebugProcessor::class)) {
  708.             $definition = new Definition(DebugProcessor::class);
  709.             $definition->setPublic(false);
  710.             $definition->addArgument(new Reference('request_stack'));
  711.             $container->setDefinition('debug.log_processor'$definition);
  712.         }
  713.     }
  714.     private function registerRouterConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  715.     {
  716.         if (!$this->isConfigEnabled($container$config)) {
  717.             $container->removeDefinition('console.command.router_debug');
  718.             $container->removeDefinition('console.command.router_match');
  719.             return;
  720.         }
  721.         $loader->load('routing.xml');
  722.         if ($config['utf8']) {
  723.             $container->getDefinition('routing.loader')->replaceArgument(1, ['utf8' => true]);
  724.         }
  725.         $container->setParameter('router.resource'$config['resource']);
  726.         $router $container->findDefinition('router.default');
  727.         $argument $router->getArgument(2);
  728.         $argument['strict_requirements'] = $config['strict_requirements'];
  729.         if (isset($config['type'])) {
  730.             $argument['resource_type'] = $config['type'];
  731.         }
  732.         $router->replaceArgument(2$argument);
  733.         $container->setParameter('request_listener.http_port'$config['http_port']);
  734.         $container->setParameter('request_listener.https_port'$config['https_port']);
  735.         if ($this->annotationsConfigEnabled) {
  736.             $container->register('routing.loader.annotation'AnnotatedRouteControllerLoader::class)
  737.                 ->setPublic(false)
  738.                 ->addTag('routing.loader', ['priority' => -10])
  739.                 ->addArgument(new Reference('annotation_reader'));
  740.             $container->register('routing.loader.annotation.directory'AnnotationDirectoryLoader::class)
  741.                 ->setPublic(false)
  742.                 ->addTag('routing.loader', ['priority' => -10])
  743.                 ->setArguments([
  744.                     new Reference('file_locator'),
  745.                     new Reference('routing.loader.annotation'),
  746.                 ]);
  747.             $container->register('routing.loader.annotation.file'AnnotationFileLoader::class)
  748.                 ->setPublic(false)
  749.                 ->addTag('routing.loader', ['priority' => -10])
  750.                 ->setArguments([
  751.                     new Reference('file_locator'),
  752.                     new Reference('routing.loader.annotation'),
  753.                 ]);
  754.         }
  755.     }
  756.     private function registerSessionConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  757.     {
  758.         $loader->load('session.xml');
  759.         // session storage
  760.         $container->setAlias('session.storage'$config['storage_id'])->setPrivate(true);
  761.         $options = ['cache_limiter' => '0'];
  762.         foreach (['name''cookie_lifetime''cookie_path''cookie_domain''cookie_secure''cookie_httponly''cookie_samesite''use_cookies''gc_maxlifetime''gc_probability''gc_divisor''sid_length''sid_bits_per_character'] as $key) {
  763.             if (isset($config[$key])) {
  764.                 $options[$key] = $config[$key];
  765.             }
  766.         }
  767.         if ('auto' === ($options['cookie_secure'] ?? null)) {
  768.             $locator $container->getDefinition('session_listener')->getArgument(0);
  769.             $locator->setValues($locator->getValues() + [
  770.                 'session_storage' => new Reference('session.storage'ContainerInterface::IGNORE_ON_INVALID_REFERENCE),
  771.                 'request_stack' => new Reference('request_stack'),
  772.             ]);
  773.         }
  774.         $container->setParameter('session.storage.options'$options);
  775.         // session handler (the internal callback registered with PHP session management)
  776.         if (null === $config['handler_id']) {
  777.             // Set the handler class to be null
  778.             $container->getDefinition('session.storage.native')->replaceArgument(1null);
  779.             $container->getDefinition('session.storage.php_bridge')->replaceArgument(0null);
  780.         } else {
  781.             $container->resolveEnvPlaceholders($config['handler_id'], null$usedEnvs);
  782.             if ($usedEnvs || preg_match('#^[a-z]++://#'$config['handler_id'])) {
  783.                 $id '.cache_connection.'.ContainerBuilder::hash($config['handler_id']);
  784.                 $container->getDefinition('session.abstract_handler')
  785.                     ->replaceArgument(0$container->hasDefinition($id) ? new Reference($id) : $config['handler_id']);
  786.                 $container->setAlias('session.handler''session.abstract_handler')->setPrivate(true);
  787.             } else {
  788.                 $container->setAlias('session.handler'$config['handler_id'])->setPrivate(true);
  789.             }
  790.         }
  791.         $container->setParameter('session.save_path'$config['save_path']);
  792.         $container->setParameter('session.metadata.update_threshold'$config['metadata_update_threshold']);
  793.     }
  794.     private function registerRequestConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  795.     {
  796.         if ($config['formats']) {
  797.             $loader->load('request.xml');
  798.             $listener $container->getDefinition('request.add_request_formats_listener');
  799.             $listener->replaceArgument(0$config['formats']);
  800.         }
  801.     }
  802.     private function registerAssetsConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  803.     {
  804.         $loader->load('assets.xml');
  805.         if ($config['version_strategy']) {
  806.             $defaultVersion = new Reference($config['version_strategy']);
  807.         } else {
  808.             $defaultVersion $this->createVersion($container$config['version'], $config['version_format'], $config['json_manifest_path'], '_default');
  809.         }
  810.         $defaultPackage $this->createPackageDefinition($config['base_path'], $config['base_urls'], $defaultVersion);
  811.         $container->setDefinition('assets._default_package'$defaultPackage);
  812.         $namedPackages = [];
  813.         foreach ($config['packages'] as $name => $package) {
  814.             if (null !== $package['version_strategy']) {
  815.                 $version = new Reference($package['version_strategy']);
  816.             } elseif (!\array_key_exists('version'$package) && null === $package['json_manifest_path']) {
  817.                 // if neither version nor json_manifest_path are specified, use the default
  818.                 $version $defaultVersion;
  819.             } else {
  820.                 // let format fallback to main version_format
  821.                 $format $package['version_format'] ?: $config['version_format'];
  822.                 $version = isset($package['version']) ? $package['version'] : null;
  823.                 $version $this->createVersion($container$version$format$package['json_manifest_path'], $name);
  824.             }
  825.             $container->setDefinition('assets._package_'.$name$this->createPackageDefinition($package['base_path'], $package['base_urls'], $version));
  826.             $container->registerAliasForArgument('assets._package_'.$namePackageInterface::class, $name.'.package');
  827.             $namedPackages[$name] = new Reference('assets._package_'.$name);
  828.         }
  829.         $container->getDefinition('assets.packages')
  830.             ->replaceArgument(0, new Reference('assets._default_package'))
  831.             ->replaceArgument(1$namedPackages)
  832.         ;
  833.     }
  834.     /**
  835.      * Returns a definition for an asset package.
  836.      */
  837.     private function createPackageDefinition(?string $basePath, array $baseUrlsReference $version): Definition
  838.     {
  839.         if ($basePath && $baseUrls) {
  840.             throw new \LogicException('An asset package cannot have base URLs and base paths.');
  841.         }
  842.         $package = new ChildDefinition($baseUrls 'assets.url_package' 'assets.path_package');
  843.         $package
  844.             ->setPublic(false)
  845.             ->replaceArgument(0$baseUrls ?: $basePath)
  846.             ->replaceArgument(1$version)
  847.         ;
  848.         return $package;
  849.     }
  850.     private function createVersion(ContainerBuilder $container, ?string $version, ?string $format, ?string $jsonManifestPathstring $name): Reference
  851.     {
  852.         // Configuration prevents $version and $jsonManifestPath from being set
  853.         if (null !== $version) {
  854.             $def = new ChildDefinition('assets.static_version_strategy');
  855.             $def
  856.                 ->replaceArgument(0$version)
  857.                 ->replaceArgument(1$format)
  858.             ;
  859.             $container->setDefinition('assets._version_'.$name$def);
  860.             return new Reference('assets._version_'.$name);
  861.         }
  862.         if (null !== $jsonManifestPath) {
  863.             $def = new ChildDefinition('assets.json_manifest_version_strategy');
  864.             $def->replaceArgument(0$jsonManifestPath);
  865.             $container->setDefinition('assets._version_'.$name$def);
  866.             return new Reference('assets._version_'.$name);
  867.         }
  868.         return new Reference('assets.empty_version_strategy');
  869.     }
  870.     private function registerTranslatorConfiguration(array $configContainerBuilder $containerLoaderInterface $loaderstring $defaultLocale)
  871.     {
  872.         if (!$this->isConfigEnabled($container$config)) {
  873.             $container->removeDefinition('console.command.translation_debug');
  874.             $container->removeDefinition('console.command.translation_update');
  875.             return;
  876.         }
  877.         $loader->load('translation.xml');
  878.         // Use the "real" translator instead of the identity default
  879.         $container->setAlias('translator''translator.default')->setPublic(true);
  880.         $container->setAlias('translator.formatter', new Alias($config['formatter'], false));
  881.         $translator $container->findDefinition('translator.default');
  882.         $translator->addMethodCall('setFallbackLocales', [$config['fallbacks'] ?: [$defaultLocale]]);
  883.         $defaultOptions $translator->getArgument(4);
  884.         $defaultOptions['cache_dir'] = $config['cache_dir'];
  885.         $translator->setArgument(4$defaultOptions);
  886.         $container->setParameter('translator.logging'$config['logging']);
  887.         $container->setParameter('translator.default_path'$config['default_path']);
  888.         // Discover translation directories
  889.         $dirs = [];
  890.         $transPaths = [];
  891.         $nonExistingDirs = [];
  892.         if (class_exists('Symfony\Component\Validator\Validation')) {
  893.             $r = new \ReflectionClass('Symfony\Component\Validator\Validation');
  894.             $dirs[] = $transPaths[] = \dirname($r->getFileName()).'/Resources/translations';
  895.         }
  896.         if (class_exists('Symfony\Component\Form\Form')) {
  897.             $r = new \ReflectionClass('Symfony\Component\Form\Form');
  898.             $dirs[] = $transPaths[] = \dirname($r->getFileName()).'/Resources/translations';
  899.         }
  900.         if (class_exists('Symfony\Component\Security\Core\Exception\AuthenticationException')) {
  901.             $r = new \ReflectionClass('Symfony\Component\Security\Core\Exception\AuthenticationException');
  902.             $dirs[] = $transPaths[] = \dirname($r->getFileName(), 2).'/Resources/translations';
  903.         }
  904.         $defaultDir $container->getParameterBag()->resolveValue($config['default_path']);
  905.         foreach ($container->getParameter('kernel.bundles_metadata') as $name => $bundle) {
  906.             if ($container->fileExists($dir $bundle['path'].'/Resources/translations') || $container->fileExists($dir $bundle['path'].'/translations')) {
  907.                 $dirs[] = $dir;
  908.             } else {
  909.                 $nonExistingDirs[] = $dir;
  910.             }
  911.         }
  912.         foreach ($config['paths'] as $dir) {
  913.             if ($container->fileExists($dir)) {
  914.                 $dirs[] = $transPaths[] = $dir;
  915.             } else {
  916.                 throw new \UnexpectedValueException(sprintf('%s defined in translator.paths does not exist or is not a directory'$dir));
  917.             }
  918.         }
  919.         if ($container->hasDefinition('console.command.translation_debug')) {
  920.             $container->getDefinition('console.command.translation_debug')->replaceArgument(5$transPaths);
  921.         }
  922.         if ($container->hasDefinition('console.command.translation_update')) {
  923.             $container->getDefinition('console.command.translation_update')->replaceArgument(6$transPaths);
  924.         }
  925.         if ($container->fileExists($defaultDir)) {
  926.             $dirs[] = $defaultDir;
  927.         } else {
  928.             $nonExistingDirs[] = $defaultDir;
  929.         }
  930.         // Register translation resources
  931.         if ($dirs) {
  932.             $files = [];
  933.             $finder Finder::create()
  934.                 ->followLinks()
  935.                 ->files()
  936.                 ->filter(function (\SplFileInfo $file) {
  937.                     return <= substr_count($file->getBasename(), '.') && preg_match('/\.\w+$/'$file->getBasename());
  938.                 })
  939.                 ->in($dirs)
  940.                 ->sortByName()
  941.             ;
  942.             foreach ($finder as $file) {
  943.                 $fileNameParts explode('.'basename($file));
  944.                 $locale $fileNameParts[\count($fileNameParts) - 2];
  945.                 if (!isset($files[$locale])) {
  946.                     $files[$locale] = [];
  947.                 }
  948.                 $files[$locale][] = (string) $file;
  949.             }
  950.             $projectDir $container->getParameter('kernel.project_dir');
  951.             $options array_merge(
  952.                 $translator->getArgument(4),
  953.                 [
  954.                     'resource_files' => $files,
  955.                     'scanned_directories' => $scannedDirectories array_merge($dirs$nonExistingDirs),
  956.                     'cache_vary' => [
  957.                         'scanned_directories' => array_map(static function (string $dir) use ($projectDir): string {
  958.                             return === strpos($dir$projectDir.'/') ? substr($dir+ \strlen($projectDir)) : $dir;
  959.                         }, $scannedDirectories),
  960.                     ],
  961.                 ]
  962.             );
  963.             $translator->replaceArgument(4$options);
  964.         }
  965.     }
  966.     private function registerValidationConfiguration(array $configContainerBuilder $containerXmlFileLoader $loaderbool $propertyInfoEnabled)
  967.     {
  968.         if (!$this->validatorConfigEnabled $this->isConfigEnabled($container$config)) {
  969.             return;
  970.         }
  971.         if (!class_exists('Symfony\Component\Validator\Validation')) {
  972.             throw new LogicException('Validation support cannot be enabled as the Validator component is not installed. Try running "composer require symfony/validator".');
  973.         }
  974.         if (!isset($config['email_validation_mode'])) {
  975.             $config['email_validation_mode'] = 'loose';
  976.         }
  977.         $loader->load('validator.xml');
  978.         $validatorBuilder $container->getDefinition('validator.builder');
  979.         $container->setParameter('validator.translation_domain'$config['translation_domain']);
  980.         $files = ['xml' => [], 'yml' => []];
  981.         $this->registerValidatorMapping($container$config$files);
  982.         if (!empty($files['xml'])) {
  983.             $validatorBuilder->addMethodCall('addXmlMappings', [$files['xml']]);
  984.         }
  985.         if (!empty($files['yml'])) {
  986.             $validatorBuilder->addMethodCall('addYamlMappings', [$files['yml']]);
  987.         }
  988.         $definition $container->findDefinition('validator.email');
  989.         $definition->replaceArgument(0$config['email_validation_mode']);
  990.         if (\array_key_exists('enable_annotations'$config) && $config['enable_annotations']) {
  991.             if (!$this->annotationsConfigEnabled) {
  992.                 throw new \LogicException('"enable_annotations" on the validator cannot be set as Annotations support is disabled.');
  993.             }
  994.             $validatorBuilder->addMethodCall('enableAnnotationMapping', [new Reference('annotation_reader')]);
  995.         }
  996.         if (\array_key_exists('static_method'$config) && $config['static_method']) {
  997.             foreach ($config['static_method'] as $methodName) {
  998.                 $validatorBuilder->addMethodCall('addMethodMapping', [$methodName]);
  999.             }
  1000.         }
  1001.         if (!$container->getParameter('kernel.debug')) {
  1002.             $validatorBuilder->addMethodCall('setMappingCache', [new Reference('validator.mapping.cache.adapter')]);
  1003.         }
  1004.         $container->setParameter('validator.auto_mapping'$config['auto_mapping']);
  1005.         if (!$propertyInfoEnabled || !class_exists(PropertyInfoLoader::class)) {
  1006.             $container->removeDefinition('validator.property_info_loader');
  1007.         }
  1008.         $container
  1009.             ->getDefinition('validator.not_compromised_password')
  1010.             ->setArgument(2$config['not_compromised_password']['enabled'])
  1011.             ->setArgument(3$config['not_compromised_password']['endpoint'])
  1012.         ;
  1013.     }
  1014.     private function registerValidatorMapping(ContainerBuilder $container, array $config, array &$files)
  1015.     {
  1016.         $fileRecorder = function ($extension$path) use (&$files) {
  1017.             $files['yaml' === $extension 'yml' $extension][] = $path;
  1018.         };
  1019.         if (interface_exists('Symfony\Component\Form\FormInterface')) {
  1020.             $reflClass = new \ReflectionClass('Symfony\Component\Form\FormInterface');
  1021.             $fileRecorder('xml', \dirname($reflClass->getFileName()).'/Resources/config/validation.xml');
  1022.         }
  1023.         foreach ($container->getParameter('kernel.bundles_metadata') as $bundle) {
  1024.             $configDir is_dir($bundle['path'].'/Resources/config') ? $bundle['path'].'/Resources/config' $bundle['path'].'/config';
  1025.             if (
  1026.                 $container->fileExists($file $configDir.'/validation.yaml'false) ||
  1027.                 $container->fileExists($file $configDir.'/validation.yml'false)
  1028.             ) {
  1029.                 $fileRecorder('yml'$file);
  1030.             }
  1031.             if ($container->fileExists($file $configDir.'/validation.xml'false)) {
  1032.                 $fileRecorder('xml'$file);
  1033.             }
  1034.             if ($container->fileExists($dir $configDir.'/validation''/^$/')) {
  1035.                 $this->registerMappingFilesFromDir($dir$fileRecorder);
  1036.             }
  1037.         }
  1038.         $projectDir $container->getParameter('kernel.project_dir');
  1039.         if ($container->fileExists($dir $projectDir.'/config/validator''/^$/')) {
  1040.             $this->registerMappingFilesFromDir($dir$fileRecorder);
  1041.         }
  1042.         $this->registerMappingFilesFromConfig($container$config$fileRecorder);
  1043.     }
  1044.     private function registerMappingFilesFromDir(string $dir, callable $fileRecorder)
  1045.     {
  1046.         foreach (Finder::create()->followLinks()->files()->in($dir)->name('/\.(xml|ya?ml)$/')->sortByName() as $file) {
  1047.             $fileRecorder($file->getExtension(), $file->getRealPath());
  1048.         }
  1049.     }
  1050.     private function registerMappingFilesFromConfig(ContainerBuilder $container, array $config, callable $fileRecorder)
  1051.     {
  1052.         foreach ($config['mapping']['paths'] as $path) {
  1053.             if (is_dir($path)) {
  1054.                 $this->registerMappingFilesFromDir($path$fileRecorder);
  1055.                 $container->addResource(new DirectoryResource($path'/^$/'));
  1056.             } elseif ($container->fileExists($pathfalse)) {
  1057.                 if (!preg_match('/\.(xml|ya?ml)$/'$path$matches)) {
  1058.                     throw new \RuntimeException(sprintf('Unsupported mapping type in "%s", supported types are XML & Yaml.'$path));
  1059.                 }
  1060.                 $fileRecorder($matches[1], $path);
  1061.             } else {
  1062.                 throw new \RuntimeException(sprintf('Could not open file or directory "%s".'$path));
  1063.             }
  1064.         }
  1065.     }
  1066.     private function registerAnnotationsConfiguration(array $configContainerBuilder $containerLoaderInterface $loader)
  1067.     {
  1068.         if (!$this->annotationsConfigEnabled) {
  1069.             return;
  1070.         }
  1071.         if (!class_exists('Doctrine\Common\Annotations\Annotation')) {
  1072.             throw new LogicException('Annotations cannot be enabled as the Doctrine Annotation library is not installed.');
  1073.         }
  1074.         $loader->load('annotations.xml');
  1075.         if (!method_exists(AnnotationRegistry::class, 'registerUniqueLoader')) {
  1076.             $container->getDefinition('annotations.dummy_registry')
  1077.                 ->setMethodCalls([['registerLoader', ['class_exists']]]);
  1078.         }
  1079.         if ('none' !== $config['cache']) {
  1080.             if (!class_exists('Doctrine\Common\Cache\CacheProvider')) {
  1081.                 throw new LogicException('Annotations cannot be enabled as the Doctrine Cache library is not installed.');
  1082.             }
  1083.             $cacheService $config['cache'];
  1084.             if ('php_array' === $config['cache']) {
  1085.                 $cacheService 'annotations.cache';
  1086.                 // Enable warmer only if PHP array is used for cache
  1087.                 $definition $container->findDefinition('annotations.cache_warmer');
  1088.                 $definition->addTag('kernel.cache_warmer');
  1089.             } elseif ('file' === $config['cache']) {
  1090.                 $cacheDir $container->getParameterBag()->resolveValue($config['file_cache_dir']);
  1091.                 if (!is_dir($cacheDir) && false === @mkdir($cacheDir0777true) && !is_dir($cacheDir)) {
  1092.                     throw new \RuntimeException(sprintf('Could not create cache directory "%s".'$cacheDir));
  1093.                 }
  1094.                 $container
  1095.                     ->getDefinition('annotations.filesystem_cache')
  1096.                     ->replaceArgument(0$cacheDir)
  1097.                 ;
  1098.                 $cacheService 'annotations.filesystem_cache';
  1099.             }
  1100.             $container
  1101.                 ->getDefinition('annotations.cached_reader')
  1102.                 ->replaceArgument(2$config['debug'])
  1103.                 // temporary property to lazy-reference the cache provider without using it until AddAnnotationsCachedReaderPass runs
  1104.                 ->setProperty('cacheProviderBackup', new ServiceClosureArgument(new Reference($cacheService)))
  1105.                 ->addTag('annotations.cached_reader')
  1106.             ;
  1107.             $container->setAlias('annotation_reader''annotations.cached_reader')->setPrivate(true);
  1108.             $container->setAlias(Reader::class, new Alias('annotations.cached_reader'false));
  1109.         } else {
  1110.             $container->removeDefinition('annotations.cached_reader');
  1111.         }
  1112.     }
  1113.     private function registerPropertyAccessConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  1114.     {
  1115.         if (!class_exists('Symfony\Component\PropertyAccess\PropertyAccessor')) {
  1116.             return;
  1117.         }
  1118.         $loader->load('property_access.xml');
  1119.         $container
  1120.             ->getDefinition('property_accessor')
  1121.             ->replaceArgument(0$config['magic_call'])
  1122.             ->replaceArgument(1$config['throw_exception_on_invalid_index'])
  1123.             ->replaceArgument(3$config['throw_exception_on_invalid_property_path'])
  1124.         ;
  1125.     }
  1126.     private function registerSecretsConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  1127.     {
  1128.         if (!$this->isConfigEnabled($container$config)) {
  1129.             $container->removeDefinition('console.command.secrets_set');
  1130.             $container->removeDefinition('console.command.secrets_list');
  1131.             $container->removeDefinition('console.command.secrets_remove');
  1132.             $container->removeDefinition('console.command.secrets_generate_key');
  1133.             $container->removeDefinition('console.command.secrets_decrypt_to_local');
  1134.             $container->removeDefinition('console.command.secrets_encrypt_from_local');
  1135.             return;
  1136.         }
  1137.         $loader->load('secrets.xml');
  1138.         $container->getDefinition('secrets.vault')->replaceArgument(0$config['vault_directory']);
  1139.         if ($config['local_dotenv_file']) {
  1140.             $container->getDefinition('secrets.local_vault')->replaceArgument(0$config['local_dotenv_file']);
  1141.         } else {
  1142.             $container->removeDefinition('secrets.local_vault');
  1143.         }
  1144.         if ($config['decryption_env_var']) {
  1145.             if (!preg_match('/^(?:\w*+:)*+\w++$/'$config['decryption_env_var'])) {
  1146.                 throw new InvalidArgumentException(sprintf('Invalid value "%s" set as "decryption_env_var": only "word" characters are allowed.'$config['decryption_env_var']));
  1147.             }
  1148.             $container->getDefinition('secrets.vault')->replaceArgument(1"%env({$config['decryption_env_var']})%");
  1149.         } else {
  1150.             $container->getDefinition('secrets.vault')->replaceArgument(1null);
  1151.         }
  1152.     }
  1153.     private function registerSecurityCsrfConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  1154.     {
  1155.         if (!$this->isConfigEnabled($container$config)) {
  1156.             return;
  1157.         }
  1158.         if (!class_exists('Symfony\Component\Security\Csrf\CsrfToken')) {
  1159.             throw new LogicException('CSRF support cannot be enabled as the Security CSRF component is not installed. Try running "composer require symfony/security-csrf".');
  1160.         }
  1161.         if (!$this->sessionConfigEnabled) {
  1162.             throw new \LogicException('CSRF protection needs sessions to be enabled.');
  1163.         }
  1164.         // Enable services for CSRF protection (even without forms)
  1165.         $loader->load('security_csrf.xml');
  1166.         if (!class_exists(CsrfExtension::class)) {
  1167.             $container->removeDefinition('twig.extension.security_csrf');
  1168.         }
  1169.     }
  1170.     private function registerSerializerConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  1171.     {
  1172.         $loader->load('serializer.xml');
  1173.         $chainLoader $container->getDefinition('serializer.mapping.chain_loader');
  1174.         if (!class_exists('Symfony\Component\PropertyAccess\PropertyAccessor')) {
  1175.             $container->removeAlias('serializer.property_accessor');
  1176.             $container->removeDefinition('serializer.normalizer.object');
  1177.         }
  1178.         if (!class_exists(Yaml::class)) {
  1179.             $container->removeDefinition('serializer.encoder.yaml');
  1180.         }
  1181.         $serializerLoaders = [];
  1182.         if (isset($config['enable_annotations']) && $config['enable_annotations']) {
  1183.             if (!$this->annotationsConfigEnabled) {
  1184.                 throw new \LogicException('"enable_annotations" on the serializer cannot be set as Annotations support is disabled.');
  1185.             }
  1186.             $annotationLoader = new Definition(
  1187.                 'Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader',
  1188.                 [new Reference('annotation_reader')]
  1189.             );
  1190.             $annotationLoader->setPublic(false);
  1191.             $serializerLoaders[] = $annotationLoader;
  1192.         }
  1193.         $fileRecorder = function ($extension$path) use (&$serializerLoaders) {
  1194.             $definition = new Definition(\in_array($extension, ['yaml''yml']) ? 'Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader' 'Symfony\Component\Serializer\Mapping\Loader\XmlFileLoader', [$path]);
  1195.             $definition->setPublic(false);
  1196.             $serializerLoaders[] = $definition;
  1197.         };
  1198.         foreach ($container->getParameter('kernel.bundles_metadata') as $bundle) {
  1199.             $configDir is_dir($bundle['path'].'/Resources/config') ? $bundle['path'].'/Resources/config' $bundle['path'].'/config';
  1200.             if ($container->fileExists($file $configDir.'/serialization.xml'false)) {
  1201.                 $fileRecorder('xml'$file);
  1202.             }
  1203.             if (
  1204.                 $container->fileExists($file $configDir.'/serialization.yaml'false) ||
  1205.                 $container->fileExists($file $configDir.'/serialization.yml'false)
  1206.             ) {
  1207.                 $fileRecorder('yml'$file);
  1208.             }
  1209.             if ($container->fileExists($dir $configDir.'/serialization''/^$/')) {
  1210.                 $this->registerMappingFilesFromDir($dir$fileRecorder);
  1211.             }
  1212.         }
  1213.         $projectDir $container->getParameter('kernel.project_dir');
  1214.         if ($container->fileExists($dir $projectDir.'/config/serializer''/^$/')) {
  1215.             $this->registerMappingFilesFromDir($dir$fileRecorder);
  1216.         }
  1217.         $this->registerMappingFilesFromConfig($container$config$fileRecorder);
  1218.         $chainLoader->replaceArgument(0$serializerLoaders);
  1219.         $container->getDefinition('serializer.mapping.cache_warmer')->replaceArgument(0$serializerLoaders);
  1220.         if ($container->getParameter('kernel.debug')) {
  1221.             $container->removeDefinition('serializer.mapping.cache_class_metadata_factory');
  1222.         }
  1223.         if (isset($config['name_converter']) && $config['name_converter']) {
  1224.             $container->getDefinition('serializer.name_converter.metadata_aware')->setArgument(1, new Reference($config['name_converter']));
  1225.         }
  1226.         if (isset($config['circular_reference_handler']) && $config['circular_reference_handler']) {
  1227.             $arguments $container->getDefinition('serializer.normalizer.object')->getArguments();
  1228.             $context = ($arguments[6] ?? []) + ['circular_reference_handler' => new Reference($config['circular_reference_handler'])];
  1229.             $container->getDefinition('serializer.normalizer.object')->setArgument(5null);
  1230.             $container->getDefinition('serializer.normalizer.object')->setArgument(6$context);
  1231.         }
  1232.         if ($config['max_depth_handler'] ?? false) {
  1233.             $defaultContext $container->getDefinition('serializer.normalizer.object')->getArgument(6);
  1234.             $defaultContext += ['max_depth_handler' => new Reference($config['max_depth_handler'])];
  1235.             $container->getDefinition('serializer.normalizer.object')->replaceArgument(6$defaultContext);
  1236.         }
  1237.     }
  1238.     private function registerPropertyInfoConfiguration(ContainerBuilder $containerXmlFileLoader $loader)
  1239.     {
  1240.         if (!interface_exists(PropertyInfoExtractorInterface::class)) {
  1241.             throw new LogicException('PropertyInfo support cannot be enabled as the PropertyInfo component is not installed. Try running "composer require symfony/property-info".');
  1242.         }
  1243.         $loader->load('property_info.xml');
  1244.         if (interface_exists('phpDocumentor\Reflection\DocBlockFactoryInterface')) {
  1245.             $definition $container->register('property_info.php_doc_extractor''Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor');
  1246.             $definition->setPrivate(true);
  1247.             $definition->addTag('property_info.description_extractor', ['priority' => -1000]);
  1248.             $definition->addTag('property_info.type_extractor', ['priority' => -1001]);
  1249.         }
  1250.         if ($container->getParameter('kernel.debug')) {
  1251.             $container->removeDefinition('property_info.cache');
  1252.         }
  1253.     }
  1254.     private function registerLockConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  1255.     {
  1256.         $loader->load('lock.xml');
  1257.         foreach ($config['resources'] as $resourceName => $resourceStores) {
  1258.             if (=== \count($resourceStores)) {
  1259.                 continue;
  1260.             }
  1261.             // Generate stores
  1262.             $storeDefinitions = [];
  1263.             foreach ($resourceStores as $storeDsn) {
  1264.                 $storeDsn $container->resolveEnvPlaceholders($storeDsnnull$usedEnvs);
  1265.                 $storeDefinition = new Definition(interface_exists(StoreInterface::class) ? StoreInterface::class : PersistingStoreInterface::class);
  1266.                 $storeDefinition->setFactory([StoreFactory::class, 'createStore']);
  1267.                 $storeDefinition->setArguments([$storeDsn]);
  1268.                 $container->setDefinition($storeDefinitionId '.lock.'.$resourceName.'.store.'.$container->hash($storeDsn), $storeDefinition);
  1269.                 $storeDefinition = new Reference($storeDefinitionId);
  1270.                 $storeDefinitions[] = $storeDefinition;
  1271.             }
  1272.             // Wrap array of stores with CombinedStore
  1273.             if (\count($storeDefinitions) > 1) {
  1274.                 $combinedDefinition = new ChildDefinition('lock.store.combined.abstract');
  1275.                 $combinedDefinition->replaceArgument(0$storeDefinitions);
  1276.                 $container->setDefinition('lock.'.$resourceName.'.store'$combinedDefinition);
  1277.             } else {
  1278.                 $container->setAlias('lock.'.$resourceName.'.store', new Alias((string) $storeDefinitions[0], false));
  1279.             }
  1280.             // Generate factories for each resource
  1281.             $factoryDefinition = new ChildDefinition('lock.factory.abstract');
  1282.             $factoryDefinition->replaceArgument(0, new Reference('lock.'.$resourceName.'.store'));
  1283.             $container->setDefinition('lock.'.$resourceName.'.factory'$factoryDefinition);
  1284.             // Generate services for lock instances
  1285.             $lockDefinition = new Definition(Lock::class);
  1286.             $lockDefinition->setPublic(false);
  1287.             $lockDefinition->setFactory([new Reference('lock.'.$resourceName.'.factory'), 'createLock']);
  1288.             $lockDefinition->setArguments([$resourceName]);
  1289.             $container->setDefinition('lock.'.$resourceName$lockDefinition);
  1290.             // provide alias for default resource
  1291.             if ('default' === $resourceName) {
  1292.                 $container->setAlias('lock.store', new Alias('lock.'.$resourceName.'.store'false));
  1293.                 $container->setAlias('lock.factory', new Alias('lock.'.$resourceName.'.factory'false));
  1294.                 $container->setAlias('lock', new Alias('lock.'.$resourceNamefalse));
  1295.                 $container->setAlias(PersistingStoreInterface::class, new Alias('lock.store'false));
  1296.                 $container->setAlias(LockFactory::class, new Alias('lock.factory'false));
  1297.                 $container->setAlias(LockInterface::class, new Alias('lock'false));
  1298.             } else {
  1299.                 $container->registerAliasForArgument('lock.'.$resourceName.'.store'PersistingStoreInterface::class, $resourceName.'.lock.store');
  1300.                 $container->registerAliasForArgument('lock.'.$resourceName.'.factory'LockFactory::class, $resourceName.'.lock.factory');
  1301.                 $container->registerAliasForArgument('lock.'.$resourceNameLockInterface::class, $resourceName.'.lock');
  1302.             }
  1303.         }
  1304.     }
  1305.     private function registerMessengerConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader, array $validationConfig)
  1306.     {
  1307.         if (!interface_exists(MessageBusInterface::class)) {
  1308.             throw new LogicException('Messenger support cannot be enabled as the Messenger component is not installed. Try running "composer require symfony/messenger".');
  1309.         }
  1310.         $loader->load('messenger.xml');
  1311.         if (null === $config['default_bus'] && === \count($config['buses'])) {
  1312.             $config['default_bus'] = key($config['buses']);
  1313.         }
  1314.         $defaultMiddleware = [
  1315.             'before' => [
  1316.                 ['id' => 'add_bus_name_stamp_middleware'],
  1317.                 ['id' => 'reject_redelivered_message_middleware'],
  1318.                 ['id' => 'dispatch_after_current_bus'],
  1319.                 ['id' => 'failed_message_processing_middleware'],
  1320.             ],
  1321.             'after' => [
  1322.                 ['id' => 'send_message'],
  1323.                 ['id' => 'handle_message'],
  1324.             ],
  1325.         ];
  1326.         foreach ($config['buses'] as $busId => $bus) {
  1327.             $middleware $bus['middleware'];
  1328.             if ($bus['default_middleware']) {
  1329.                 if ('allow_no_handlers' === $bus['default_middleware']) {
  1330.                     $defaultMiddleware['after'][1]['arguments'] = [true];
  1331.                 } else {
  1332.                     unset($defaultMiddleware['after'][1]['arguments']);
  1333.                 }
  1334.                 // argument to add_bus_name_stamp_middleware
  1335.                 $defaultMiddleware['before'][0]['arguments'] = [$busId];
  1336.                 $middleware array_merge($defaultMiddleware['before'], $middleware$defaultMiddleware['after']);
  1337.             }
  1338.             foreach ($middleware as $middlewareItem) {
  1339.                 if (!$validationConfig['enabled'] && \in_array($middlewareItem['id'], ['validation''messenger.middleware.validation'], true)) {
  1340.                     throw new LogicException('The Validation middleware is only available when the Validator component is installed and enabled. Try running "composer require symfony/validator".');
  1341.                 }
  1342.             }
  1343.             if ($container->getParameter('kernel.debug') && class_exists(Stopwatch::class)) {
  1344.                 array_unshift($middleware, ['id' => 'traceable''arguments' => [$busId]]);
  1345.             }
  1346.             $container->setParameter($busId.'.middleware'$middleware);
  1347.             $container->register($busIdMessageBus::class)->addArgument([])->addTag('messenger.bus');
  1348.             if ($busId === $config['default_bus']) {
  1349.                 $container->setAlias('messenger.default_bus'$busId)->setPublic(true);
  1350.                 $container->setAlias(MessageBusInterface::class, $busId);
  1351.             } else {
  1352.                 $container->registerAliasForArgument($busIdMessageBusInterface::class);
  1353.             }
  1354.         }
  1355.         if (empty($config['transports'])) {
  1356.             $container->removeDefinition('messenger.transport.symfony_serializer');
  1357.             $container->removeDefinition('messenger.transport.amqp.factory');
  1358.             $container->removeDefinition('messenger.transport.redis.factory');
  1359.         } else {
  1360.             $container->getDefinition('messenger.transport.symfony_serializer')
  1361.                 ->replaceArgument(1$config['serializer']['symfony_serializer']['format'])
  1362.                 ->replaceArgument(2$config['serializer']['symfony_serializer']['context']);
  1363.             $container->setAlias('messenger.default_serializer'$config['serializer']['default_serializer']);
  1364.         }
  1365.         $senderAliases = [];
  1366.         $transportRetryReferences = [];
  1367.         foreach ($config['transports'] as $name => $transport) {
  1368.             $serializerId $transport['serializer'] ?? 'messenger.default_serializer';
  1369.             $transportDefinition = (new Definition(TransportInterface::class))
  1370.                 ->setFactory([new Reference('messenger.transport_factory'), 'createTransport'])
  1371.                 ->setArguments([$transport['dsn'], $transport['options'] + ['transport_name' => $name], new Reference($serializerId)])
  1372.                 ->addTag('messenger.receiver', ['alias' => $name])
  1373.             ;
  1374.             $container->setDefinition($transportId 'messenger.transport.'.$name$transportDefinition);
  1375.             $senderAliases[$name] = $transportId;
  1376.             if (null !== $transport['retry_strategy']['service']) {
  1377.                 $transportRetryReferences[$name] = new Reference($transport['retry_strategy']['service']);
  1378.             } else {
  1379.                 $retryServiceId sprintf('messenger.retry.multiplier_retry_strategy.%s'$name);
  1380.                 $retryDefinition = new ChildDefinition('messenger.retry.abstract_multiplier_retry_strategy');
  1381.                 $retryDefinition
  1382.                     ->replaceArgument(0$transport['retry_strategy']['max_retries'])
  1383.                     ->replaceArgument(1$transport['retry_strategy']['delay'])
  1384.                     ->replaceArgument(2$transport['retry_strategy']['multiplier'])
  1385.                     ->replaceArgument(3$transport['retry_strategy']['max_delay']);
  1386.                 $container->setDefinition($retryServiceId$retryDefinition);
  1387.                 $transportRetryReferences[$name] = new Reference($retryServiceId);
  1388.             }
  1389.         }
  1390.         $senderReferences = [];
  1391.         // alias => service_id
  1392.         foreach ($senderAliases as $alias => $serviceId) {
  1393.             $senderReferences[$alias] = new Reference($serviceId);
  1394.         }
  1395.         // service_id => service_id
  1396.         foreach ($senderAliases as $serviceId) {
  1397.             $senderReferences[$serviceId] = new Reference($serviceId);
  1398.         }
  1399.         $messageToSendersMapping = [];
  1400.         foreach ($config['routing'] as $message => $messageConfiguration) {
  1401.             if ('*' !== $message && !class_exists($message) && !interface_exists($messagefalse)) {
  1402.                 throw new LogicException(sprintf('Invalid Messenger routing configuration: class or interface "%s" not found.'$message));
  1403.             }
  1404.             // make sure senderAliases contains all senders
  1405.             foreach ($messageConfiguration['senders'] as $sender) {
  1406.                 if (!isset($senderReferences[$sender])) {
  1407.                     throw new LogicException(sprintf('Invalid Messenger routing configuration: the "%s" class is being routed to a sender called "%s". This is not a valid transport or service id.'$message$sender));
  1408.                 }
  1409.             }
  1410.             $messageToSendersMapping[$message] = $messageConfiguration['senders'];
  1411.         }
  1412.         $sendersServiceLocator ServiceLocatorTagPass::register($container$senderReferences);
  1413.         $container->getDefinition('messenger.senders_locator')
  1414.             ->replaceArgument(0$messageToSendersMapping)
  1415.             ->replaceArgument(1$sendersServiceLocator)
  1416.         ;
  1417.         $container->getDefinition('messenger.retry.send_failed_message_for_retry_listener')
  1418.             ->replaceArgument(0$sendersServiceLocator)
  1419.         ;
  1420.         $container->getDefinition('messenger.retry_strategy_locator')
  1421.             ->replaceArgument(0$transportRetryReferences);
  1422.         if ($config['failure_transport']) {
  1423.             if (!isset($senderReferences[$config['failure_transport']])) {
  1424.                 throw new LogicException(sprintf('Invalid Messenger configuration: the failure transport "%s" is not a valid transport or service id.'$config['failure_transport']));
  1425.             }
  1426.             $container->getDefinition('messenger.failure.send_failed_message_to_failure_transport_listener')
  1427.                 ->replaceArgument(0$senderReferences[$config['failure_transport']]);
  1428.             $container->getDefinition('console.command.messenger_failed_messages_retry')
  1429.                 ->replaceArgument(0$config['failure_transport']);
  1430.             $container->getDefinition('console.command.messenger_failed_messages_show')
  1431.                 ->replaceArgument(0$config['failure_transport']);
  1432.             $container->getDefinition('console.command.messenger_failed_messages_remove')
  1433.                 ->replaceArgument(0$config['failure_transport']);
  1434.         } else {
  1435.             $container->removeDefinition('messenger.failure.send_failed_message_to_failure_transport_listener');
  1436.             $container->removeDefinition('console.command.messenger_failed_messages_retry');
  1437.             $container->removeDefinition('console.command.messenger_failed_messages_show');
  1438.             $container->removeDefinition('console.command.messenger_failed_messages_remove');
  1439.         }
  1440.     }
  1441.     private function registerCacheConfiguration(array $configContainerBuilder $container)
  1442.     {
  1443.         if (!class_exists(DefaultMarshaller::class)) {
  1444.             $container->removeDefinition('cache.default_marshaller');
  1445.         }
  1446.         $version = new Parameter('container.build_id');
  1447.         $container->getDefinition('cache.adapter.apcu')->replaceArgument(2$version);
  1448.         $container->getDefinition('cache.adapter.system')->replaceArgument(2$version);
  1449.         $container->getDefinition('cache.adapter.filesystem')->replaceArgument(2$config['directory']);
  1450.         if (isset($config['prefix_seed'])) {
  1451.             $container->setParameter('cache.prefix.seed'$config['prefix_seed']);
  1452.         }
  1453.         if ($container->hasParameter('cache.prefix.seed')) {
  1454.             // Inline any env vars referenced in the parameter
  1455.             $container->setParameter('cache.prefix.seed'$container->resolveEnvPlaceholders($container->getParameter('cache.prefix.seed'), true));
  1456.         }
  1457.         foreach (['doctrine''psr6''redis''memcached''pdo'] as $name) {
  1458.             if (isset($config[$name 'default_'.$name.'_provider'])) {
  1459.                 $container->setAlias('cache.'.$name, new Alias(CachePoolPass::getServiceProvider($container$config[$name]), false));
  1460.             }
  1461.         }
  1462.         foreach (['app''system'] as $name) {
  1463.             $config['pools']['cache.'.$name] = [
  1464.                 'adapters' => [$config[$name]],
  1465.                 'public' => true,
  1466.                 'tags' => false,
  1467.             ];
  1468.         }
  1469.         foreach ($config['pools'] as $name => $pool) {
  1470.             $pool['adapters'] = $pool['adapters'] ?: ['cache.app'];
  1471.             foreach ($pool['adapters'] as $provider => $adapter) {
  1472.                 if ($config['pools'][$adapter]['tags'] ?? false) {
  1473.                     $pool['adapters'][$provider] = $adapter '.'.$adapter.'.inner';
  1474.                 }
  1475.             }
  1476.             if (=== \count($pool['adapters'])) {
  1477.                 if (!isset($pool['provider']) && !\is_int($provider)) {
  1478.                     $pool['provider'] = $provider;
  1479.                 }
  1480.                 $definition = new ChildDefinition($adapter);
  1481.             } else {
  1482.                 $definition = new Definition(ChainAdapter::class, [$pool['adapters'], 0]);
  1483.                 $pool['reset'] = 'reset';
  1484.             }
  1485.             if ($pool['tags']) {
  1486.                 if (true !== $pool['tags'] && ($config['pools'][$pool['tags']]['tags'] ?? false)) {
  1487.                     $pool['tags'] = '.'.$pool['tags'].'.inner';
  1488.                 }
  1489.                 $container->register($nameTagAwareAdapter::class)
  1490.                     ->addArgument(new Reference('.'.$name.'.inner'))
  1491.                     ->addArgument(true !== $pool['tags'] ? new Reference($pool['tags']) : null)
  1492.                     ->setPublic($pool['public'])
  1493.                 ;
  1494.                 $pool['name'] = $name;
  1495.                 $pool['public'] = false;
  1496.                 $name '.'.$name.'.inner';
  1497.                 if (!\in_array($pool['name'], ['cache.app''cache.system'], true)) {
  1498.                     $container->registerAliasForArgument($pool['name'], TagAwareCacheInterface::class);
  1499.                     $container->registerAliasForArgument($nameCacheInterface::class, $pool['name']);
  1500.                     $container->registerAliasForArgument($nameCacheItemPoolInterface::class, $pool['name']);
  1501.                 }
  1502.             } elseif (!\in_array($name, ['cache.app''cache.system'], true)) {
  1503.                 $container->register('.'.$name.'.taggable'TagAwareAdapter::class)
  1504.                     ->addArgument(new Reference($name))
  1505.                 ;
  1506.                 $container->registerAliasForArgument('.'.$name.'.taggable'TagAwareCacheInterface::class, $name);
  1507.                 $container->registerAliasForArgument($nameCacheInterface::class);
  1508.                 $container->registerAliasForArgument($nameCacheItemPoolInterface::class);
  1509.             }
  1510.             $definition->setPublic($pool['public']);
  1511.             unset($pool['adapters'], $pool['public'], $pool['tags']);
  1512.             $definition->addTag('cache.pool'$pool);
  1513.             $container->setDefinition($name$definition);
  1514.         }
  1515.         if (method_exists(PropertyAccessor::class, 'createCache')) {
  1516.             $propertyAccessDefinition $container->register('cache.property_access'AdapterInterface::class);
  1517.             $propertyAccessDefinition->setPublic(false);
  1518.             if (!$container->getParameter('kernel.debug')) {
  1519.                 $propertyAccessDefinition->setFactory([PropertyAccessor::class, 'createCache']);
  1520.                 $propertyAccessDefinition->setArguments([null0$version, new Reference('logger'ContainerInterface::IGNORE_ON_INVALID_REFERENCE)]);
  1521.                 $propertyAccessDefinition->addTag('cache.pool', ['clearer' => 'cache.system_clearer']);
  1522.                 $propertyAccessDefinition->addTag('monolog.logger', ['channel' => 'cache']);
  1523.             } else {
  1524.                 $propertyAccessDefinition->setClass(ArrayAdapter::class);
  1525.                 $propertyAccessDefinition->setArguments([0false]);
  1526.             }
  1527.         }
  1528.     }
  1529.     private function registerHttpClientConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader, array $profilerConfig)
  1530.     {
  1531.         $loader->load('http_client.xml');
  1532.         $container->getDefinition('http_client')->setArguments([$config['default_options'] ?? [], $config['max_host_connections'] ?? 6]);
  1533.         if (!$hasPsr18 interface_exists(ClientInterface::class)) {
  1534.             $container->removeDefinition('psr18.http_client');
  1535.             $container->removeAlias(ClientInterface::class);
  1536.         }
  1537.         if (!interface_exists(HttpClient::class)) {
  1538.             $container->removeDefinition(HttpClient::class);
  1539.         }
  1540.         $httpClientId $this->isConfigEnabled($container$profilerConfig) ? '.debug.http_client.inner' 'http_client';
  1541.         foreach ($config['scoped_clients'] as $name => $scopeConfig) {
  1542.             if ('http_client' === $name) {
  1543.                 throw new InvalidArgumentException(sprintf('Invalid scope name: "%s" is reserved.'$name));
  1544.             }
  1545.             $scope $scopeConfig['scope'] ?? null;
  1546.             unset($scopeConfig['scope']);
  1547.             if (null === $scope) {
  1548.                 $container->register($nameScopingHttpClient::class)
  1549.                     ->setFactory([ScopingHttpClient::class, 'forBaseUri'])
  1550.                     ->setArguments([new Reference($httpClientId), $scopeConfig['base_uri'], $scopeConfig])
  1551.                     ->addTag('http_client.client')
  1552.                 ;
  1553.             } else {
  1554.                 $container->register($nameScopingHttpClient::class)
  1555.                     ->setArguments([new Reference($httpClientId), [$scope => $scopeConfig], $scope])
  1556.                     ->addTag('http_client.client')
  1557.                 ;
  1558.             }
  1559.             $container->registerAliasForArgument($nameHttpClientInterface::class);
  1560.             if ($hasPsr18) {
  1561.                 $container->setDefinition('psr18.'.$name, new ChildDefinition('psr18.http_client'))
  1562.                     ->replaceArgument(0, new Reference($name));
  1563.                 $container->registerAliasForArgument('psr18.'.$nameClientInterface::class, $name);
  1564.             }
  1565.         }
  1566.     }
  1567.     private function registerMailerConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  1568.     {
  1569.         if (!class_exists(Mailer::class)) {
  1570.             throw new LogicException('Mailer support cannot be enabled as the component is not installed. Try running "composer require symfony/mailer".');
  1571.         }
  1572.         $loader->load('mailer.xml');
  1573.         $loader->load('mailer_transports.xml');
  1574.         if (!\count($config['transports']) && null === $config['dsn']) {
  1575.             $config['dsn'] = 'smtp://null';
  1576.         }
  1577.         $transports $config['dsn'] ? ['main' => $config['dsn']] : $config['transports'];
  1578.         $container->getDefinition('mailer.transports')->setArgument(0$transports);
  1579.         $container->getDefinition('mailer.default_transport')->setArgument(0current($transports));
  1580.         $classToServices = [
  1581.             SesTransportFactory::class => 'mailer.transport_factory.amazon',
  1582.             GmailTransportFactory::class => 'mailer.transport_factory.gmail',
  1583.             MandrillTransportFactory::class => 'mailer.transport_factory.mailchimp',
  1584.             MailgunTransportFactory::class => 'mailer.transport_factory.mailgun',
  1585.             PostmarkTransportFactory::class => 'mailer.transport_factory.postmark',
  1586.             SendgridTransportFactory::class => 'mailer.transport_factory.sendgrid',
  1587.         ];
  1588.         foreach ($classToServices as $class => $service) {
  1589.             if (!class_exists($class)) {
  1590.                 $container->removeDefinition($service);
  1591.             }
  1592.         }
  1593.         $recipients $config['envelope']['recipients'] ?? null;
  1594.         $sender $config['envelope']['sender'] ?? null;
  1595.         $envelopeListener $container->getDefinition('mailer.envelope_listener');
  1596.         $envelopeListener->setArgument(0$sender);
  1597.         $envelopeListener->setArgument(1$recipients);
  1598.     }
  1599.     private function registerNotifierConfiguration(array $configContainerBuilder $containerXmlFileLoader $loader)
  1600.     {
  1601.         if (!class_exists(Notifier::class)) {
  1602.             throw new LogicException('Notifier support cannot be enabled as the component is not installed. Try running "composer require symfony/notifier".');
  1603.         }
  1604.         $loader->load('notifier.xml');
  1605.         $loader->load('notifier_transports.xml');
  1606.         if ($config['chatter_transports']) {
  1607.             $container->getDefinition('chatter.transports')->setArgument(0$config['chatter_transports']);
  1608.         } else {
  1609.             $container->removeDefinition('chatter');
  1610.         }
  1611.         if ($config['texter_transports']) {
  1612.             $container->getDefinition('texter.transports')->setArgument(0$config['texter_transports']);
  1613.         } else {
  1614.             $container->removeDefinition('texter');
  1615.         }
  1616.         if ($this->mailerConfigEnabled) {
  1617.             $sender $container->getDefinition('mailer.envelope_listener')->getArgument(0);
  1618.             $container->getDefinition('notifier.channel.email')->setArgument(2$sender);
  1619.         } else {
  1620.             $container->removeDefinition('notifier.channel.email');
  1621.         }
  1622.         if ($this->messengerConfigEnabled) {
  1623.             if ($config['notification_on_failed_messages']) {
  1624.                 $container->getDefinition('notifier.failed_message_listener')->addTag('kernel.event_subscriber');
  1625.             }
  1626.             // as we have a bus, the channels don't need the transports
  1627.             $container->getDefinition('notifier.channel.chat')->setArgument(0null);
  1628.             if ($container->hasDefinition('notifier.channel.email')) {
  1629.                 $container->getDefinition('notifier.channel.email')->setArgument(0null);
  1630.             }
  1631.             $container->getDefinition('notifier.channel.sms')->setArgument(0null);
  1632.         }
  1633.         $container->getDefinition('notifier.channel_policy')->setArgument(0$config['channel_policy']);
  1634.         $classToServices = [
  1635.             SlackTransportFactory::class => 'notifier.transport_factory.slack',
  1636.             TelegramTransportFactory::class => 'notifier.transport_factory.telegram',
  1637.             NexmoTransportFactory::class => 'notifier.transport_factory.nexmo',
  1638.             TwilioTransportFactory::class => 'notifier.transport_factory.twilio',
  1639.         ];
  1640.         foreach ($classToServices as $class => $service) {
  1641.             if (!class_exists($class)) {
  1642.                 $container->removeDefinition($service);
  1643.             }
  1644.         }
  1645.         if (isset($config['admin_recipients'])) {
  1646.             $notifier $container->getDefinition('notifier');
  1647.             foreach ($config['admin_recipients'] as $i => $recipient) {
  1648.                 $id 'notifier.admin_recipient.'.$i;
  1649.                 $container->setDefinition($id, new Definition(AdminRecipient::class, [$recipient['email'], $recipient['phone']]));
  1650.                 $notifier->addMethodCall('addAdminRecipient', [new Reference($id)]);
  1651.             }
  1652.         }
  1653.     }
  1654.     /**
  1655.      * {@inheritdoc}
  1656.      */
  1657.     public function getXsdValidationBasePath()
  1658.     {
  1659.         return \dirname(__DIR__).'/Resources/config/schema';
  1660.     }
  1661.     public function getNamespace()
  1662.     {
  1663.         return 'http://symfony.com/schema/dic/symfony';
  1664.     }
  1665. }