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

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