Skip to content

[DI][Config] Add ContainerBuilder::classExists() for checking and tracking class, interface or trait existence #21452

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@

namespace Symfony\Bundle\FrameworkBundle\DependencyInjection;

use Doctrine\Common\Annotations\Annotation;
use Doctrine\Common\Annotations\Reader;
use phpDocumentor\Reflection\DocBlockFactoryInterface;
use Symfony\Bridge\Monolog\Processor\DebugProcessor;
use Symfony\Component\Asset\Package;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\Alias;
Expand All @@ -26,16 +29,21 @@
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Config\Resource\DirectoryResource;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Resource\ClassExistenceResource;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Serializer\Encoder\YamlEncoder;
use Symfony\Component\Serializer\Encoder\CsvEncoder;
use Symfony\Component\Serializer\Mapping\Factory\CacheClassMetadataFactory;
use Symfony\Component\Serializer\Normalizer\DataUriNormalizer;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
use Symfony\Component\Templating\PhpEngine;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Workflow;
use Symfony\Component\Workflow\SupportStrategy\ClassInstanceSupportStrategy;
use Symfony\Component\Yaml\Yaml;
Expand Down Expand Up @@ -85,8 +93,7 @@ public function load(array $configs, ContainerBuilder $container)

$loader->load('fragment_renderer.xml');

