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

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