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

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