$container->addResource(new ClassExistenceResource(Application::class));
if (class_exists(Application::class)) {
if ($container->classExists(Application::class)) {
$loader->load('console.xml');
}

Expand All @@ -105,16 +112,18 @@ public function load(array $configs, ContainerBuilder $container)
// default in the Form and Validator component). If disabled, an identity
// translator will be used and everything will still work as expected.
if ($this->isConfigEnabled($container, $config['translator']) || $this->isConfigEnabled($container, $config['form']) || $this->isConfigEnabled($container, $config['validation'])) {
if (!class_exists('Symfony\Component\Translation\Translator') && $this->isConfigEnabled($container, $config['translator'])) {
throw new LogicException('Translation support cannot be enabled as the Translation component is not installed.');
}
if (!$container->classExists(Translator::class)) {
if ($this->isConfigEnabled($container, $config['translator'])) {
throw new LogicException('Translation support cannot be enabled as the Translation component is not installed.');
}

if (!class_exists('Symfony\Component\Translation\Translator') && $this->isConfigEnabled($container, $config['form'])) {
throw new LogicException('Form support cannot be enabled as the Translation component is not installed.');
}
if ($this->isConfigEnabled($container, $config['form'])) {
throw new LogicException('Form support cannot be enabled as the Translation component is not installed.');
}

if (!class_exists('Symfony\Component\Translation\Translator') && $this->isConfigEnabled($container, $config['validation'])) {
throw new LogicException('Validation support cannot be enabled as the Translation component is not installed.');
if ($this->isConfigEnabled($container, $config['validation'])) {
throw new LogicException('Validation support cannot be enabled as the Translation component is not installed.');
}
}

$loader->load('identity_translator.xml');
Expand Down Expand Up @@ -163,23 +172,23 @@ public function load(array $configs, ContainerBuilder $container)
$this->registerFormConfiguration($config, $container, $loader);
$config['validation']['enabled'] = true;

if (!class_exists('Symfony\Component\Validator\Validation')) {
if (!$container->classExists(Validation::class)) {
throw new LogicException('The Validator component is required to use the Form component.');
}
}

$this->registerSecurityCsrfConfiguration($config['csrf_protection'], $container, $loader);

if ($this->isConfigEnabled($container, $config['assets'])) {
if (!class_exists('Symfony\Component\Asset\Package')) {
if (!$container->classExists(Package::class)) {
throw new LogicException('Asset support cannot be enabled as the Asset component is not installed.');
}

$this->registerAssetsConfiguration($config['assets'], $container, $loader);
}

if ($this->isConfigEnabled($container, $config['templating'])) {
if (!class_exists('Symfony\Component\Templating\PhpEngine')) {
if (!$container->classExists(PhpEngine::class)) {
throw new LogicException('Templating support cannot be enabled as the Templating component is not installed.');
}

Expand Down Expand Up @@ -525,7 +534,7 @@ private function registerDebugConfiguration(array $config, ContainerBuilder $con
$definition->replaceArgument(4, $debug);
$definition->replaceArgument(6, $debug);

if ($debug && class_exists(DebugProcessor::class)) {
if ($debug && $container->classExists(DebugProcessor::class)) {
$definition = new Definition(DebugProcessor::class);
$definition->setPublic(false);
$container->setDefinition('debug.log_processor', $definition);
Expand Down Expand Up @@ -860,18 +869,18 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder

// Discover translation directories
$dirs = array();
if (class_exists('Symfony\Component\Validator\Validation')) {
$r = new \ReflectionClass('Symfony\Component\Validator\Validation');
if ($container->classExists(Validation::class)) {
$r = new \ReflectionClass(Validation::class);

$dirs[] = dirname($r->getFileName()).'/Resources/translations';
}
if (class_exists('Symfony\Component\Form\Form')) {
$r = new \ReflectionClass('Symfony\Component\Form\Form');
if ($container->classExists(Form::class)) {
$r = new \ReflectionClass(Form::class);

$dirs[] = dirname($r->getFileName()).'/Resources/translations';
}
if (class_exists('Symfony\Component\Security\Core\Exception\AuthenticationException')) {
$r = new \ReflectionClass('Symfony\Component\Security\Core\Exception\AuthenticationException');
if ($container->classExists(AuthenticationException::class)) {
$r = new \ReflectionClass(AuthenticationException::class);

$dirs[] = dirname(dirname($r->getFileName())).'/Resources/translations';
}
Expand Down Expand Up @@ -944,7 +953,7 @@ private function registerValidationConfiguration(array $config, ContainerBuilder
return;
}

if (!class_exists('Symfony\Component\Validator\Validation')) {
if (!$container->classExists(Validation::class)) {
throw new LogicException('Validation support cannot be enabled as the Validator component is not installed.');
}

Expand Down Expand Up @@ -999,8 +1008,8 @@ private function registerValidationConfiguration(array $config, ContainerBuilder

private function getValidatorMappingFiles(ContainerBuilder $container, array &$files)
{
if (interface_exists('Symfony\Component\Form\FormInterface')) {
$reflClass = new \ReflectionClass('Symfony\Component\Form\FormInterface');
if ($container->classExists(FormInterface::class)) {
$reflClass = new \ReflectionClass(FormInterface::class);
$files['xml'][] = $file = dirname($reflClass->getFileName()).'/Resources/config/validation.xml';
$container->addResource(new FileResource($file));
}
Expand Down Expand Up @@ -1057,7 +1066,7 @@ private function registerAnnotationsConfiguration(array $config, ContainerBuilde
return;
}

if (!class_exists('Doctrine\Common\Annotations\Annotation')) {
if (!$container->classExists(Annotation::class)) {
throw new LogicException('Annotations cannot be enabled as the Doctrine Annotation library is not installed.');
}

Expand Down Expand Up @@ -1129,7 +1138,7 @@ private function registerSecurityCsrfConfiguration(array $config, ContainerBuild
return;
}

if (!class_exists('Symfony\Component\Security\Csrf\CsrfToken')) {
if (!$container->classExists('Symfony\Component\Security\Csrf\CsrfToken')) {
throw new LogicException('CSRF support cannot be enabled as the Security CSRF component is not installed.');
}

Expand All @@ -1150,34 +1159,34 @@ private function registerSecurityCsrfConfiguration(array $config, ContainerBuild
*/
private function registerSerializerConfiguration(array $config, ContainerBuilder $container, XmlFileLoader $loader)
{
if (class_exists('Symfony\Component\Serializer\Normalizer\DataUriNormalizer')) {
if ($container->classExists(DataUriNormalizer::class)) {
// Run after serializer.normalizer.object
$definition = $container->register('serializer.normalizer.data_uri', DataUriNormalizer::class);
$definition->setPublic(false);
$definition->addTag('serializer.normalizer', array('priority' => -920));
}

if (class_exists('Symfony\Component\Serializer\Normalizer\DateTimeNormalizer')) {
if ($container->classExists(DateTimeNormalizer::class)) {
// Run before serializer.normalizer.object
$definition = $container->register('serializer.normalizer.datetime', DateTimeNormalizer::class);
$definition->setPublic(false);
$definition->addTag('serializer.normalizer', array('priority' => -910));
}

if (class_exists('Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer')) {
if ($container->classExists(JsonSerializableNormalizer::class)) {
// Run before serializer.normalizer.object
$definition = $container->register('serializer.normalizer.json_serializable', JsonSerializableNormalizer::class);
$definition->setPublic(false);
$definition->addTag('serializer.normalizer', array('priority' => -900));
}

if (class_exists(YamlEncoder::class) && defined('Symfony\Component\Yaml\Yaml::DUMP_OBJECT')) {
if ($container->classExists(YamlEncoder::class) && defined('Symfony\Component\Yaml\Yaml::DUMP_OBJECT')) {
$definition = $container->register('serializer.encoder.yaml', YamlEncoder::class);
$definition->setPublic(false);
$definition->addTag('serializer.encoder');
}

if (class_exists(CsvEncoder::class)) {
if ($container->classExists(CsvEncoder::class)) {
$definition = $container->register('serializer.encoder.csv', CsvEncoder::class);
$definition->setPublic(false);
$definition->addTag('serializer.encoder');
Expand Down Expand Up @@ -1252,7 +1261,7 @@ private function registerSerializerConfiguration(array $config, ContainerBuilder
$container->getDefinition('serializer.mapping.class_metadata_factory')->replaceArgument(
1, new Reference($config['cache'])
);
} elseif (!$container->getParameter('kernel.debug') && class_exists(CacheClassMetadataFactory::class)) {
} elseif (!$container->getParameter('kernel.debug') && $container->classExists(CacheClassMetadataFactory::class)) {
$cacheMetadataFactory = new Definition(
CacheClassMetadataFactory::class,
array(
Expand Down Expand Up @@ -1282,7 +1291,7 @@ private function registerPropertyInfoConfiguration(array $config, ContainerBuild
{
$loader->load('property_info.xml');

if (interface_exists('phpDocumentor\Reflection\DocBlockFactoryInterface')) {
if ($container->classExists(DocBlockFactoryInterface::class)) {
$definition = $container->register('property_info.php_doc_extractor', 'Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor');
$definition->addTag('property_info.description_extractor', array('priority' => -1000));
$definition->addTag('property_info.type_extractor', array('priority' => -1001));
Expand Down Expand Up @@ -1324,7 +1333,7 @@ private function registerCacheConfiguration(array $config, ContainerBuilder $con
$container->setDefinition($name, $definition);
}

if (method_exists(PropertyAccessor::class, 'createCache')) {
if ($container->classExists(PropertyAccessor::class) && method_exists(PropertyAccessor::class, 'createCache')) {
$propertyAccessDefinition = $container->register('cache.property_access', AdapterInterface::class);
$propertyAccessDefinition->setPublic(false);
$propertyAccessDefinition->setFactory(array(PropertyAccessor::class, 'createCache'));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\Security\Acl\Model\AclInterface;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;

/**
Expand Down Expand Up @@ -70,7 +72,7 @@ public function load(array $configs, ContainerBuilder $container)
$loader->load('security_debug.xml');
}

if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
if (!$container->classExists(Expression::class)) {
$container->removeDefinition('security.expression_language');
$container->removeDefinition('security.access.expression_voter');
}
Expand Down Expand Up @@ -121,7 +123,7 @@ public function load(array $configs, ContainerBuilder $container)

private function aclLoad($config, ContainerBuilder $container)
{
if (!interface_exists('Symfony\Component\Security\Acl\Model\AclInterface')) {
if (!$container->classExists(AclInterface::class)) {
throw new \LogicException('You must install symfony/security-acl in order to use the ACL functionality.');
}

Expand Down Expand Up @@ -643,7 +645,7 @@ private function createExpression($container, $expression)
->register($id, 'Symfony\Component\ExpressionLanguage\SerializedParsedExpression')
->setPublic(false)
->addArgument($expression)
->addArgument(serialize($this->getExpressionLanguage()->parse($expression, array('token', 'user', 'object', 'roles', 'request', 'trust_resolver'))->getNodes()))
->addArgument(serialize($this->getExpressionLanguage($container)->parse($expression, array('token', 'user', 'object', 'roles', 'request', 'trust_resolver'))->getNodes()))
;

return $this->expressions[$id] = new Reference($id);
Expand Down Expand Up @@ -708,10 +710,10 @@ public function getConfiguration(array $config, ContainerBuilder $container)
return new MainConfiguration($this->factories, $this->userProviderFactories);
}

private function getExpressionLanguage()
private function getExpressionLanguage($container)
{
if (null === $this->expressionLanguage) {
if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
if (!$container->hasDefinition('security.expression_language')) {
throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
}
$this->expressionLanguage = new ExpressionLanguage();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@

namespace Symfony\Bundle\TwigBundle\DependencyInjection\Compiler;

use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
* Registers the Twig exception listener if Twig is registered as a templating engine.
Expand All @@ -28,7 +30,7 @@ public function process(ContainerBuilder $container)
}

// register the exception controller only if Twig is enabled and required dependencies do exist
if (!class_exists('Symfony\Component\Debug\Exception\FlattenException') || !interface_exists('Symfony\Component\EventDispatcher\EventSubscriberInterface')) {
if (!$container->classExists(FlattenException::class) || !$container->classExists(EventSubscriberInterface::class)) {
$container->removeDefinition('twig.exception_listener');
} elseif ($container->hasParameter('templating.engines')) {
$engines = $container->getParameter('templating.engines');
Expand Down
Loading