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