diff --git a/UPGRADE-4.0.md b/UPGRADE-4.0.md index 23ed6fbd33..8947744a9f 100644 --- a/UPGRADE-4.0.md +++ b/UPGRADE-4.0.md @@ -230,7 +230,7 @@ DependencyInjection supported. * The ``strict`` attribute in service arguments has been removed. - The attribute is ignored since 3.0, so you can simply remove it. + The attribute is ignored since 3.0, you can remove it. * Top-level anonymous services in XML are no longer supported. diff --git a/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterMappingsPass.php b/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterMappingsPass.php index 5c33f71f04..5b1d78fbf8 100644 --- a/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterMappingsPass.php +++ b/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterMappingsPass.php @@ -24,8 +24,8 @@ use Symfony\Component\DependencyInjection\Reference; * The compiler pass is meant to register the mappings with the metadata * chain driver corresponding to one of the object managers. * - * For concrete implementations that are easy to use, see the - * RegisterXyMappingsPass classes in the DoctrineBundle resp. + * For concrete implementations, see the RegisterXyMappingsPass classes + * in the DoctrineBundle resp. * DoctrineMongodbBundle, DoctrineCouchdbBundle and DoctrinePhpcrBundle. * * @author David Buchmann diff --git a/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php b/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php index d9f7f391d2..49dfd9bfbc 100644 --- a/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php +++ b/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php @@ -165,7 +165,7 @@ class DoctrineOrmTypeGuesser implements FormTypeGuesserInterface // normalize class name $class = self::getRealClass(ltrim($class, '\\')); - if (array_key_exists($class, $this->cache)) { + if (\array_key_exists($class, $this->cache)) { return $this->cache[$class]; } diff --git a/src/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php b/src/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php index 769e9bb20e..20f6839957 100644 --- a/src/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php +++ b/src/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php @@ -20,7 +20,7 @@ use Symfony\Component\Security\Core\User\UserProviderInterface; /** * Wrapper around a Doctrine ObjectManager. * - * Provides easy to use provisioning for Doctrine entity users. + * Provides provisioning for Doctrine entity users. * * @author Fabien Potencier * @author Johannes M. Schmitt diff --git a/src/Symfony/Bridge/Monolog/Handler/FingersCrossed/HttpCodeActivationStrategy.php b/src/Symfony/Bridge/Monolog/Handler/FingersCrossed/HttpCodeActivationStrategy.php index b31817d76d..ae8fd3650a 100644 --- a/src/Symfony/Bridge/Monolog/Handler/FingersCrossed/HttpCodeActivationStrategy.php +++ b/src/Symfony/Bridge/Monolog/Handler/FingersCrossed/HttpCodeActivationStrategy.php @@ -31,10 +31,10 @@ class HttpCodeActivationStrategy extends ErrorLevelActivationStrategy public function __construct(RequestStack $requestStack, array $exclusions, $actionLevel) { foreach ($exclusions as $exclusion) { - if (!array_key_exists('code', $exclusion)) { + if (!\array_key_exists('code', $exclusion)) { throw new \LogicException(sprintf('An exclusion must have a "code" key')); } - if (!array_key_exists('urls', $exclusion)) { + if (!\array_key_exists('urls', $exclusion)) { throw new \LogicException(sprintf('An exclusion must have a "urls" key')); } } diff --git a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/PhpDumper/Fixtures/proxy-factory.php b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/PhpDumper/Fixtures/proxy-factory.php index af3b972cdf..e571b85571 100644 --- a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/PhpDumper/Fixtures/proxy-factory.php +++ b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/PhpDumper/Fixtures/proxy-factory.php @@ -1,7 +1,6 @@ data)) { + if (\array_key_exists($key, $this->data)) { return true; } @@ -98,7 +98,7 @@ class Scope */ public function get($key, $default = null) { - if (array_key_exists($key, $this->data)) { + if (\array_key_exists($key, $this->data)) { return $this->data[$key]; } diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/ConfigDebugCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/ConfigDebugCommand.php index a4a10805f6..7d3373f3eb 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/ConfigDebugCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/ConfigDebugCommand.php @@ -138,7 +138,7 @@ EOF $steps = explode('.', $path); foreach ($steps as $step) { - if (!array_key_exists($step, $config)) { + if (!\array_key_exists($step, $config)) { throw new LogicException(sprintf('Unable to find configuration for "%s.%s"', $alias, $path)); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/Descriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/Descriptor.php index d2afe921ff..484ca4fefd 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/Descriptor.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/Descriptor.php @@ -11,6 +11,7 @@ namespace Symfony\Bundle\FrameworkBundle\Console\Descriptor; +use Symfony\Component\Config\Resource\ClassExistenceResource; use Symfony\Component\Console\Descriptor\DescriptorInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\DependencyInjection\Alias; @@ -226,7 +227,7 @@ abstract class Descriptor implements DescriptorInterface return $builder->getDefinition($serviceId); } - // Some service IDs don't have a Definition, they're simply an Alias + // Some service IDs don't have a Definition, they're aliases if ($builder->hasAlias($serviceId)) { return $builder->getAlias($serviceId); } @@ -292,6 +293,11 @@ abstract class Descriptor implements DescriptorInterface { $resolvedClass = $class; try { + $resource = new ClassExistenceResource($class, false); + + // isFresh() will explode ONLY if a parent class/trait does not exist + $resource->isFresh(0); + $r = new \ReflectionClass($class); $resolvedClass = $r->name; diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php index 06d57dcdb2..44fae86bc0 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php @@ -156,7 +156,7 @@ class JsonDescriptor extends Descriptor */ protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = []) { - $this->writeData($this->getEventDispatcherListenersData($eventDispatcher, array_key_exists('event', $options) ? $options['event'] : null), $options); + $this->writeData($this->getEventDispatcherListenersData($eventDispatcher, \array_key_exists('event', $options) ? $options['event'] : null), $options); } /** diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/MarkdownDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/MarkdownDescriptor.php index 89180c03ca..56e11b07f6 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/MarkdownDescriptor.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/MarkdownDescriptor.php @@ -274,7 +274,7 @@ class MarkdownDescriptor extends Descriptor */ protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = []) { - $event = array_key_exists('event', $options) ? $options['event'] : null; + $event = \array_key_exists('event', $options) ? $options['event'] : null; $title = 'Registered listeners'; if (null !== $event) { diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php index 79566a1ad9..c0ec5e412e 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php @@ -385,7 +385,7 @@ class TextDescriptor extends Descriptor */ protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = []) { - $event = array_key_exists('event', $options) ? $options['event'] : null; + $event = \array_key_exists('event', $options) ? $options['event'] : null; if (null !== $event) { $title = sprintf('Registered Listeners for "%s" Event', $event); diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/XmlDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/XmlDescriptor.php index d66a081aab..3e66b05d0b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/XmlDescriptor.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/XmlDescriptor.php @@ -112,7 +112,7 @@ class XmlDescriptor extends Descriptor */ protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = []) { - $this->writeDocument($this->getEventDispatcherListenersDocument($eventDispatcher, array_key_exists('event', $options) ? $options['event'] : null)); + $this->writeDocument($this->getEventDispatcherListenersDocument($eventDispatcher, \array_key_exists('event', $options) ? $options['event'] : null)); } /** diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php index 53a3220000..0d2aa264ad 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php @@ -327,7 +327,7 @@ class Configuration implements ConfigurationInterface } foreach ($places as $name => $place) { - if (\is_array($place) && array_key_exists('name', $place)) { + if (\is_array($place) && \array_key_exists('name', $place)) { continue; } $place['name'] = $name; @@ -365,7 +365,7 @@ class Configuration implements ConfigurationInterface } foreach ($transitions as $name => $transition) { - if (\is_array($transition) && array_key_exists('name', $transition)) { + if (\is_array($transition) && \array_key_exists('name', $transition)) { continue; } $transition['name'] = $name; diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php index ee23ac58aa..714d92379d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php @@ -939,7 +939,7 @@ class FrameworkExtension extends Extension foreach ($config['packages'] as $name => $package) { if (null !== $package['version_strategy']) { $version = new Reference($package['version_strategy']); - } elseif (!array_key_exists('version', $package) && null === $package['json_manifest_path']) { + } elseif (!\array_key_exists('version', $package) && null === $package['json_manifest_path']) { // if neither version nor json_manifest_path are specified, use the default $version = $defaultVersion; } else { @@ -1146,7 +1146,7 @@ class FrameworkExtension extends Extension $definition = $container->findDefinition('validator.email'); $definition->replaceArgument(0, $config['email_validation_mode']); - if (array_key_exists('enable_annotations', $config) && $config['enable_annotations']) { + if (\array_key_exists('enable_annotations', $config) && $config['enable_annotations']) { if (!$this->annotationsConfigEnabled) { throw new \LogicException('"enable_annotations" on the validator cannot be set as Annotations support is disabled.'); } @@ -1154,7 +1154,7 @@ class FrameworkExtension extends Extension $validatorBuilder->addMethodCall('enableAnnotationMapping', [new Reference('annotation_reader')]); } - if (array_key_exists('static_method', $config) && $config['static_method']) { + if (\array_key_exists('static_method', $config) && $config['static_method']) { foreach ($config['static_method'] as $methodName) { $validatorBuilder->addMethodCall('addMethodMapping', [$methodName]); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/CacheClearCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/CacheClearCommandTest.php index e91ecc50ca..9e4c46d585 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/CacheClearCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/CacheClearCommandTest.php @@ -51,7 +51,7 @@ class CacheClearCommandTest extends TestCase // Ensure that all *.meta files are fresh $finder = new Finder(); $metaFiles = $finder->files()->in($this->kernel->getCacheDir())->name('*.php.meta'); - // simply check that cache is warmed up + // check that cache is warmed up $this->assertNotEmpty($metaFiles); $configCacheFactory = new ConfigCacheFactory(true); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/ContainerDebugCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/ContainerDebugCommandTest.php index 93028bf8c2..ee13386a4b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/ContainerDebugCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/ContainerDebugCommandTest.php @@ -22,7 +22,7 @@ class ContainerDebugCommandTest extends WebTestCase { public function testDumpContainerIfNotExists() { - static::bootKernel(['test_case' => 'ContainerDebug', 'root_config' => 'config.yml']); + static::bootKernel(['test_case' => 'ContainerDebug', 'root_config' => 'config.yml', 'debug' => true]); $application = new Application(static::$kernel); $application->setAutoExit(false); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/WebTestCase.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/WebTestCase.php index 3f7bb4c7ee..00eda65709 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/WebTestCase.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/WebTestCase.php @@ -62,7 +62,7 @@ class WebTestCase extends BaseWebTestCase $options['test_case'], isset($options['root_config']) ? $options['root_config'] : 'config.yml', isset($options['environment']) ? $options['environment'] : strtolower(static::getVarDir().$options['test_case']), - isset($options['debug']) ? $options['debug'] : true + isset($options['debug']) ? $options['debug'] : false ); } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php index 108afc2f7c..a3d41a70a6 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php @@ -67,7 +67,7 @@ class SecurityExtension extends Extension implements PrependExtensionInterface foreach ($container->getExtensionConfig('framework') as $config) { if (isset($config['session']) && \is_array($config['session'])) { $rememberMeSecureDefault = $config['session']['cookie_secure'] ?? $rememberMeSecureDefault; - $rememberMeSameSiteDefault = array_key_exists('cookie_samesite', $config['session']) ? $config['session']['cookie_samesite'] : $rememberMeSameSiteDefault; + $rememberMeSameSiteDefault = \array_key_exists('cookie_samesite', $config['session']) ? $config['session']['cookie_samesite'] : $rememberMeSameSiteDefault; } } foreach ($this->listenerPositions as $position) { @@ -412,7 +412,7 @@ class SecurityExtension extends Extension implements PrependExtensionInterface foreach ($this->factories as $position) { foreach ($position as $factory) { $key = str_replace('-', '_', $factory->getKey()); - if (array_key_exists($key, $firewall)) { + if (\array_key_exists($key, $firewall)) { $listenerKeys[] = $key; } } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/WebTestCase.php b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/WebTestCase.php index f1d23b6054..9bcbc05324 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/WebTestCase.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/WebTestCase.php @@ -62,7 +62,7 @@ class WebTestCase extends BaseWebTestCase $options['test_case'], isset($options['root_config']) ? $options['root_config'] : 'config.yml', isset($options['environment']) ? $options['environment'] : strtolower(static::getVarDir().$options['test_case']), - isset($options['debug']) ? $options['debug'] : true + isset($options['debug']) ? $options['debug'] : false ); } diff --git a/src/Symfony/Bundle/WebServerBundle/Resources/router.php b/src/Symfony/Bundle/WebServerBundle/Resources/router.php index a366b381aa..30d6b258a2 100644 --- a/src/Symfony/Bundle/WebServerBundle/Resources/router.php +++ b/src/Symfony/Bundle/WebServerBundle/Resources/router.php @@ -17,8 +17,8 @@ * If you have custom directory layout, then you have to write your own router * and pass it as a value to 'router' option of server:run command. * - * @author: Michał Pipa - * @author: Albert Jessurum + * @author Michał Pipa + * @author Albert Jessurum */ // Workaround https://bugs.php.net/64566 diff --git a/src/Symfony/Component/BrowserKit/Client.php b/src/Symfony/Component/BrowserKit/Client.php index 307c3b0252..9678cd381a 100644 --- a/src/Symfony/Component/BrowserKit/Client.php +++ b/src/Symfony/Component/BrowserKit/Client.php @@ -548,7 +548,7 @@ abstract class Client { do { $request = $this->history->back(); - } while (array_key_exists(serialize($request), $this->redirects)); + } while (\array_key_exists(serialize($request), $this->redirects)); return $this->requestFromRequest($request, false); } @@ -562,7 +562,7 @@ abstract class Client { do { $request = $this->history->forward(); - } while (array_key_exists(serialize($request), $this->redirects)); + } while (\array_key_exists(serialize($request), $this->redirects)); return $this->requestFromRequest($request, false); } diff --git a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php index d93ae711bd..6897fbceee 100644 --- a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php @@ -94,7 +94,7 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg } /** - * Returns an ApcuAdapter if supported, a PhpFilesAdapter otherwise. + * Returns the best possible adapter that your runtime supports. * * Using ApcuAdapter makes system caches compatible with read-only filesystems. * @@ -108,16 +108,12 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg */ public static function createSystemCache($namespace, $defaultLifetime, $version, $directory, LoggerInterface $logger = null) { - if (null === self::$apcuSupported) { - self::$apcuSupported = ApcuAdapter::isSupported(); + $opcache = new PhpFilesAdapter($namespace, $defaultLifetime, $directory, true); + if (null !== $logger) { + $opcache->setLogger($logger); } - if (!self::$apcuSupported) { - $opcache = new PhpFilesAdapter($namespace, $defaultLifetime, $directory, true); - if (null !== $logger) { - $opcache->setLogger($logger); - } - + if (!self::$apcuSupported = self::$apcuSupported ?? ApcuAdapter::isSupported()) { return $opcache; } @@ -128,7 +124,7 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg $apcu->setLogger($logger); } - return $apcu; + return new ChainAdapter([$apcu, $opcache]); } public static function createConnection($dsn, array $options = []) diff --git a/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php b/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php index 8a7d147808..0eceb6e572 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php @@ -22,7 +22,7 @@ abstract class AdapterTestCase extends CachePoolTest { parent::setUp(); - if (!array_key_exists('testPrune', $this->skippedTests) && !$this->createCachePool() instanceof PruneableInterface) { + if (!\array_key_exists('testPrune', $this->skippedTests) && !$this->createCachePool() instanceof PruneableInterface) { $this->skippedTests['testPrune'] = 'Not a pruneable cache pool.'; } } diff --git a/src/Symfony/Component/Cache/Tests/Psr16CacheTest.php b/src/Symfony/Component/Cache/Tests/Psr16CacheTest.php index 8fb10f2372..6692d3eb59 100644 --- a/src/Symfony/Component/Cache/Tests/Psr16CacheTest.php +++ b/src/Symfony/Component/Cache/Tests/Psr16CacheTest.php @@ -25,7 +25,7 @@ class Psr16CacheTest extends SimpleCacheTest { parent::setUp(); - if (array_key_exists('testPrune', $this->skippedTests)) { + if (\array_key_exists('testPrune', $this->skippedTests)) { return; } diff --git a/src/Symfony/Component/Cache/Tests/Simple/CacheTestCase.php b/src/Symfony/Component/Cache/Tests/Simple/CacheTestCase.php index 1a13cbaae8..3c8824869b 100644 --- a/src/Symfony/Component/Cache/Tests/Simple/CacheTestCase.php +++ b/src/Symfony/Component/Cache/Tests/Simple/CacheTestCase.php @@ -21,7 +21,7 @@ abstract class CacheTestCase extends SimpleCacheTest { parent::setUp(); - if (!array_key_exists('testPrune', $this->skippedTests) && !$this->createSimpleCache() instanceof PruneableInterface) { + if (!\array_key_exists('testPrune', $this->skippedTests) && !$this->createSimpleCache() instanceof PruneableInterface) { $this->skippedTests['testPrune'] = 'Not a pruneable cache pool.'; } } diff --git a/src/Symfony/Component/Cache/Traits/MemcachedTrait.php b/src/Symfony/Component/Cache/Traits/MemcachedTrait.php index b83d695937..9c52323943 100644 --- a/src/Symfony/Component/Cache/Traits/MemcachedTrait.php +++ b/src/Symfony/Component/Cache/Traits/MemcachedTrait.php @@ -166,7 +166,7 @@ trait MemcachedTrait $client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true); $client->setOption(\Memcached::OPT_NO_BLOCK, true); $client->setOption(\Memcached::OPT_TCP_NODELAY, true); - if (!array_key_exists('LIBKETAMA_COMPATIBLE', $options) && !array_key_exists(\Memcached::OPT_LIBKETAMA_COMPATIBLE, $options)) { + if (!\array_key_exists('LIBKETAMA_COMPATIBLE', $options) && !\array_key_exists(\Memcached::OPT_LIBKETAMA_COMPATIBLE, $options)) { $client->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true); } foreach ($options as $name => $value) { diff --git a/src/Symfony/Component/Cache/Traits/RedisTrait.php b/src/Symfony/Component/Cache/Traits/RedisTrait.php index 0276c4fb6d..8da2e257a8 100644 --- a/src/Symfony/Component/Cache/Traits/RedisTrait.php +++ b/src/Symfony/Component/Cache/Traits/RedisTrait.php @@ -284,7 +284,7 @@ trait RedisTrait $result = []; - if ($this->redis instanceof \Predis\Client) { + if ($this->redis instanceof \Predis\Client && $this->redis->getConnection() instanceof ClusterInterface) { $values = $this->pipeline(function () use ($ids) { foreach ($ids as $id) { yield 'get' => [$id]; diff --git a/src/Symfony/Component/Config/Definition/ArrayNode.php b/src/Symfony/Component/Config/Definition/ArrayNode.php index dd908c999e..43697ef279 100644 --- a/src/Symfony/Component/Config/Definition/ArrayNode.php +++ b/src/Symfony/Component/Config/Definition/ArrayNode.php @@ -59,7 +59,7 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface $normalized = []; foreach ($value as $k => $v) { - if (false !== strpos($k, '-') && false === strpos($k, '_') && !array_key_exists($normalizedKey = str_replace('-', '_', $k), $value)) { + if (false !== strpos($k, '-') && false === strpos($k, '_') && !\array_key_exists($normalizedKey = str_replace('-', '_', $k), $value)) { $normalized[$normalizedKey] = $v; } else { $normalized[$k] = $v; @@ -223,7 +223,7 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface } foreach ($this->children as $name => $child) { - if (!array_key_exists($name, $value)) { + if (!\array_key_exists($name, $value)) { if ($child->isRequired()) { $ex = new InvalidConfigurationException(sprintf('The child node "%s" at path "%s" must be configured.', $name, $this->getPath())); $ex->setPath($this->getPath()); @@ -383,7 +383,7 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface foreach ($rightSide as $k => $v) { // no conflict - if (!array_key_exists($k, $leftSide)) { + if (!\array_key_exists($k, $leftSide)) { if (!$this->allowNewKeys) { $ex = new InvalidConfigurationException(sprintf('You are not allowed to define new elements for path "%s". Please define all elements for this path in one config file. If you are trying to overwrite an element, make sure you redefine it with the same name.', $this->getPath())); $ex->setPath($this->getPath()); diff --git a/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php b/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php index 43c2b8b731..dca5687a20 100644 --- a/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php +++ b/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php @@ -332,10 +332,10 @@ class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinition * Allows extra config keys to be specified under an array without * throwing an exception. * - * Those config values are simply ignored and removed from the - * resulting array. This should be used only in special cases where - * you want to send an entire configuration array through a special - * tree that processes only part of the array. + * Those config values are ignored and removed from the resulting + * array. This should be used only in special cases where you want + * to send an entire configuration array through a special tree that + * processes only part of the array. * * @param bool $remove Whether to remove the extra keys * diff --git a/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php b/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php index 4a3446f52f..dd6ccd94a3 100644 --- a/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php +++ b/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php @@ -245,7 +245,7 @@ class PrototypedArrayNode extends ArrayNode // if only "value" is left if (array_keys($v) === ['value']) { $v = $v['value']; - if ($this->prototype instanceof ArrayNode && ($children = $this->prototype->getChildren()) && array_key_exists('value', $children)) { + if ($this->prototype instanceof ArrayNode && ($children = $this->prototype->getChildren()) && \array_key_exists('value', $children)) { $valuePrototype = current($this->valuePrototypes) ?: clone $children['value']; $valuePrototype->parent = $this; $originalClosures = $this->prototype->normalizationClosures; @@ -258,7 +258,7 @@ class PrototypedArrayNode extends ArrayNode } } - if (array_key_exists($k, $normalized)) { + if (\array_key_exists($k, $normalized)) { $ex = new DuplicateKeyException(sprintf('Duplicate key "%s" for path "%s".', $k, $this->getPath())); $ex->setPath($this->getPath()); @@ -301,14 +301,14 @@ class PrototypedArrayNode extends ArrayNode } foreach ($rightSide as $k => $v) { - // prototype, and key is irrelevant, so simply append the element + // prototype, and key is irrelevant, append the element if (null === $this->keyAttribute) { $leftSide[] = $v; continue; } // no conflict - if (!array_key_exists($k, $leftSide)) { + if (!\array_key_exists($k, $leftSide)) { if (!$this->allowNewKeys) { $ex = new InvalidConfigurationException(sprintf('You are not allowed to define new elements for path "%s". Please define all elements for this path in one config file.', $this->getPath())); $ex->setPath($this->getPath()); diff --git a/src/Symfony/Component/Console/Application.php b/src/Symfony/Component/Console/Application.php index f96d690589..17df91f994 100644 --- a/src/Symfony/Component/Console/Application.php +++ b/src/Symfony/Component/Console/Application.php @@ -199,6 +199,13 @@ class Application return 0; } + try { + // Makes ArgvInput::getFirstArgument() able to distinguish an option from an argument. + $input->bind($this->getDefinition()); + } catch (ExceptionInterface $e) { + // Errors must be ignored, full binding/validation happens later when the command is known. + } + $name = $this->getCommandName($input); if (true === $input->hasParameterOption(['--help', '-h'], true)) { if (!$name) { diff --git a/src/Symfony/Component/Console/Helper/QuestionHelper.php b/src/Symfony/Component/Console/Helper/QuestionHelper.php index e367c7d430..cf6447a4bc 100644 --- a/src/Symfony/Component/Console/Helper/QuestionHelper.php +++ b/src/Symfony/Component/Console/Helper/QuestionHelper.php @@ -269,6 +269,10 @@ class QuestionHelper extends Helper continue; } else { + if ("\x80" <= $c) { + $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]); + } + $output->write($c); $ret .= $c; ++$i; diff --git a/src/Symfony/Component/Console/Input/ArgvInput.php b/src/Symfony/Component/Console/Input/ArgvInput.php index 85ff6f91d8..c56c20c684 100644 --- a/src/Symfony/Component/Console/Input/ArgvInput.php +++ b/src/Symfony/Component/Console/Input/ArgvInput.php @@ -257,8 +257,27 @@ class ArgvInput extends Input */ public function getFirstArgument() { - foreach ($this->tokens as $token) { + $isOption = false; + foreach ($this->tokens as $i => $token) { if ($token && '-' === $token[0]) { + if (false !== strpos($token, '=') || !isset($this->tokens[$i + 1])) { + continue; + } + + // If it's a long option, consider that everything after "--" is the option name. + // Otherwise, use the last char (if it's a short option set, only the last one can take a value with space separator) + $name = '-' === $token[1] ? substr($token, 2) : substr($token, -1); + if (!isset($this->options[$name]) && !$this->definition->hasShortcut($name)) { + // noop + } elseif ((isset($this->options[$name]) || isset($this->options[$name = $this->definition->shortcutToName($name)])) && $this->tokens[$i + 1] === $this->options[$name]) { + $isOption = true; + } + + continue; + } + + if ($isOption) { + $isOption = false; continue; } diff --git a/src/Symfony/Component/Console/Input/ArrayInput.php b/src/Symfony/Component/Console/Input/ArrayInput.php index cf09ff45ec..44c2f0d5c6 100644 --- a/src/Symfony/Component/Console/Input/ArrayInput.php +++ b/src/Symfony/Component/Console/Input/ArrayInput.php @@ -19,7 +19,7 @@ use Symfony\Component\Console\Exception\InvalidOptionException; * * Usage: * - * $input = new ArrayInput(['name' => 'foo', '--bar' => 'foobar']); + * $input = new ArrayInput(['command' => 'foo:bar', 'foo' => 'bar', '--bar' => 'foobar']); * * @author Fabien Potencier */ diff --git a/src/Symfony/Component/Console/Input/Input.php b/src/Symfony/Component/Console/Input/Input.php index 7a16e0ee4b..c1220316dc 100644 --- a/src/Symfony/Component/Console/Input/Input.php +++ b/src/Symfony/Component/Console/Input/Input.php @@ -69,7 +69,7 @@ abstract class Input implements InputInterface, StreamableInputInterface $givenArguments = $this->arguments; $missingArguments = array_filter(array_keys($definition->getArguments()), function ($argument) use ($definition, $givenArguments) { - return !array_key_exists($argument, $givenArguments) && $definition->getArgument($argument)->isRequired(); + return !\array_key_exists($argument, $givenArguments) && $definition->getArgument($argument)->isRequired(); }); if (\count($missingArguments) > 0) { @@ -150,7 +150,7 @@ abstract class Input implements InputInterface, StreamableInputInterface throw new InvalidArgumentException(sprintf('The "%s" option does not exist.', $name)); } - return array_key_exists($name, $this->options) ? $this->options[$name] : $this->definition->getOption($name)->getDefault(); + return \array_key_exists($name, $this->options) ? $this->options[$name] : $this->definition->getOption($name)->getDefault(); } /** diff --git a/src/Symfony/Component/Console/Input/InputDefinition.php b/src/Symfony/Component/Console/Input/InputDefinition.php index c7e5c987e5..2189c46282 100644 --- a/src/Symfony/Component/Console/Input/InputDefinition.php +++ b/src/Symfony/Component/Console/Input/InputDefinition.php @@ -338,8 +338,10 @@ class InputDefinition * @return string The InputOption name * * @throws InvalidArgumentException When option given does not exist + * + * @internal */ - private function shortcutToName($shortcut) + public function shortcutToName($shortcut) { if (!isset($this->shortcuts[$shortcut])) { throw new InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut)); diff --git a/src/Symfony/Component/Console/Tester/TesterTrait.php b/src/Symfony/Component/Console/Tester/TesterTrait.php index e5df56d835..7b5e128c49 100644 --- a/src/Symfony/Component/Console/Tester/TesterTrait.php +++ b/src/Symfony/Component/Console/Tester/TesterTrait.php @@ -126,7 +126,7 @@ trait TesterTrait */ private function initOutput(array $options) { - $this->captureStreamsIndependently = array_key_exists('capture_stderr_separately', $options) && $options['capture_stderr_separately']; + $this->captureStreamsIndependently = \array_key_exists('capture_stderr_separately', $options) && $options['capture_stderr_separately']; if (!$this->captureStreamsIndependently) { $this->output = new StreamOutput(fopen('php://memory', 'w', false)); if (isset($options['decorated'])) { diff --git a/src/Symfony/Component/Console/Tests/ApplicationTest.php b/src/Symfony/Component/Console/Tests/ApplicationTest.php index 2aaf9d7dae..e9b1be32a6 100644 --- a/src/Symfony/Component/Console/Tests/ApplicationTest.php +++ b/src/Symfony/Component/Console/Tests/ApplicationTest.php @@ -968,6 +968,19 @@ class ApplicationTest extends TestCase $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if -n is passed'); } + public function testRunWithGlobalOptionAndNoCommand() + { + $application = new Application(); + $application->setAutoExit(false); + $application->setCatchExceptions(false); + $application->getDefinition()->addOption(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)); + + $output = new StreamOutput(fopen('php://memory', 'w', false)); + $input = new ArgvInput(['cli.php', '--foo', 'bar']); + + $this->assertSame(0, $application->run($input, $output)); + } + /** * Issue #9285. * diff --git a/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php b/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php index 30f1f709d8..e3edbed029 100644 --- a/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php @@ -237,6 +237,43 @@ class QuestionHelperTest extends AbstractQuestionHelperTest $this->assertSame('b', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question)); } + public function getInputs() + { + return [ + ['$'], // 1 byte character + ['¢'], // 2 bytes character + ['€'], // 3 bytes character + ['𐍈'], // 4 bytes character + ]; + } + + /** + * @dataProvider getInputs + */ + public function testAskWithAutocompleteWithMultiByteCharacter($character) + { + if (!$this->hasSttyAvailable()) { + $this->markTestSkipped('`stty` is required to test autocomplete functionality'); + } + + $inputStream = $this->getInputStream("$character\n"); + + $possibleChoices = [ + '$' => '1 byte character', + '¢' => '2 bytes character', + '€' => '3 bytes character', + '𐍈' => '4 bytes character', + ]; + + $dialog = new QuestionHelper(); + $dialog->setHelperSet(new HelperSet([new FormatterHelper()])); + + $question = new ChoiceQuestion('Please select a character', $possibleChoices); + $question->setMaxAttempts(1); + + $this->assertSame($character, $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question)); + } + public function testAutocompleteWithTrailingBackslash() { if (!$this->hasSttyAvailable()) { diff --git a/src/Symfony/Component/Console/Tests/Input/ArgvInputTest.php b/src/Symfony/Component/Console/Tests/Input/ArgvInputTest.php index 37caaf2d1c..e20bcdd21b 100644 --- a/src/Symfony/Component/Console/Tests/Input/ArgvInputTest.php +++ b/src/Symfony/Component/Console/Tests/Input/ArgvInputTest.php @@ -312,6 +312,14 @@ class ArgvInputTest extends TestCase $input = new ArgvInput(['cli.php', '-fbbar', 'foo']); $this->assertEquals('foo', $input->getFirstArgument(), '->getFirstArgument() returns the first argument from the raw input'); + + $input = new ArgvInput(['cli.php', '--foo', 'fooval', 'bar']); + $input->bind(new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('arg')])); + $this->assertSame('bar', $input->getFirstArgument()); + + $input = new ArgvInput(['cli.php', '-bf', 'fooval', 'argval']); + $input->bind(new InputDefinition([new InputOption('bar', 'b', InputOption::VALUE_NONE), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('arg')])); + $this->assertSame('argval', $input->getFirstArgument()); } public function testHasParameterOption() diff --git a/src/Symfony/Component/Debug/ErrorHandler.php b/src/Symfony/Component/Debug/ErrorHandler.php index 083404fb09..2f250cba36 100644 --- a/src/Symfony/Component/Debug/ErrorHandler.php +++ b/src/Symfony/Component/Debug/ErrorHandler.php @@ -222,7 +222,7 @@ class ErrorHandler } if (!\is_array($log)) { $log = [$log]; - } elseif (!array_key_exists(0, $log)) { + } elseif (!\array_key_exists(0, $log)) { throw new \InvalidArgumentException('No logger provided'); } if (null === $log[0]) { diff --git a/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php b/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php index 33739eb276..d9d6e60f9e 100644 --- a/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php +++ b/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php @@ -44,7 +44,7 @@ class DebugClassLoaderTest extends TestCase $functions = spl_autoload_functions(); foreach ($functions as $function) { - if (is_array($function) && $function[0] instanceof DebugClassLoader) { + if (\is_array($function) && $function[0] instanceof DebugClassLoader) { $reflClass = new \ReflectionClass($function[0]); $reflProp = $reflClass->getProperty('classLoader'); $reflProp->setAccessible(true); @@ -205,7 +205,7 @@ class DebugClassLoaderTest extends TestCase require __DIR__.'/Fixtures/FinalClasses.php'; $i = 1; - while(class_exists($finalClass = __NAMESPACE__.'\\Fixtures\\FinalClass'.$i++, false)) { + while (class_exists($finalClass = __NAMESPACE__.'\\Fixtures\\FinalClass'.$i++, false)) { spl_autoload_call($finalClass); class_exists('Test\\'.__NAMESPACE__.'\\Extends'.substr($finalClass, strrpos($finalClass, '\\') + 1), true); } @@ -371,7 +371,7 @@ class ClassLoader public function findFile($class) { - $fixtureDir = __DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR; + $fixtureDir = __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR; if (__NAMESPACE__.'\TestingUnsilencing' === $class) { eval('-- parse error --'); @@ -380,7 +380,7 @@ class ClassLoader } elseif (__NAMESPACE__.'\TestingCaseMismatch' === $class) { eval('namespace '.__NAMESPACE__.'; class TestingCaseMisMatch {}'); } elseif (__NAMESPACE__.'\Fixtures\Psr4CaseMismatch' === $class) { - return $fixtureDir.'psr4'.DIRECTORY_SEPARATOR.'Psr4CaseMismatch.php'; + return $fixtureDir.'psr4'.\DIRECTORY_SEPARATOR.'Psr4CaseMismatch.php'; } elseif (__NAMESPACE__.'\Fixtures\NotPSR0' === $class) { return $fixtureDir.'reallyNotPsr0.php'; } elseif (__NAMESPACE__.'\Fixtures\NotPSR0bis' === $class) { diff --git a/src/Symfony/Component/DependencyInjection/ChildDefinition.php b/src/Symfony/Component/DependencyInjection/ChildDefinition.php index 095beaec72..f80fa3e8e3 100644 --- a/src/Symfony/Component/DependencyInjection/ChildDefinition.php +++ b/src/Symfony/Component/DependencyInjection/ChildDefinition.php @@ -71,7 +71,7 @@ class ChildDefinition extends Definition */ public function getArgument($index) { - if (array_key_exists('index_'.$index, $this->arguments)) { + if (\array_key_exists('index_'.$index, $this->arguments)) { return $this->arguments['index_'.$index]; } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php b/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php index 57614119fc..5aa6680e7e 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php @@ -188,7 +188,7 @@ class AutowirePass extends AbstractRecursivePass } foreach ($parameters as $index => $parameter) { - if (array_key_exists($index, $arguments) && '' !== $arguments[$index]) { + if (\array_key_exists($index, $arguments) && '' !== $arguments[$index]) { continue; } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RegisterServiceSubscribersPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RegisterServiceSubscribersPass.php index 8c34ce4182..aeb9641811 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RegisterServiceSubscribersPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RegisterServiceSubscribersPass.php @@ -43,10 +43,10 @@ class RegisterServiceSubscribersPass extends AbstractRecursivePass if ([] !== array_diff(array_keys($attributes), ['id', 'key'])) { throw new InvalidArgumentException(sprintf('The "container.service_subscriber" tag accepts only the "key" and "id" attributes, "%s" given for service "%s".', implode('", "', array_keys($attributes)), $this->currentId)); } - if (!array_key_exists('id', $attributes)) { + if (!\array_key_exists('id', $attributes)) { throw new InvalidArgumentException(sprintf('Missing "id" attribute on "container.service_subscriber" tag with key="%s" for service "%s".', $attributes['key'], $this->currentId)); } - if (!array_key_exists('key', $attributes)) { + if (!\array_key_exists('key', $attributes)) { $attributes['key'] = $attributes['id']; } if (isset($serviceMap[$attributes['key']])) { diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ResolveBindingsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ResolveBindingsPass.php index cf7d96fceb..2238779a25 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ResolveBindingsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ResolveBindingsPass.php @@ -119,19 +119,19 @@ class ResolveBindingsPass extends AbstractRecursivePass } foreach ($reflectionMethod->getParameters() as $key => $parameter) { - if (array_key_exists($key, $arguments) && '' !== $arguments[$key]) { + if (\array_key_exists($key, $arguments) && '' !== $arguments[$key]) { continue; } $typeHint = ProxyHelper::getTypeHint($reflectionMethod, $parameter); - if (array_key_exists($k = ltrim($typeHint, '\\').' $'.$parameter->name, $bindings)) { + if (\array_key_exists($k = ltrim($typeHint, '\\').' $'.$parameter->name, $bindings)) { $arguments[$key] = $this->getBindingValue($bindings[$k]); continue; } - if (array_key_exists('$'.$parameter->name, $bindings)) { + if (\array_key_exists('$'.$parameter->name, $bindings)) { $arguments[$key] = $this->getBindingValue($bindings['$'.$parameter->name]); continue; diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ResolveNamedArgumentsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ResolveNamedArgumentsPass.php index 70f2556df5..771c8f7b38 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ResolveNamedArgumentsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ResolveNamedArgumentsPass.php @@ -77,7 +77,7 @@ class ResolveNamedArgumentsPass extends AbstractRecursivePass $typeFound = false; foreach ($parameters as $j => $p) { - if (!array_key_exists($j, $resolvedArguments) && ProxyHelper::getTypeHint($r, $p, true) === $key) { + if (!\array_key_exists($j, $resolvedArguments) && ProxyHelper::getTypeHint($r, $p, true) === $key) { $resolvedArguments[$j] = $argument; $typeFound = true; } diff --git a/src/Symfony/Component/DependencyInjection/Container.php b/src/Symfony/Component/DependencyInjection/Container.php index 938c0a8e3c..f1bafe9812 100644 --- a/src/Symfony/Component/DependencyInjection/Container.php +++ b/src/Symfony/Component/DependencyInjection/Container.php @@ -385,7 +385,7 @@ class Container implements ResettableContainerInterface if (isset($this->resolving[$envName = "env($name)"])) { throw new ParameterCircularReferenceException(array_keys($this->resolving)); } - if (isset($this->envCache[$name]) || array_key_exists($name, $this->envCache)) { + if (isset($this->envCache[$name]) || \array_key_exists($name, $this->envCache)) { return $this->envCache[$name]; } if (!$this->has($id = 'container.env_var_processors_locator')) { diff --git a/src/Symfony/Component/DependencyInjection/Definition.php b/src/Symfony/Component/DependencyInjection/Definition.php index 195e2dac68..b79a8c9a82 100644 --- a/src/Symfony/Component/DependencyInjection/Definition.php +++ b/src/Symfony/Component/DependencyInjection/Definition.php @@ -269,7 +269,7 @@ class Definition throw new OutOfBoundsException(sprintf('The index "%d" is not in the range [0, %d].', $index, \count($this->arguments) - 1)); } - if (!array_key_exists($index, $this->arguments)) { + if (!\array_key_exists($index, $this->arguments)) { throw new OutOfBoundsException(sprintf('The argument "%s" doesn\'t exist.', $index)); } @@ -314,7 +314,7 @@ class Definition */ public function getArgument($index) { - if (!array_key_exists($index, $this->arguments)) { + if (!\array_key_exists($index, $this->arguments)) { throw new OutOfBoundsException(sprintf('The argument "%s" doesn\'t exist.', $index)); } diff --git a/src/Symfony/Component/DependencyInjection/Dumper/GraphvizDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/GraphvizDumper.php index b1a9016b0f..08c3e306fb 100644 --- a/src/Symfony/Component/DependencyInjection/Dumper/GraphvizDumper.php +++ b/src/Symfony/Component/DependencyInjection/Dumper/GraphvizDumper.php @@ -171,7 +171,7 @@ class GraphvizDumper extends Dumper } foreach ($container->getServiceIds() as $id) { - if (array_key_exists($id, $container->getAliases())) { + if (\array_key_exists($id, $container->getAliases())) { continue; } diff --git a/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php b/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php index da4e2d9f7a..137fc97798 100644 --- a/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php +++ b/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php @@ -69,7 +69,7 @@ class EnvVarProcessor implements EnvVarProcessorInterface throw new RuntimeException(sprintf('Resolved value of "%s" did not result in an array value.', $next)); } - if (!isset($array[$key]) && !array_key_exists($key, $array)) { + if (!isset($array[$key]) && !\array_key_exists($key, $array)) { throw new EnvNotFoundException(sprintf('Key "%s" not found in "%s" (resolved from "%s").', $key, json_encode($array), $next)); } diff --git a/src/Symfony/Component/DependencyInjection/Extension/Extension.php b/src/Symfony/Component/DependencyInjection/Extension/Extension.php index 25d07ff83b..1285334f58 100644 --- a/src/Symfony/Component/DependencyInjection/Extension/Extension.php +++ b/src/Symfony/Component/DependencyInjection/Extension/Extension.php @@ -127,7 +127,7 @@ abstract class Extension implements ExtensionInterface, ConfigurationExtensionIn */ protected function isConfigEnabled(ContainerBuilder $container, array $config) { - if (!array_key_exists('enabled', $config)) { + if (!\array_key_exists('enabled', $config)) { throw new InvalidArgumentException("The config array has no 'enabled' key."); } diff --git a/src/Symfony/Component/DependencyInjection/LazyProxy/Instantiator/RealServiceInstantiator.php b/src/Symfony/Component/DependencyInjection/LazyProxy/Instantiator/RealServiceInstantiator.php index 4d6a9f05a9..2e36704080 100644 --- a/src/Symfony/Component/DependencyInjection/LazyProxy/Instantiator/RealServiceInstantiator.php +++ b/src/Symfony/Component/DependencyInjection/LazyProxy/Instantiator/RealServiceInstantiator.php @@ -17,7 +17,7 @@ use Symfony\Component\DependencyInjection\Definition; /** * {@inheritdoc} * - * Noop proxy instantiator - simply produces the real service instead of a proxy instance. + * Noop proxy instantiator - produces the real service instead of a proxy instance. * * @author Marco Pivetta */ diff --git a/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php b/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php index 84170577fc..988dbf88cc 100644 --- a/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php +++ b/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php @@ -68,7 +68,7 @@ class ParameterBag implements ParameterBagInterface { $name = (string) $name; - if (!array_key_exists($name, $this->parameters)) { + if (!\array_key_exists($name, $this->parameters)) { if (!$name) { throw new ParameterNotFoundException($name); } @@ -119,7 +119,7 @@ class ParameterBag implements ParameterBagInterface */ public function has($name) { - return array_key_exists((string) $name, $this->parameters); + return \array_key_exists((string) $name, $this->parameters); } /** diff --git a/src/Symfony/Component/DomCrawler/Crawler.php b/src/Symfony/Component/DomCrawler/Crawler.php index c629d8d041..760d3df388 100644 --- a/src/Symfony/Component/DomCrawler/Crawler.php +++ b/src/Symfony/Component/DomCrawler/Crawler.php @@ -985,7 +985,7 @@ class Crawler implements \Countable, \IteratorAggregate $expressions = []; // An expression which will never match to replace expressions which cannot match in the crawler - // We cannot simply drop + // We cannot drop $nonMatchingExpression = 'a[name() = "b"]'; $xpathLen = \strlen($xpath); diff --git a/src/Symfony/Component/DomCrawler/Field/FileFormField.php b/src/Symfony/Component/DomCrawler/Field/FileFormField.php index af9c6e6f25..9e21c9c4b9 100644 --- a/src/Symfony/Component/DomCrawler/Field/FileFormField.php +++ b/src/Symfony/Component/DomCrawler/Field/FileFormField.php @@ -60,7 +60,7 @@ class FileFormField extends FormField // copy to a tmp location $tmp = sys_get_temp_dir().'/'.strtr(substr(base64_encode(hash('sha256', uniqid(mt_rand(), true), true)), 0, 7), '/', '_'); - if (array_key_exists('extension', $info)) { + if (\array_key_exists('extension', $info)) { $tmp .= '.'.$info['extension']; } if (is_file($tmp)) { diff --git a/src/Symfony/Component/DomCrawler/FormFieldRegistry.php b/src/Symfony/Component/DomCrawler/FormFieldRegistry.php index 10c7e8cb36..8f432cfbbb 100644 --- a/src/Symfony/Component/DomCrawler/FormFieldRegistry.php +++ b/src/Symfony/Component/DomCrawler/FormFieldRegistry.php @@ -57,7 +57,7 @@ class FormFieldRegistry $target = &$this->fields; while (\count($segments) > 1) { $path = array_shift($segments); - if (!array_key_exists($path, $target)) { + if (!\array_key_exists($path, $target)) { return; } $target = &$target[$path]; @@ -80,7 +80,7 @@ class FormFieldRegistry $target = &$this->fields; while ($segments) { $path = array_shift($segments); - if (!array_key_exists($path, $target)) { + if (!\array_key_exists($path, $target)) { throw new \InvalidArgumentException(sprintf('Unreachable field "%s"', $path)); } $target = &$target[$path]; diff --git a/src/Symfony/Component/EventDispatcher/Debug/WrappedListener.php b/src/Symfony/Component/EventDispatcher/Debug/WrappedListener.php index 8b3f64a119..8aa3f80a76 100644 --- a/src/Symfony/Component/EventDispatcher/Debug/WrappedListener.php +++ b/src/Symfony/Component/EventDispatcher/Debug/WrappedListener.php @@ -30,6 +30,7 @@ class WrappedListener private $dispatcher; private $pretty; private $stub; + private $priority; private static $hasClassStub; public function __construct(callable $listener, ?string $name, Stopwatch $stopwatch, EventDispatcherInterface $dispatcher = null) @@ -98,7 +99,7 @@ class WrappedListener return [ 'event' => $eventName, - 'priority' => null !== $this->dispatcher ? $this->dispatcher->getListenerPriority($eventName, $this->listener) : null, + 'priority' => null !== $this->priority ? $this->priority : (null !== $this->dispatcher ? $this->dispatcher->getListenerPriority($eventName, $this->listener) : null), 'pretty' => $this->pretty, 'stub' => $this->stub, ]; @@ -106,11 +107,14 @@ class WrappedListener public function __invoke(Event $event, $eventName, EventDispatcherInterface $dispatcher) { + $dispatcher = $this->dispatcher ?: $dispatcher; + $this->called = true; + $this->priority = $dispatcher->getListenerPriority($eventName, $this->listener); $e = $this->stopwatch->start($this->name, 'event_listener'); - ($this->optimizedListener)($event, $eventName, $this->dispatcher ?: $dispatcher); + ($this->optimizedListener)($event, $eventName, $dispatcher); if ($e->isStarted()) { $e->stop(); diff --git a/src/Symfony/Component/EventDispatcher/GenericEvent.php b/src/Symfony/Component/EventDispatcher/GenericEvent.php index a9a0a5dfa5..f005e3a3db 100644 --- a/src/Symfony/Component/EventDispatcher/GenericEvent.php +++ b/src/Symfony/Component/EventDispatcher/GenericEvent.php @@ -111,7 +111,7 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate */ public function hasArgument($key) { - return array_key_exists($key, $this->arguments); + return \array_key_exists($key, $this->arguments); } /** diff --git a/src/Symfony/Component/Finder/Finder.php b/src/Symfony/Component/Finder/Finder.php index ab8f92b366..83163f51d5 100644 --- a/src/Symfony/Component/Finder/Finder.php +++ b/src/Symfony/Component/Finder/Finder.php @@ -29,7 +29,7 @@ use Symfony\Component\Finder\Iterator\SortableIterator; * * All rules may be invoked several times. * - * All methods return the current Finder object to allow easy chaining: + * All methods return the current Finder object to allow chaining: * * $finder = Finder::create()->files()->name('*.php')->in(__DIR__); * @@ -674,12 +674,15 @@ class Finder implements \IteratorAggregate, \Countable private function searchInDirectory(string $dir): \Iterator { + $exclude = $this->exclude; + $notPaths = $this->notPaths; + if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) { - $this->exclude = array_merge($this->exclude, self::$vcsPatterns); + $exclude = array_merge($exclude, self::$vcsPatterns); } if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) { - $this->notPaths[] = '#(^|/)\..+(/|$)#'; + $notPaths[] = '#(^|/)\..+(/|$)#'; } $minDepth = 0; @@ -712,8 +715,8 @@ class Finder implements \IteratorAggregate, \Countable $iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs); - if ($this->exclude) { - $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude); + if ($exclude) { + $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $exclude); } $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST); @@ -746,8 +749,8 @@ class Finder implements \IteratorAggregate, \Countable $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters); } - if ($this->paths || $this->notPaths) { - $iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $this->notPaths); + if ($this->paths || $notPaths) { + $iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $notPaths); } if ($this->sort || $this->reverseSorting) { diff --git a/src/Symfony/Component/Finder/Tests/FinderTest.php b/src/Symfony/Component/Finder/Tests/FinderTest.php index 1b50663e9f..ddff250287 100644 --- a/src/Symfony/Component/Finder/Tests/FinderTest.php +++ b/src/Symfony/Component/Finder/Tests/FinderTest.php @@ -421,6 +421,18 @@ class FinderTest extends Iterator\RealIteratorTestCase ]), $finder->in(self::$tmpDir)->getIterator()); } + public function testIgnoreVCSCanBeDisabledAfterFirstIteration() + { + $finder = $this->buildFinder(); + $finder->in(self::$tmpDir); + $finder->ignoreDotFiles(false); + + $this->assertIterator($this->toAbsolute(['foo', 'foo/bar.tmp', 'test.php', 'test.py', 'toto', '.bar', '.foo', '.foo/.bar', '.foo/bar', 'foo bar']), $finder->getIterator()); + + $finder->ignoreVCS(false); + $this->assertIterator($this->toAbsolute(['.git', 'foo', 'foo/bar.tmp', 'test.php', 'test.py', 'toto', 'toto/.git', '.bar', '.foo', '.foo/.bar', '.foo/bar', 'foo bar']), $finder->getIterator()); + } + public function testIgnoreDotFiles() { $finder = $this->buildFinder(); @@ -496,6 +508,17 @@ class FinderTest extends Iterator\RealIteratorTestCase ]), $finder->in(self::$tmpDir)->getIterator()); } + public function testIgnoreDotFilesCanBeDisabledAfterFirstIteration() + { + $finder = $this->buildFinder(); + $finder->in(self::$tmpDir); + + $this->assertIterator($this->toAbsolute(['foo', 'foo/bar.tmp', 'test.php', 'test.py', 'toto', 'foo bar']), $finder->getIterator()); + + $finder->ignoreDotFiles(false); + $this->assertIterator($this->toAbsolute(['foo', 'foo/bar.tmp', 'test.php', 'test.py', 'toto', '.bar', '.foo', '.foo/.bar', '.foo/bar', 'foo bar']), $finder->getIterator()); + } + public function testSortByName() { $finder = $this->buildFinder(); diff --git a/src/Symfony/Component/Form/ButtonBuilder.php b/src/Symfony/Component/Form/ButtonBuilder.php index 38377db30f..d5db836df3 100644 --- a/src/Symfony/Component/Form/ButtonBuilder.php +++ b/src/Symfony/Component/Form/ButtonBuilder.php @@ -670,7 +670,7 @@ class ButtonBuilder implements \IteratorAggregate, FormBuilderInterface */ public function hasAttribute($name) { - return array_key_exists($name, $this->attributes); + return \array_key_exists($name, $this->attributes); } /** @@ -683,7 +683,7 @@ class ButtonBuilder implements \IteratorAggregate, FormBuilderInterface */ public function getAttribute($name, $default = null) { - return array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; + return \array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; } /** @@ -777,7 +777,7 @@ class ButtonBuilder implements \IteratorAggregate, FormBuilderInterface */ public function hasOption($name) { - return array_key_exists($name, $this->options); + return \array_key_exists($name, $this->options); } /** @@ -790,7 +790,7 @@ class ButtonBuilder implements \IteratorAggregate, FormBuilderInterface */ public function getOption($name, $default = null) { - return array_key_exists($name, $this->options) ? $this->options[$name] : $default; + return \array_key_exists($name, $this->options) ? $this->options[$name] : $default; } /** diff --git a/src/Symfony/Component/Form/ChoiceList/ArrayChoiceList.php b/src/Symfony/Component/Form/ChoiceList/ArrayChoiceList.php index b24f32a8cd..a3150d275f 100644 --- a/src/Symfony/Component/Form/ChoiceList/ArrayChoiceList.php +++ b/src/Symfony/Component/Form/ChoiceList/ArrayChoiceList.php @@ -78,7 +78,7 @@ class ArrayChoiceList implements ChoiceListInterface // If a deterministic value generator was passed, use it later $this->valueCallback = $value; } else { - // Otherwise simply generate incrementing integers as values + // Otherwise generate incrementing integers as values $i = 0; $value = function () use (&$i) { return $i++; @@ -135,7 +135,7 @@ class ArrayChoiceList implements ChoiceListInterface $choices = []; foreach ($values as $i => $givenValue) { - if (array_key_exists($givenValue, $this->choices)) { + if (\array_key_exists($givenValue, $this->choices)) { $choices[$i] = $this->choices[$givenValue]; } } diff --git a/src/Symfony/Component/Form/ChoiceList/LazyChoiceList.php b/src/Symfony/Component/Form/ChoiceList/LazyChoiceList.php index 30cc97551c..b1a671d0c6 100644 --- a/src/Symfony/Component/Form/ChoiceList/LazyChoiceList.php +++ b/src/Symfony/Component/Form/ChoiceList/LazyChoiceList.php @@ -32,7 +32,7 @@ class LazyChoiceList implements ChoiceListInterface /** * The callable creating string values for each choice. * - * If null, choices are simply cast to strings. + * If null, choices are cast to strings. * * @var callable|null */ diff --git a/src/Symfony/Component/Form/Console/Descriptor/JsonDescriptor.php b/src/Symfony/Component/Form/Console/Descriptor/JsonDescriptor.php index 31d9aa485e..18a288b444 100644 --- a/src/Symfony/Component/Form/Console/Descriptor/JsonDescriptor.php +++ b/src/Symfony/Component/Form/Console/Descriptor/JsonDescriptor.php @@ -79,7 +79,7 @@ class JsonDescriptor extends Descriptor 'allowed_values' => 'allowedValues', ]; foreach ($map as $label => $name) { - if (array_key_exists($name, $definition)) { + if (\array_key_exists($name, $definition)) { $data[$label] = $definition[$name]; if ('default' === $name) { diff --git a/src/Symfony/Component/Form/Console/Descriptor/TextDescriptor.php b/src/Symfony/Component/Form/Console/Descriptor/TextDescriptor.php index 70ee44520e..90dd8f1dfe 100644 --- a/src/Symfony/Component/Form/Console/Descriptor/TextDescriptor.php +++ b/src/Symfony/Component/Form/Console/Descriptor/TextDescriptor.php @@ -114,7 +114,7 @@ class TextDescriptor extends Descriptor ]; $rows = []; foreach ($map as $label => $name) { - $value = array_key_exists($name, $definition) ? $dump($definition[$name]) : '-'; + $value = \array_key_exists($name, $definition) ? $dump($definition[$name]) : '-'; if ('default' === $name && isset($definition['lazy'])) { $value = "Value: $value\n\nClosure(s): ".$dump($definition['lazy']); } diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php index 48aa9978e6..392aa49e51 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php @@ -11,6 +11,8 @@ namespace Symfony\Component\Form\Extension\Core\DataTransformer; +use Symfony\Component\Form\Exception\TransformationFailedException; + /** * Transforms between an integer and a localized number with grouping * (each thousand) and comma separators. @@ -42,6 +44,12 @@ class IntegerToLocalizedStringTransformer extends NumberToLocalizedStringTransfo */ public function reverseTransform($value) { + $decimalSeparator = $this->getNumberFormatter()->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL); + + if (\is_string($value) && false !== strpos($value, $decimalSeparator)) { + throw new TransformationFailedException(sprintf('The value "%s" is not a valid integer.', $value)); + } + $result = parent::reverseTransform($value); return null !== $result ? (int) $result : null; diff --git a/src/Symfony/Component/Form/Extension/Core/Type/FormType.php b/src/Symfony/Component/Form/Extension/Core/Type/FormType.php index 208d44f5fa..a2bec36949 100644 --- a/src/Symfony/Component/Form/Extension/Core/Type/FormType.php +++ b/src/Symfony/Component/Form/Extension/Core/Type/FormType.php @@ -38,7 +38,7 @@ class FormType extends BaseType { parent::buildForm($builder, $options); - $isDataOptionSet = array_key_exists('data', $options); + $isDataOptionSet = \array_key_exists('data', $options); $builder ->setRequired($options['required']) diff --git a/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php b/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php index 19fac82957..db96bc731b 100644 --- a/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php +++ b/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php @@ -41,7 +41,7 @@ class FormValidator extends ConstraintValidator $validator = $this->context->getValidator()->inContext($this->context); - if ($form->isSynchronized()) { + if ($form->isSubmitted() && $form->isSynchronized()) { // Validate the form data only if transformation succeeded $groups = self::getValidationGroups($form); $data = $form->getData(); @@ -90,7 +90,7 @@ class FormValidator extends ConstraintValidator } } } - } else { + } elseif (!$form->isSynchronized()) { $childrenSynchronized = true; /** @var FormInterface $child */ diff --git a/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapper.php b/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapper.php index 86a77044d1..659c266ce6 100644 --- a/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapper.php +++ b/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapper.php @@ -273,9 +273,6 @@ class ViolationMapper implements ViolationMapperInterface */ private function acceptsErrors(FormInterface $form) { - // Ignore non-submitted forms. This happens, for example, in PATCH - // requests. - // https://github.com/symfony/symfony/pull/10567 - return $form->isSubmitted() && ($this->allowNonSynchronized || $form->isSynchronized()); + return $this->allowNonSynchronized || $form->isSynchronized(); } } diff --git a/src/Symfony/Component/Form/Form.php b/src/Symfony/Component/Form/Form.php index fb0ba683e8..17ecfd6f47 100644 --- a/src/Symfony/Component/Form/Form.php +++ b/src/Symfony/Component/Form/Form.php @@ -42,9 +42,9 @@ use Symfony\Component\PropertyAccess\PropertyPath; * * In most cases, format (1) and format (2) will be the same. For example, * a checkbox field uses a Boolean value for both internal processing and - * storage in the object. In these cases you simply need to set a view - * transformer to convert between formats (2) and (3). You can do this by - * calling addViewTransformer(). + * storage in the object. In these cases you need to set a view transformer + * to convert between formats (2) and (3). You can do this by calling + * addViewTransformer(). * * In some cases though it makes sense to make format (1) configurable. To * demonstrate this, let's extend our above date field to store the value @@ -574,7 +574,7 @@ class Form implements \IteratorAggregate, FormInterface, ClearableErrorsInterfac } foreach ($this->children as $name => $child) { - $isSubmitted = array_key_exists($name, $submittedData); + $isSubmitted = \array_key_exists($name, $submittedData); if ($isSubmitted || $clearMissing) { $child->submit($isSubmitted ? $submittedData[$name] : null, $clearMissing); diff --git a/src/Symfony/Component/Form/FormConfigBuilder.php b/src/Symfony/Component/Form/FormConfigBuilder.php index 344751b159..1a581d9b8e 100644 --- a/src/Symfony/Component/Form/FormConfigBuilder.php +++ b/src/Symfony/Component/Form/FormConfigBuilder.php @@ -418,7 +418,7 @@ class FormConfigBuilder implements FormConfigBuilderInterface */ public function hasAttribute($name) { - return array_key_exists($name, $this->attributes); + return \array_key_exists($name, $this->attributes); } /** @@ -426,7 +426,7 @@ class FormConfigBuilder implements FormConfigBuilderInterface */ public function getAttribute($name, $default = null) { - return array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; + return \array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; } /** @@ -513,7 +513,7 @@ class FormConfigBuilder implements FormConfigBuilderInterface */ public function hasOption($name) { - return array_key_exists($name, $this->options); + return \array_key_exists($name, $this->options); } /** @@ -521,7 +521,7 @@ class FormConfigBuilder implements FormConfigBuilderInterface */ public function getOption($name, $default = null) { - return array_key_exists($name, $this->options) ? $this->options[$name] : $default; + return \array_key_exists($name, $this->options) ? $this->options[$name] : $default; } /** diff --git a/src/Symfony/Component/Form/FormFactory.php b/src/Symfony/Component/Form/FormFactory.php index d474d5903f..b397f9a21f 100644 --- a/src/Symfony/Component/Form/FormFactory.php +++ b/src/Symfony/Component/Form/FormFactory.php @@ -63,7 +63,7 @@ class FormFactory implements FormFactoryInterface */ public function createNamedBuilder($name, $type = 'Symfony\Component\Form\Extension\Core\Type\FormType', $data = null, array $options = []) { - if (null !== $data && !array_key_exists('data', $options)) { + if (null !== $data && !\array_key_exists('data', $options)) { $options['data'] = $data; } diff --git a/src/Symfony/Component/Form/FormRenderer.php b/src/Symfony/Component/Form/FormRenderer.php index 4b3866fe1c..91e6faa9cc 100644 --- a/src/Symfony/Component/Form/FormRenderer.php +++ b/src/Symfony/Component/Form/FormRenderer.php @@ -165,7 +165,7 @@ class FormRenderer implements FormRendererInterface // "form_widget" in this example (again, no matter in which theme). // If the designer wants to explicitly fallback to "form_widget" in their // custom "choice_widget", for example because they only want to wrap - // a
around the original implementation, they can simply call the + // a
around the original implementation, they can call the // widget() function again to render the block for the parent type. // // The second kind is implemented in the following blocks. diff --git a/src/Symfony/Component/Form/NativeRequestHandler.php b/src/Symfony/Component/Form/NativeRequestHandler.php index b9b4b64b21..cfccf180b9 100644 --- a/src/Symfony/Component/Form/NativeRequestHandler.php +++ b/src/Symfony/Component/Form/NativeRequestHandler.php @@ -94,10 +94,10 @@ class NativeRequestHandler implements RequestHandlerInterface if ('' === $name) { $params = $_POST; $files = $fixedFiles; - } elseif (array_key_exists($name, $_POST) || array_key_exists($name, $fixedFiles)) { + } elseif (\array_key_exists($name, $_POST) || \array_key_exists($name, $fixedFiles)) { $default = $form->getConfig()->getCompound() ? [] : null; - $params = array_key_exists($name, $_POST) ? $_POST[$name] : $default; - $files = array_key_exists($name, $fixedFiles) ? $fixedFiles[$name] : $default; + $params = \array_key_exists($name, $_POST) ? $_POST[$name] : $default; + $files = \array_key_exists($name, $fixedFiles) ? $fixedFiles[$name] : $default; } else { // Don't submit the form if it is not present in the request return; @@ -115,7 +115,7 @@ class NativeRequestHandler implements RequestHandlerInterface return; } - if (\is_array($data) && array_key_exists('_method', $data) && $method === $data['_method'] && !$form->has('_method')) { + if (\is_array($data) && \array_key_exists('_method', $data) && $method === $data['_method'] && !$form->has('_method')) { unset($data['_method']); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php index 8d54b064f8..3b1426dfa7 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php @@ -107,9 +107,7 @@ class IntegerToLocalizedStringTransformerTest extends TestCase $transformer = new IntegerToLocalizedStringTransformer(); $this->assertEquals(1, $transformer->reverseTransform('1')); - $this->assertEquals(1, $transformer->reverseTransform('1,5')); - $this->assertEquals(1234, $transformer->reverseTransform('1234,5')); - $this->assertEquals(12345, $transformer->reverseTransform('12345,912')); + $this->assertEquals(12345, $transformer->reverseTransform('12345')); } public function testReverseTransformEmpty() @@ -147,10 +145,10 @@ class IntegerToLocalizedStringTransformerTest extends TestCase $transformer = new IntegerToLocalizedStringTransformer(null, true); - $this->assertEquals(1234, $transformer->reverseTransform('1.234,5')); - $this->assertEquals(12345, $transformer->reverseTransform('12.345,912')); - $this->assertEquals(1234, $transformer->reverseTransform('1234,5')); - $this->assertEquals(12345, $transformer->reverseTransform('12345,912')); + $this->assertEquals(1234, $transformer->reverseTransform('1.234')); + $this->assertEquals(12345, $transformer->reverseTransform('12.345')); + $this->assertEquals(1234, $transformer->reverseTransform('1234')); + $this->assertEquals(12345, $transformer->reverseTransform('12345')); } public function reverseTransformWithRoundingProvider() @@ -246,6 +244,29 @@ class IntegerToLocalizedStringTransformerTest extends TestCase $transformer->reverseTransform('foo'); } + /** + * @dataProvider floatNumberProvider + * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException + */ + public function testReverseTransformExpectsInteger($number, $locale) + { + IntlTestHelper::requireFullIntl($this, false); + + \Locale::setDefault($locale); + + $transformer = new IntegerToLocalizedStringTransformer(); + + $transformer->reverseTransform($number); + } + + public function floatNumberProvider() + { + return [ + ['12345.912', 'en'], + ['1.234,5', 'de_DE'], + ]; + } + /** * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException */ diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/IntegerTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/IntegerTypeTest.php index 5a9d195f27..c5c7dd9161 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/IntegerTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/IntegerTypeTest.php @@ -24,14 +24,15 @@ class IntegerTypeTest extends BaseTypeTest parent::setUp(); } - public function testSubmitCastsToInteger() + public function testSubmitRejectsFloats() { $form = $this->factory->create(static::TESTED_TYPE); $form->submit('1.678'); - $this->assertSame(1, $form->getData()); - $this->assertSame('1', $form->getViewData()); + $this->assertTrue($form->isSubmitted()); + $this->assertFalse($form->isValid()); + $this->assertFalse($form->isSynchronized()); } public function testSubmitNull($expected = null, $norm = null, $view = null) diff --git a/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php b/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php index a342ab21fa..9a8b5c259e 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php @@ -61,9 +61,8 @@ class FormValidatorTest extends ConstraintValidatorTestCase { $object = new \stdClass(); $options = ['validation_groups' => ['group1', 'group2']]; - $form = $this->getBuilder('name', '\stdClass', $options) - ->setData($object) - ->getForm(); + $form = $this->getCompoundForm($object, $options); + $form->submit([]); $this->expectValidateAt(0, 'data', $object, ['group1', 'group2']); @@ -82,9 +81,8 @@ class FormValidatorTest extends ConstraintValidatorTestCase 'validation_groups' => ['group1', 'group2'], 'constraints' => [$constraint1, $constraint2], ]; - $form = $this->getBuilder('name', '\stdClass', $options) - ->setData($object) - ->getForm(); + $form = $this->getCompoundForm($object, $options); + $form->submit([]); // First default constraints $this->expectValidateAt(0, 'data', $object, ['group1', 'group2']); @@ -110,10 +108,9 @@ class FormValidatorTest extends ConstraintValidatorTestCase 'validation_groups' => ['group1', 'group2'], 'constraints' => [new Valid()], ]; - $form = $this->getBuilder('name', '\stdClass', $options)->getForm(); + $form = $this->getCompoundForm($object, $options); $parent->add($form); - - $form->setData($object); + $parent->submit([]); $this->expectValidateAt(0, 'data', $object, ['group1', 'group2']); @@ -146,8 +143,8 @@ class FormValidatorTest extends ConstraintValidatorTestCase public function testMissingConstraintIndex() { $object = new \stdClass(); - $form = new FormBuilder('name', '\stdClass', $this->dispatcher, $this->factory); - $form = $form->setData($object)->getForm(); + $form = $this->getCompoundForm($object); + $form->submit([]); $this->expectValidateAt(0, 'data', $object, ['Default']); @@ -170,10 +167,9 @@ class FormValidatorTest extends ConstraintValidatorTestCase 'validation_groups' => ['group1', 'group2'], 'constraints' => [$constraint1, $constraint2], ]; - $form = $this->getBuilder('name', '\stdClass', $options) - ->setData($object) - ->getForm(); + $form = $this->getCompoundForm($object, $options); $parent->add($form); + $parent->submit([]); $this->expectValidateValueAt(0, 'data', $object, $constraint1, 'group1'); $this->expectValidateValueAt(1, 'data', $object, $constraint2, 'group2'); @@ -361,9 +357,8 @@ class FormValidatorTest extends ConstraintValidatorTestCase { $object = new \stdClass(); $options = ['validation_groups' => new GroupSequence(['group1', 'group2'])]; - $form = $this->getBuilder('name', '\stdClass', $options) - ->setData($object) - ->getForm(); + $form = $this->getCompoundForm($object, $options); + $form->submit([]); $this->expectValidateAt(0, 'data', $object, new GroupSequence(['group1', 'group2'])); $this->expectValidateAt(1, 'data', $object, new GroupSequence(['group1', 'group2'])); @@ -377,9 +372,8 @@ class FormValidatorTest extends ConstraintValidatorTestCase { $object = new \stdClass(); $options = ['validation_groups' => [$this, 'getValidationGroups']]; - $form = $this->getBuilder('name', '\stdClass', $options) - ->setData($object) - ->getForm(); + $form = $this->getCompoundForm($object, $options); + $form->submit([]); $this->expectValidateAt(0, 'data', $object, ['group1', 'group2']); @@ -392,9 +386,8 @@ class FormValidatorTest extends ConstraintValidatorTestCase { $object = new \stdClass(); $options = ['validation_groups' => 'header']; - $form = $this->getBuilder('name', '\stdClass', $options) - ->setData($object) - ->getForm(); + $form = $this->getCompoundForm($object, $options); + $form->submit([]); $this->expectValidateAt(0, 'data', $object, ['header']); @@ -409,9 +402,8 @@ class FormValidatorTest extends ConstraintValidatorTestCase $options = ['validation_groups' => function (FormInterface $form) { return ['group1', 'group2']; }]; - $form = $this->getBuilder('name', '\stdClass', $options) - ->setData($object) - ->getForm(); + $form = $this->getCompoundForm($object, $options); + $form->submit([]); $this->expectValidateAt(0, 'data', $object, ['group1', 'group2']); @@ -455,7 +447,7 @@ class FormValidatorTest extends ConstraintValidatorTestCase ->setCompound(true) ->setDataMapper(new PropertyPathMapper()) ->getForm(); - $form = $this->getForm('name', '\stdClass', [ + $form = $this->getCompoundForm($object, [ 'validation_groups' => 'form_group', 'constraints' => [new Valid()], ]); @@ -465,7 +457,7 @@ class FormValidatorTest extends ConstraintValidatorTestCase 'validation_groups' => 'button_group', ])); - $form->setData($object); + $parent->submit([]); $this->expectValidateAt(0, 'data', $object, ['form_group']); @@ -484,10 +476,9 @@ class FormValidatorTest extends ConstraintValidatorTestCase ->setDataMapper(new PropertyPathMapper()) ->getForm(); $formOptions = ['constraints' => [new Valid()]]; - $form = $this->getBuilder('name', '\stdClass', $formOptions)->getForm(); + $form = $this->getCompoundForm($object, $formOptions); $parent->add($form); - - $form->setData($object); + $parent->submit([]); $this->expectValidateAt(0, 'data', $object, ['group']); @@ -506,10 +497,9 @@ class FormValidatorTest extends ConstraintValidatorTestCase ->setDataMapper(new PropertyPathMapper()) ->getForm(); $formOptions = ['constraints' => [new Valid()]]; - $form = $this->getBuilder('name', '\stdClass', $formOptions)->getForm(); + $form = $this->getCompoundForm($object, $formOptions); $parent->add($form); - - $form->setData($object); + $parent->submit([]); $this->expectValidateAt(0, 'data', $object, ['group1', 'group2']); @@ -523,7 +513,7 @@ class FormValidatorTest extends ConstraintValidatorTestCase $object = new \stdClass(); $parentOptions = [ - 'validation_groups' => function (FormInterface $form) { + 'validation_groups' => function () { return ['group1', 'group2']; }, ]; @@ -532,10 +522,9 @@ class FormValidatorTest extends ConstraintValidatorTestCase ->setDataMapper(new PropertyPathMapper()) ->getForm(); $formOptions = ['constraints' => [new Valid()]]; - $form = $this->getBuilder('name', '\stdClass', $formOptions)->getForm(); + $form = $this->getCompoundForm($object, $formOptions); $parent->add($form); - - $form->setData($object); + $parent->submit([]); $this->expectValidateAt(0, 'data', $object, ['group1', 'group2']); @@ -547,9 +536,8 @@ class FormValidatorTest extends ConstraintValidatorTestCase public function testAppendPropertyPath() { $object = new \stdClass(); - $form = $this->getBuilder('name', '\stdClass') - ->setData($object) - ->getForm(); + $form = $this->getCompoundForm($object); + $form->submit([]); $this->expectValidateAt(0, 'data', $object, ['Default']); @@ -683,6 +671,15 @@ class FormValidatorTest extends ConstraintValidatorTestCase return $this->getBuilder($name, $dataClass, $options)->getForm(); } + private function getCompoundForm($data, array $options = []) + { + return $this->getBuilder('name', \get_class($data), $options) + ->setData($data) + ->setCompound(true) + ->setDataMapper(new PropertyPathMapper()) + ->getForm(); + } + private function getSubmitButton($name = 'name', array $options = []) { $builder = new SubmitButtonBuilder($name, $options); diff --git a/src/Symfony/Component/Form/Tests/Extension/Validator/ValidatorExtensionTest.php b/src/Symfony/Component/Form/Tests/Extension/Validator/ValidatorExtensionTest.php index b526650ea0..136086a5e5 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Validator/ValidatorExtensionTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Validator/ValidatorExtensionTest.php @@ -12,12 +12,19 @@ namespace Symfony\Component\Form\Tests\Extension\Validator; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Validator\Constraints\Form as FormConstraint; use Symfony\Component\Form\Extension\Validator\ValidatorExtension; use Symfony\Component\Form\Extension\Validator\ValidatorTypeGuesser; use Symfony\Component\Form\Form; +use Symfony\Component\Form\FormBuilderInterface; +use Symfony\Component\Form\FormFactoryBuilder; +use Symfony\Component\OptionsResolver\OptionsResolver; +use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Mapping\CascadingStrategy; use Symfony\Component\Validator\Mapping\ClassMetadata; +use Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory; +use Symfony\Component\Validator\Mapping\Loader\StaticMethodLoader; use Symfony\Component\Validator\Mapping\TraversalStrategy; use Symfony\Component\Validator\Tests\Fixtures\FakeMetadataFactory; use Symfony\Component\Validator\Validation; @@ -45,4 +52,78 @@ class ValidatorExtensionTest extends TestCase $this->assertSame(CascadingStrategy::CASCADE, $metadata->getPropertyMetadata('children')[0]->cascadingStrategy); $this->assertSame(TraversalStrategy::IMPLICIT, $metadata->getPropertyMetadata('children')[0]->traversalStrategy); } + + public function testDataConstraintsInvalidateFormEvenIfFieldIsNotSubmitted() + { + $form = $this->createForm(FooType::class); + $form->submit(['baz' => 'foobar'], false); + + $this->assertTrue($form->isSubmitted()); + $this->assertFalse($form->isValid()); + $this->assertFalse($form->get('bar')->isSubmitted()); + $this->assertCount(1, $form->get('bar')->getErrors()); + } + + public function testFieldConstraintsDoNotInvalidateFormIfFieldIsNotSubmitted() + { + $form = $this->createForm(FooType::class); + $form->submit(['bar' => 'foobar'], false); + + $this->assertTrue($form->isSubmitted()); + $this->assertTrue($form->isValid()); + } + + public function testFieldConstraintsInvalidateFormIfFieldIsSubmitted() + { + $form = $this->createForm(FooType::class); + $form->submit(['bar' => 'foobar', 'baz' => ''], false); + + $this->assertTrue($form->isSubmitted()); + $this->assertFalse($form->isValid()); + $this->assertTrue($form->get('bar')->isSubmitted()); + $this->assertTrue($form->get('bar')->isValid()); + $this->assertTrue($form->get('baz')->isSubmitted()); + $this->assertFalse($form->get('baz')->isValid()); + } + + private function createForm($type) + { + $validator = Validation::createValidatorBuilder() + ->setMetadataFactory(new LazyLoadingMetadataFactory(new StaticMethodLoader())) + ->getValidator(); + $formFactoryBuilder = new FormFactoryBuilder(); + $formFactoryBuilder->addExtension(new ValidatorExtension($validator)); + $formFactory = $formFactoryBuilder->getFormFactory(); + + return $formFactory->create($type); + } +} + +class Foo +{ + public $bar; + public $baz; + + public static function loadValidatorMetadata(ClassMetadata $metadata) + { + $metadata->addPropertyConstraint('bar', new NotBlank()); + } +} + +class FooType extends AbstractType +{ + public function buildForm(FormBuilderInterface $builder, array $options) + { + $builder + ->add('bar') + ->add('baz', null, [ + 'constraints' => [new NotBlank()], + ]) + ; + } + + public function configureOptions(OptionsResolver $resolver) + { + $resolver->setDefault('data_class', Foo::class); + } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php b/src/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php index 5d0afa238c..2fa3e92892 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php @@ -205,7 +205,7 @@ class ViolationMapperTest extends TestCase $this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one'); } - public function testAbortMappingIfNotSubmitted() + public function testMappingIfNotSubmitted() { $violation = $this->getConstraintViolation('children[address].data.street'); $parent = $this->getForm('parent'); @@ -225,10 +225,10 @@ class ViolationMapperTest extends TestCase $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one'); $this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error, but has one'); - $this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one'); + $this->assertCount(1, $grandChild->getErrors(), $grandChild->getName().' should have one error'); } - public function testAbortDotRuleMappingIfNotSubmitted() + public function testDotRuleMappingIfNotSubmitted() { $violation = $this->getConstraintViolation('data.address'); $parent = $this->getForm('parent'); @@ -250,7 +250,7 @@ class ViolationMapperTest extends TestCase $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one'); $this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error, but has one'); - $this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one'); + $this->assertCount(1, $grandChild->getErrors(), $grandChild->getName().' should have one error'); } public function provideDefaultTests() diff --git a/src/Symfony/Component/Form/Tests/Fixtures/CustomArrayObject.php b/src/Symfony/Component/Form/Tests/Fixtures/CustomArrayObject.php index 39758e7818..006724014a 100644 --- a/src/Symfony/Component/Form/Tests/Fixtures/CustomArrayObject.php +++ b/src/Symfony/Component/Form/Tests/Fixtures/CustomArrayObject.php @@ -26,7 +26,7 @@ class CustomArrayObject implements \ArrayAccess, \IteratorAggregate, \Countable, public function offsetExists($offset) { - return array_key_exists($offset, $this->array); + return \array_key_exists($offset, $this->array); } public function offsetGet($offset) diff --git a/src/Symfony/Component/Form/Tests/Fixtures/FixedDataTransformer.php b/src/Symfony/Component/Form/Tests/Fixtures/FixedDataTransformer.php index e768b1d7cf..2939116096 100644 --- a/src/Symfony/Component/Form/Tests/Fixtures/FixedDataTransformer.php +++ b/src/Symfony/Component/Form/Tests/Fixtures/FixedDataTransformer.php @@ -25,7 +25,7 @@ class FixedDataTransformer implements DataTransformerInterface public function transform($value) { - if (!array_key_exists($value, $this->mapping)) { + if (!\array_key_exists($value, $this->mapping)) { throw new TransformationFailedException(sprintf('No mapping for value "%s"', $value)); } diff --git a/src/Symfony/Component/HttpFoundation/HeaderBag.php b/src/Symfony/Component/HttpFoundation/HeaderBag.php index b37a72e47e..fa9d17313c 100644 --- a/src/Symfony/Component/HttpFoundation/HeaderBag.php +++ b/src/Symfony/Component/HttpFoundation/HeaderBag.php @@ -112,7 +112,7 @@ class HeaderBag implements \IteratorAggregate, \Countable $key = str_replace('_', '-', strtolower($key)); $headers = $this->all(); - if (!array_key_exists($key, $headers)) { + if (!\array_key_exists($key, $headers)) { if (null === $default) { return $first ? null : []; } @@ -168,7 +168,7 @@ class HeaderBag implements \IteratorAggregate, \Countable */ public function has($key) { - return array_key_exists(str_replace('_', '-', strtolower($key)), $this->all()); + return \array_key_exists(str_replace('_', '-', strtolower($key)), $this->all()); } /** @@ -245,7 +245,7 @@ class HeaderBag implements \IteratorAggregate, \Countable */ public function hasCacheControlDirective($key) { - return array_key_exists($key, $this->cacheControl); + return \array_key_exists($key, $this->cacheControl); } /** @@ -257,7 +257,7 @@ class HeaderBag implements \IteratorAggregate, \Countable */ public function getCacheControlDirective($key) { - return array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] : null; + return \array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] : null; } /** diff --git a/src/Symfony/Component/HttpFoundation/ParameterBag.php b/src/Symfony/Component/HttpFoundation/ParameterBag.php index 3c6ba46a6a..f05e4a2154 100644 --- a/src/Symfony/Component/HttpFoundation/ParameterBag.php +++ b/src/Symfony/Component/HttpFoundation/ParameterBag.php @@ -81,7 +81,7 @@ class ParameterBag implements \IteratorAggregate, \Countable */ public function get($key, $default = null) { - return array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default; + return \array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default; } /** @@ -104,7 +104,7 @@ class ParameterBag implements \IteratorAggregate, \Countable */ public function has($key) { - return array_key_exists($key, $this->parameters); + return \array_key_exists($key, $this->parameters); } /** diff --git a/src/Symfony/Component/HttpFoundation/RedirectResponse.php b/src/Symfony/Component/HttpFoundation/RedirectResponse.php index 22e5fbb2d0..f685856584 100644 --- a/src/Symfony/Component/HttpFoundation/RedirectResponse.php +++ b/src/Symfony/Component/HttpFoundation/RedirectResponse.php @@ -42,7 +42,7 @@ class RedirectResponse extends Response throw new \InvalidArgumentException(sprintf('The HTTP status code is not a redirect ("%s" given).', $status)); } - if (301 == $status && !array_key_exists('cache-control', $headers)) { + if (301 == $status && !\array_key_exists('cache-control', $headers)) { $this->headers->remove('cache-control'); } } diff --git a/src/Symfony/Component/HttpFoundation/Request.php b/src/Symfony/Component/HttpFoundation/Request.php index 7f44aab1d5..355bf59548 100644 --- a/src/Symfony/Component/HttpFoundation/Request.php +++ b/src/Symfony/Component/HttpFoundation/Request.php @@ -617,6 +617,81 @@ class Request } /** +<<<<<<< HEAD +======= + * Sets the name for trusted headers. + * + * The following header keys are supported: + * + * * Request::HEADER_CLIENT_IP: defaults to X-Forwarded-For (see getClientIp()) + * * Request::HEADER_CLIENT_HOST: defaults to X-Forwarded-Host (see getHost()) + * * Request::HEADER_CLIENT_PORT: defaults to X-Forwarded-Port (see getPort()) + * * Request::HEADER_CLIENT_PROTO: defaults to X-Forwarded-Proto (see getScheme() and isSecure()) + * * Request::HEADER_FORWARDED: defaults to Forwarded (see RFC 7239) + * + * Setting an empty value allows to disable the trusted header for the given key. + * + * @param string $key The header key + * @param string $value The header name + * + * @throws \InvalidArgumentException + * + * @deprecated since version 3.3, to be removed in 4.0. Use the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead. + */ + public static function setTrustedHeaderName($key, $value) + { + @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 3.3 and will be removed in 4.0. Use the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead.', __METHOD__), E_USER_DEPRECATED); + + if ('forwarded' === $key) { + $key = self::HEADER_FORWARDED; + } elseif ('client_ip' === $key) { + $key = self::HEADER_CLIENT_IP; + } elseif ('client_host' === $key) { + $key = self::HEADER_CLIENT_HOST; + } elseif ('client_proto' === $key) { + $key = self::HEADER_CLIENT_PROTO; + } elseif ('client_port' === $key) { + $key = self::HEADER_CLIENT_PORT; + } elseif (!\array_key_exists($key, self::$trustedHeaders)) { + throw new \InvalidArgumentException(sprintf('Unable to set the trusted header name for key "%s".', $key)); + } + + self::$trustedHeaders[$key] = $value; + + if (null !== $value) { + self::$trustedHeaderNames[$key] = $value; + self::$trustedHeaderSet |= $key; + } else { + self::$trustedHeaderSet &= ~$key; + } + } + + /** + * Gets the trusted proxy header name. + * + * @param string $key The header key + * + * @return string The header name + * + * @throws \InvalidArgumentException + * + * @deprecated since version 3.3, to be removed in 4.0. Use the Request::getTrustedHeaderSet() method instead. + */ + public static function getTrustedHeaderName($key) + { + if (2 > \func_num_args() || func_get_arg(1)) { + @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 3.3 and will be removed in 4.0. Use the Request::getTrustedHeaderSet() method instead.', __METHOD__), E_USER_DEPRECATED); + } + + if (!\array_key_exists($key, self::$trustedHeaders)) { + throw new \InvalidArgumentException(sprintf('Unable to get the trusted header name for key "%s".', $key)); + } + + return self::$trustedHeaders[$key]; + } + + /** +>>>>>>> 3.4 * Normalizes a query string. * * It builds a normalized query string, where keys/value pairs are alphabetized, diff --git a/src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php b/src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php index 9dd8908b27..9e07221933 100644 --- a/src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php +++ b/src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php @@ -160,7 +160,7 @@ class ResponseHeaderBag extends HeaderBag */ public function hasCacheControlDirective($key) { - return array_key_exists($key, $this->computedCacheControl); + return \array_key_exists($key, $this->computedCacheControl); } /** @@ -168,7 +168,7 @@ class ResponseHeaderBag extends HeaderBag */ public function getCacheControlDirective($key) { - return array_key_exists($key, $this->computedCacheControl) ? $this->computedCacheControl[$key] : null; + return \array_key_exists($key, $this->computedCacheControl) ? $this->computedCacheControl[$key] : null; } public function setCookie(Cookie $cookie) diff --git a/src/Symfony/Component/HttpFoundation/Session/Attribute/AttributeBag.php b/src/Symfony/Component/HttpFoundation/Session/Attribute/AttributeBag.php index 7b53e7fc76..ee33698cf0 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Attribute/AttributeBag.php +++ b/src/Symfony/Component/HttpFoundation/Session/Attribute/AttributeBag.php @@ -63,7 +63,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta */ public function has($name) { - return array_key_exists($name, $this->attributes); + return \array_key_exists($name, $this->attributes); } /** @@ -71,7 +71,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta */ public function get($name, $default = null) { - return array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; + return \array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; } /** @@ -107,7 +107,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta public function remove($name) { $retval = null; - if (array_key_exists($name, $this->attributes)) { + if (\array_key_exists($name, $this->attributes)) { $retval = $this->attributes[$name]; unset($this->attributes[$name]); } diff --git a/src/Symfony/Component/HttpFoundation/Session/Attribute/NamespacedAttributeBag.php b/src/Symfony/Component/HttpFoundation/Session/Attribute/NamespacedAttributeBag.php index 7890214e82..162c4b5295 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Attribute/NamespacedAttributeBag.php +++ b/src/Symfony/Component/HttpFoundation/Session/Attribute/NamespacedAttributeBag.php @@ -44,7 +44,7 @@ class NamespacedAttributeBag extends AttributeBag return false; } - return array_key_exists($name, $attributes); + return \array_key_exists($name, $attributes); } /** @@ -60,7 +60,7 @@ class NamespacedAttributeBag extends AttributeBag return $default; } - return array_key_exists($name, $attributes) ? $attributes[$name] : $default; + return \array_key_exists($name, $attributes) ? $attributes[$name] : $default; } /** @@ -81,7 +81,7 @@ class NamespacedAttributeBag extends AttributeBag $retval = null; $attributes = &$this->resolveAttributePath($name); $name = $this->resolveKey($name); - if (null !== $attributes && array_key_exists($name, $attributes)) { + if (null !== $attributes && \array_key_exists($name, $attributes)) { $retval = $attributes[$name]; unset($attributes[$name]); } @@ -123,7 +123,7 @@ class NamespacedAttributeBag extends AttributeBag unset($parts[\count($parts) - 1]); foreach ($parts as $part) { - if (null !== $array && !array_key_exists($part, $array)) { + if (null !== $array && !\array_key_exists($part, $array)) { if (!$writeContext) { $null = null; diff --git a/src/Symfony/Component/HttpFoundation/Session/Flash/AutoExpireFlashBag.php b/src/Symfony/Component/HttpFoundation/Session/Flash/AutoExpireFlashBag.php index 782665caff..6502f3d501 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Flash/AutoExpireFlashBag.php +++ b/src/Symfony/Component/HttpFoundation/Session/Flash/AutoExpireFlashBag.php @@ -53,7 +53,7 @@ class AutoExpireFlashBag implements FlashBagInterface // The logic: messages from the last request will be stored in new, so we move them to previous // This request we will show what is in 'display'. What is placed into 'new' this time round will // be moved to display next time round. - $this->flashes['display'] = array_key_exists('new', $this->flashes) ? $this->flashes['new'] : []; + $this->flashes['display'] = \array_key_exists('new', $this->flashes) ? $this->flashes['new'] : []; $this->flashes['new'] = []; } @@ -78,7 +78,7 @@ class AutoExpireFlashBag implements FlashBagInterface */ public function peekAll() { - return array_key_exists('display', $this->flashes) ? (array) $this->flashes['display'] : []; + return \array_key_exists('display', $this->flashes) ? (array) $this->flashes['display'] : []; } /** @@ -132,7 +132,7 @@ class AutoExpireFlashBag implements FlashBagInterface */ public function has($type) { - return array_key_exists($type, $this->flashes['display']) && $this->flashes['display'][$type]; + return \array_key_exists($type, $this->flashes['display']) && $this->flashes['display'][$type]; } /** diff --git a/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBag.php b/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBag.php index 9674e3514b..c6b7ce354c 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBag.php +++ b/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBag.php @@ -123,7 +123,7 @@ class FlashBag implements FlashBagInterface */ public function has($type) { - return array_key_exists($type, $this->flashes) && $this->flashes[$type]; + return \array_key_exists($type, $this->flashes) && $this->flashes[$type]; } /** diff --git a/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php b/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php index dd00797f5f..811f99bd9d 100644 --- a/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php +++ b/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php @@ -79,13 +79,12 @@ class ExceptionListener implements EventSubscriberInterface $this->logException($e, sprintf('Exception thrown when handling an exception (%s: %s at %s line %s)', $f->getClass(), $f->getMessage(), $e->getFile(), $e->getLine())); - $wrapper = $e; - - while ($prev = $wrapper->getPrevious()) { + $prev = $e; + do { if ($exception === $wrapper = $prev) { throw $e; } - } + } while ($prev = $wrapper->getPrevious()); $prev = new \ReflectionProperty($wrapper instanceof \Exception ? \Exception::class : \Error::class, 'previous'); $prev->setAccessible(true); diff --git a/src/Symfony/Component/HttpKernel/Fragment/InlineFragmentRenderer.php b/src/Symfony/Component/HttpKernel/Fragment/InlineFragmentRenderer.php index 5ee09fb1a7..c01b09559a 100644 --- a/src/Symfony/Component/HttpKernel/Fragment/InlineFragmentRenderer.php +++ b/src/Symfony/Component/HttpKernel/Fragment/InlineFragmentRenderer.php @@ -80,7 +80,7 @@ class InlineFragmentRenderer extends RoutableFragmentRenderer return SubRequestHandler::handle($this->kernel, $subRequest, HttpKernelInterface::SUB_REQUEST, false); } catch (\Exception $e) { // we dispatch the exception event to trigger the logging - // the response that comes back is simply ignored + // the response that comes back is ignored if (isset($options['ignore_errors']) && $options['ignore_errors'] && $this->dispatcher) { $event = new GetResponseForExceptionEvent($this->kernel, $request, HttpKernelInterface::SUB_REQUEST, $e); diff --git a/src/Symfony/Component/HttpKernel/Tests/DataCollector/RequestDataCollectorTest.php b/src/Symfony/Component/HttpKernel/Tests/DataCollector/RequestDataCollectorTest.php index ec86792e93..f32247fd32 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DataCollector/RequestDataCollectorTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DataCollector/RequestDataCollectorTest.php @@ -351,15 +351,15 @@ class RequestDataCollectorTest extends TestCase public function provideJsonContentTypes() { - return array( - array('text/csv', false), - array('application/json', true), - array('application/JSON', true), - array('application/hal+json', true), - array('application/xml+json', true), - array('application/xml', false), - array('', false), - ); + return [ + ['text/csv', false], + ['application/json', true], + ['application/JSON', true], + ['application/hal+json', true], + ['application/xml+json', true], + ['application/xml', false], + ['', false], + ]; } /** @@ -368,7 +368,7 @@ class RequestDataCollectorTest extends TestCase public function testGetPrettyJsonValidity($content, $expected) { $response = $this->createResponse(); - $request = Request::create('/', 'POST', array(), array(), array(), array(), $content); + $request = Request::create('/', 'POST', [], [], [], [], $content); $c = new RequestDataCollector(); $c->collect($request, $response); @@ -378,13 +378,13 @@ class RequestDataCollectorTest extends TestCase public function providePrettyJson() { - return array( - array('null', 'null'), - array('{ "foo": "bar" }', '{ + return [ + ['null', 'null'], + ['{ "foo": "bar" }', '{ "foo": "bar" -}'), - array('{ "abc" }', null), - array('', null), - ); +}'], + ['{ "abc" }', null], + ['', null], + ]; } } diff --git a/src/Symfony/Component/Intl/Data/Generator/LocaleDataGenerator.php b/src/Symfony/Component/Intl/Data/Generator/LocaleDataGenerator.php index d1fc3c01e0..84940e63ae 100644 --- a/src/Symfony/Component/Intl/Data/Generator/LocaleDataGenerator.php +++ b/src/Symfony/Component/Intl/Data/Generator/LocaleDataGenerator.php @@ -164,7 +164,7 @@ class LocaleDataGenerator // the name sorting // $name = $this->langBundle->getLanguageName($displayLocale, $lang, $region); - // Some languages are simply not translated + // Some languages are not translated // Example: "az" (Azerbaijani) has no translation in "af" (Afrikaans) if (null === ($name = $this->languageDataProvider->getName($lang, $displayLocale))) { return; diff --git a/src/Symfony/Component/Intl/Data/Util/RecursiveArrayAccess.php b/src/Symfony/Component/Intl/Data/Util/RecursiveArrayAccess.php index c133932c9e..09dd551daf 100644 --- a/src/Symfony/Component/Intl/Data/Util/RecursiveArrayAccess.php +++ b/src/Symfony/Component/Intl/Data/Util/RecursiveArrayAccess.php @@ -25,7 +25,7 @@ class RecursiveArrayAccess foreach ($indices as $index) { // Use array_key_exists() for arrays, isset() otherwise if (\is_array($array)) { - if (array_key_exists($index, $array)) { + if (\array_key_exists($index, $array)) { $array = $array[$index]; continue; } diff --git a/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php b/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php index 247ea5e1d8..c668d9a3c1 100644 --- a/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php +++ b/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php @@ -460,7 +460,7 @@ class NumberFormatter */ public function getSymbol($attr) { - return array_key_exists($this->style, self::$enSymbols) && array_key_exists($attr, self::$enSymbols[$this->style]) ? self::$enSymbols[$this->style][$attr] : false; + return \array_key_exists($this->style, self::$enSymbols) && \array_key_exists($attr, self::$enSymbols[$this->style]) ? self::$enSymbols[$this->style][$attr] : false; } /** @@ -474,7 +474,7 @@ class NumberFormatter */ public function getTextAttribute($attr) { - return array_key_exists($this->style, self::$enTextAttributes) && array_key_exists($attr, self::$enTextAttributes[$this->style]) ? self::$enTextAttributes[$this->style][$attr] : false; + return \array_key_exists($this->style, self::$enTextAttributes) && \array_key_exists($attr, self::$enTextAttributes[$this->style]) ? self::$enTextAttributes[$this->style][$attr] : false; } /** diff --git a/src/Symfony/Component/Messenger/Transport/AmqpExt/Connection.php b/src/Symfony/Component/Messenger/Transport/AmqpExt/Connection.php index d56b105a2b..e576916b8d 100644 --- a/src/Symfony/Component/Messenger/Transport/AmqpExt/Connection.php +++ b/src/Symfony/Component/Messenger/Transport/AmqpExt/Connection.php @@ -110,7 +110,7 @@ class Connection private static function normalizeQueueArguments(array $arguments): array { foreach (self::ARGUMENTS_AS_INTEGER as $key) { - if (!array_key_exists($key, $arguments)) { + if (!\array_key_exists($key, $arguments)) { continue; } @@ -256,6 +256,6 @@ class Connection private function shouldSetup(): bool { - return !array_key_exists('auto-setup', $this->connectionCredentials) || !\in_array($this->connectionCredentials['auto-setup'], [false, 'false'], true); + return !\array_key_exists('auto-setup', $this->connectionCredentials) || !\in_array($this->connectionCredentials['auto-setup'], [false, 'false'], true); } } diff --git a/src/Symfony/Component/OptionsResolver/Debug/OptionsResolverIntrospector.php b/src/Symfony/Component/OptionsResolver/Debug/OptionsResolverIntrospector.php index 3867447a30..ccce082fed 100644 --- a/src/Symfony/Component/OptionsResolver/Debug/OptionsResolverIntrospector.php +++ b/src/Symfony/Component/OptionsResolver/Debug/OptionsResolverIntrospector.php @@ -32,7 +32,7 @@ class OptionsResolverIntrospector throw new UndefinedOptionsException(sprintf('The option "%s" does not exist.', $option)); } - if (!array_key_exists($option, $this->{$property})) { + if (!\array_key_exists($option, $this->{$property})) { throw new NoConfigurationException($message); } diff --git a/src/Symfony/Component/OptionsResolver/OptionsResolver.php b/src/Symfony/Component/OptionsResolver/OptionsResolver.php index 6532fe0a0a..eb0a6c2480 100644 --- a/src/Symfony/Component/OptionsResolver/OptionsResolver.php +++ b/src/Symfony/Component/OptionsResolver/OptionsResolver.php @@ -219,7 +219,7 @@ class OptionsResolver implements Options // to resolve options with lazy closures, normalizers or validation // rules, none of which can exist for undefined options // If the option was resolved before, update the resolved value - if (!isset($this->defined[$option]) || array_key_exists($option, $this->resolved)) { + if (!isset($this->defined[$option]) || \array_key_exists($option, $this->resolved)) { $this->resolved[$option] = $value; } @@ -259,7 +259,7 @@ class OptionsResolver implements Options */ public function hasDefault($option) { - return array_key_exists($option, $this->defaults); + return \array_key_exists($option, $this->defaults); } /** @@ -324,7 +324,7 @@ class OptionsResolver implements Options */ public function isMissing($option) { - return isset($this->required[$option]) && !array_key_exists($option, $this->defaults); + return isset($this->required[$option]) && !\array_key_exists($option, $this->defaults); } /** @@ -800,7 +800,7 @@ class OptionsResolver implements Options $triggerDeprecation = 1 === \func_num_args() || \func_get_arg(1); // Shortcut for resolved options - if (isset($this->resolved[$option]) || array_key_exists($option, $this->resolved)) { + if (isset($this->resolved[$option]) || \array_key_exists($option, $this->resolved)) { if ($triggerDeprecation && isset($this->deprecated[$option]) && (isset($this->given[$option]) || $this->calling) && \is_string($this->deprecated[$option])) { @trigger_error(strtr($this->deprecated[$option], ['%name%' => $option]), E_USER_DEPRECATED); } @@ -809,7 +809,7 @@ class OptionsResolver implements Options } // Check whether the option is set at all - if (!isset($this->defaults[$option]) && !array_key_exists($option, $this->defaults)) { + if (!isset($this->defaults[$option]) && !\array_key_exists($option, $this->defaults)) { if (!isset($this->defined[$option])) { throw new NoSuchOptionException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined)))); } @@ -1033,7 +1033,7 @@ class OptionsResolver implements Options throw new AccessException('Array access is only supported within closures of lazy options and normalizers.'); } - return array_key_exists($option, $this->defaults); + return \array_key_exists($option, $this->defaults); } /** diff --git a/src/Symfony/Component/PropertyAccess/PropertyAccessor.php b/src/Symfony/Component/PropertyAccess/PropertyAccessor.php index aae083e4b7..b7333dac30 100644 --- a/src/Symfony/Component/PropertyAccess/PropertyAccessor.php +++ b/src/Symfony/Component/PropertyAccess/PropertyAccessor.php @@ -185,7 +185,7 @@ class PropertyAccessor implements PropertyAccessorInterface return; } - if (isset($trace[$i]['file']) && __FILE__ === $trace[$i]['file'] && array_key_exists(0, $trace[$i]['args'])) { + if (isset($trace[$i]['file']) && __FILE__ === $trace[$i]['file'] && \array_key_exists(0, $trace[$i]['args'])) { $pos = strpos($message, $delim = 'must be of the type ') ?: (strpos($message, $delim = 'must be an instance of ') ?: strpos($message, $delim = 'must implement interface ')); $pos += \strlen($delim); $type = $trace[$i]['args'][0]; @@ -287,7 +287,7 @@ class PropertyAccessor implements PropertyAccessorInterface if ($isIndex) { // Create missing nested arrays on demand if (($zval[self::VALUE] instanceof \ArrayAccess && !$zval[self::VALUE]->offsetExists($property)) || - (\is_array($zval[self::VALUE]) && !isset($zval[self::VALUE][$property]) && !array_key_exists($property, $zval[self::VALUE])) + (\is_array($zval[self::VALUE]) && !isset($zval[self::VALUE][$property]) && !\array_key_exists($property, $zval[self::VALUE])) ) { if (!$ignoreInvalidIndices) { if (!\is_array($zval[self::VALUE])) { diff --git a/src/Symfony/Component/PropertyAccess/Tests/Fixtures/NonTraversableArrayObject.php b/src/Symfony/Component/PropertyAccess/Tests/Fixtures/NonTraversableArrayObject.php index 4852e8d58f..4b18e725ae 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/Fixtures/NonTraversableArrayObject.php +++ b/src/Symfony/Component/PropertyAccess/Tests/Fixtures/NonTraversableArrayObject.php @@ -26,7 +26,7 @@ class NonTraversableArrayObject implements \ArrayAccess, \Countable, \Serializab public function offsetExists($offset) { - return array_key_exists($offset, $this->array); + return \array_key_exists($offset, $this->array); } public function offsetGet($offset) diff --git a/src/Symfony/Component/PropertyAccess/Tests/Fixtures/TraversableArrayObject.php b/src/Symfony/Component/PropertyAccess/Tests/Fixtures/TraversableArrayObject.php index 9803a11f84..b075286f4a 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/Fixtures/TraversableArrayObject.php +++ b/src/Symfony/Component/PropertyAccess/Tests/Fixtures/TraversableArrayObject.php @@ -26,7 +26,7 @@ class TraversableArrayObject implements \ArrayAccess, \IteratorAggregate, \Count public function offsetExists($offset) { - return array_key_exists($offset, $this->array); + return \array_key_exists($offset, $this->array); } public function offsetGet($offset) diff --git a/src/Symfony/Component/PropertyInfo/PropertyInfoCacheExtractor.php b/src/Symfony/Component/PropertyInfo/PropertyInfoCacheExtractor.php index ac883e7c04..0eb9f63a54 100644 --- a/src/Symfony/Component/PropertyInfo/PropertyInfoCacheExtractor.php +++ b/src/Symfony/Component/PropertyInfo/PropertyInfoCacheExtractor.php @@ -105,7 +105,7 @@ class PropertyInfoCacheExtractor implements PropertyInfoExtractorInterface, Prop // Calling rawurlencode escapes special characters not allowed in PSR-6's keys $key = rawurlencode($method.'.'.$serializedArguments); - if (array_key_exists($key, $this->arrayCache)) { + if (\array_key_exists($key, $this->arrayCache)) { return $this->arrayCache[$key]; } diff --git a/src/Symfony/Component/Routing/Generator/UrlGenerator.php b/src/Symfony/Component/Routing/Generator/UrlGenerator.php index abb5b7e6f0..1871437eae 100644 --- a/src/Symfony/Component/Routing/Generator/UrlGenerator.php +++ b/src/Symfony/Component/Routing/Generator/UrlGenerator.php @@ -160,7 +160,7 @@ class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInt // variable is not important by default $important = $token[5] ?? false; - if (!$optional || $important || !array_key_exists($varName, $defaults) || (null !== $mergedParams[$varName] && (string) $mergedParams[$varName] !== (string) $defaults[$varName])) { + if (!$optional || $important || !\array_key_exists($varName, $defaults) || (null !== $mergedParams[$varName] && (string) $mergedParams[$varName] !== (string) $defaults[$varName])) { // check requirement if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#'.(empty($token[4]) ? '' : 'u'), $mergedParams[$varName])) { if ($this->strictRequirements) { @@ -216,7 +216,8 @@ class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInt $routeHost = ''; foreach ($hostTokens as $token) { if ('variable' === $token[0]) { - if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#i'.(empty($token[4]) ? '' : 'u'), $mergedParams[$token[3]])) { + // check requirement (while ignoring look-around patterns) + if (null !== $this->strictRequirements && !preg_match('#^'.preg_replace('/\(\?(?:=|<=|!|strictRequirements) { throw new InvalidParameterException(strtr($message, ['{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]]])); } diff --git a/src/Symfony/Component/Routing/RequestContext.php b/src/Symfony/Component/Routing/RequestContext.php index dc3e4be1e7..591dd15938 100644 --- a/src/Symfony/Component/Routing/RequestContext.php +++ b/src/Symfony/Component/Routing/RequestContext.php @@ -306,7 +306,7 @@ class RequestContext */ public function hasParameter($name) { - return array_key_exists($name, $this->parameters); + return \array_key_exists($name, $this->parameters); } /** diff --git a/src/Symfony/Component/Routing/Route.php b/src/Symfony/Component/Routing/Route.php index 58675902a1..4e0463b575 100644 --- a/src/Symfony/Component/Routing/Route.php +++ b/src/Symfony/Component/Routing/Route.php @@ -327,7 +327,7 @@ class Route implements \Serializable */ public function hasOption($name) { - return array_key_exists($name, $this->options); + return \array_key_exists($name, $this->options); } /** @@ -396,7 +396,7 @@ class Route implements \Serializable */ public function hasDefault($name) { - return array_key_exists($name, $this->defaults); + return \array_key_exists($name, $this->defaults); } /** @@ -481,7 +481,7 @@ class Route implements \Serializable */ public function hasRequirement($key) { - return array_key_exists($key, $this->requirements); + return \array_key_exists($key, $this->requirements); } /** diff --git a/src/Symfony/Component/Routing/Router.php b/src/Symfony/Component/Routing/Router.php index 34c4d9ce23..3024c9f255 100644 --- a/src/Symfony/Component/Routing/Router.php +++ b/src/Symfony/Component/Routing/Router.php @@ -146,7 +146,7 @@ class Router implements RouterInterface, RequestMatcherInterface $invalid = []; foreach ($options as $key => $value) { $this->checkDeprecatedOption($key); - if (array_key_exists($key, $this->options)) { + if (\array_key_exists($key, $this->options)) { $this->options[$key] = $value; } else { $invalid[] = $key; @@ -168,7 +168,7 @@ class Router implements RouterInterface, RequestMatcherInterface */ public function setOption($key, $value) { - if (!array_key_exists($key, $this->options)) { + if (!\array_key_exists($key, $this->options)) { throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key)); } @@ -188,7 +188,7 @@ class Router implements RouterInterface, RequestMatcherInterface */ public function getOption($key) { - if (!array_key_exists($key, $this->options)) { + if (!\array_key_exists($key, $this->options)) { throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key)); } diff --git a/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php b/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php index 6a79609917..6ed5aa1787 100644 --- a/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php +++ b/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php @@ -724,6 +724,23 @@ class UrlGeneratorTest extends TestCase $this->assertEquals('/app.php/testing#fragment', $url); } + /** + * @dataProvider provideLookAroundRequirementsInPath + */ + public function testLookRoundRequirementsInPath($expected, $path, $requirement) + { + $routes = $this->getRoutes('test', new Route($path, [], ['foo' => $requirement, 'baz' => '.+?'])); + $this->assertSame($expected, $this->getGenerator($routes)->generate('test', ['foo' => 'a/b', 'baz' => 'c/d/e'])); + } + + public function provideLookAroundRequirementsInPath() + { + yield ['/app.php/a/b/b%28ar/c/d/e', '/{foo}/b(ar/{baz}', '.+(?=/b\\(ar/)']; + yield ['/app.php/a/b/bar/c/d/e', '/{foo}/bar/{baz}', '.+(?!$)']; + yield ['/app.php/bar/a/b/bam/c/d/e', '/bar/{foo}/bam/{baz}', '(?<=/bar/).+']; + yield ['/app.php/bar/a/b/bam/c/d/e', '/bar/{foo}/bam/{baz}', '(?attributes); + return \array_key_exists($name, $this->attributes); } /** @@ -239,7 +239,7 @@ abstract class AbstractToken implements TokenInterface */ public function getAttribute($name) { - if (!array_key_exists($name, $this->attributes)) { + if (!\array_key_exists($name, $this->attributes)) { throw new \InvalidArgumentException(sprintf('This token has no "%s" attribute.', $name)); } diff --git a/src/Symfony/Component/Security/Core/Authorization/AccessDecisionManager.php b/src/Symfony/Component/Security/Core/Authorization/AccessDecisionManager.php index 058085e349..8509844f9a 100644 --- a/src/Symfony/Component/Security/Core/Authorization/AccessDecisionManager.php +++ b/src/Symfony/Component/Security/Core/Authorization/AccessDecisionManager.php @@ -42,7 +42,7 @@ class AccessDecisionManager implements AccessDecisionManagerInterface public function __construct(iterable $voters = [], string $strategy = self::STRATEGY_AFFIRMATIVE, bool $allowIfAllAbstainDecisions = false, bool $allowIfEqualGrantedDeniedDecisions = true) { $strategyMethod = 'decide'.ucfirst($strategy); - if (!\is_callable([$this, $strategyMethod])) { + if ('' === $strategy || !\is_callable([$this, $strategyMethod])) { throw new \InvalidArgumentException(sprintf('The strategy "%s" is not supported.', $strategy)); } diff --git a/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php b/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php index a774d7e11c..8695ba3401 100644 --- a/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php +++ b/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php @@ -33,7 +33,7 @@ class EncoderFactory implements EncoderFactoryInterface $encoderKey = null; if ($user instanceof EncoderAwareInterface && (null !== $encoderName = $user->getEncoderName())) { - if (!array_key_exists($encoderName, $this->encoders)) { + if (!\array_key_exists($encoderName, $this->encoders)) { throw new \RuntimeException(sprintf('The encoder "%s" was not configured.', $encoderName)); } diff --git a/src/Symfony/Component/Security/Http/Firewall/SimpleFormAuthenticationListener.php b/src/Symfony/Component/Security/Http/Firewall/SimpleFormAuthenticationListener.php index f6fd0c1ec4..a8ccee0f7d 100644 --- a/src/Symfony/Component/Security/Http/Firewall/SimpleFormAuthenticationListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/SimpleFormAuthenticationListener.php @@ -97,7 +97,7 @@ class SimpleFormAuthenticationListener extends AbstractAuthenticationListener $password = ParameterBagUtils::getRequestParameterValue($request, $this->options['password_parameter']); } - if (!\is_string($username) || (\is_object($username) && !\method_exists($username, '__toString'))) { + if (!\is_string($username) && (!\is_object($username) || !\method_exists($username, '__toString'))) { throw new BadRequestHttpException(sprintf('The key "%s" must be a string, "%s" given.', $this->options['username_parameter'], \gettype($username))); } diff --git a/src/Symfony/Component/Security/Http/Firewall/UsernamePasswordFormAuthenticationListener.php b/src/Symfony/Component/Security/Http/Firewall/UsernamePasswordFormAuthenticationListener.php index f6ce869b29..2b8ab8d09f 100644 --- a/src/Symfony/Component/Security/Http/Firewall/UsernamePasswordFormAuthenticationListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/UsernamePasswordFormAuthenticationListener.php @@ -85,7 +85,7 @@ class UsernamePasswordFormAuthenticationListener extends AbstractAuthenticationL $password = ParameterBagUtils::getRequestParameterValue($request, $this->options['password_parameter']); } - if (!\is_string($username) || (\is_object($username) && !\method_exists($username, '__toString'))) { + if (!\is_string($username) && (!\is_object($username) || !\method_exists($username, '__toString'))) { throw new BadRequestHttpException(sprintf('The key "%s" must be a string, "%s" given.', $this->options['username_parameter'], \gettype($username))); } diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordFormAuthenticationListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordFormAuthenticationListenerTest.php index 198ee6566d..f1536db6d2 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordFormAuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordFormAuthenticationListenerTest.php @@ -81,7 +81,7 @@ class UsernamePasswordFormAuthenticationListenerTest extends TestCase * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException * @expectedExceptionMessage The key "_username" must be a string, "array" given. */ - public function testHandleNonStringUsername($postOnly) + public function testHandleNonStringUsernameWithArray($postOnly) { $request = Request::create('/login_check', 'POST', ['_username' => []]); $request->setSession($this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock()); @@ -99,6 +99,79 @@ class UsernamePasswordFormAuthenticationListenerTest extends TestCase $listener->handle($event); } + /** + * @dataProvider postOnlyDataProvider + * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException + * @expectedExceptionMessage The key "_username" must be a string, "integer" given. + */ + public function testHandleNonStringUsernameWithInt($postOnly) + { + $request = Request::create('/login_check', 'POST', ['_username' => 42]); + $request->setSession($this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock()); + $listener = new UsernamePasswordFormAuthenticationListener( + new TokenStorage(), + $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(), + new SessionAuthenticationStrategy(SessionAuthenticationStrategy::NONE), + $httpUtils = new HttpUtils(), + 'foo', + new DefaultAuthenticationSuccessHandler($httpUtils), + new DefaultAuthenticationFailureHandler($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $httpUtils), + ['require_previous_session' => false, 'post_only' => $postOnly] + ); + $event = new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST); + $listener->handle($event); + } + + /** + * @dataProvider postOnlyDataProvider + * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException + * @expectedExceptionMessage The key "_username" must be a string, "object" given. + */ + public function testHandleNonStringUsernameWithObject($postOnly) + { + $request = Request::create('/login_check', 'POST', ['_username' => new \stdClass()]); + $request->setSession($this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock()); + $listener = new UsernamePasswordFormAuthenticationListener( + new TokenStorage(), + $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(), + new SessionAuthenticationStrategy(SessionAuthenticationStrategy::NONE), + $httpUtils = new HttpUtils(), + 'foo', + new DefaultAuthenticationSuccessHandler($httpUtils), + new DefaultAuthenticationFailureHandler($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $httpUtils), + ['require_previous_session' => false, 'post_only' => $postOnly] + ); + $event = new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST); + $listener->handle($event); + } + + /** + * @dataProvider postOnlyDataProvider + */ + public function testHandleNonStringUsernameWith__toString($postOnly) + { + $usernameClass = $this->getMockBuilder(DummyUserClass::class)->getMock(); + $usernameClass + ->expects($this->atLeastOnce()) + ->method('__toString') + ->will($this->returnValue('someUsername')); + + $request = Request::create('/login_check', 'POST', ['_username' => $usernameClass]); + $request->setSession($this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock()); + $listener = new UsernamePasswordFormAuthenticationListener( + new TokenStorage(), + $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(), + new SessionAuthenticationStrategy(SessionAuthenticationStrategy::NONE), + $httpUtils = new HttpUtils(), + 'foo', + new DefaultAuthenticationSuccessHandler($httpUtils), + new DefaultAuthenticationFailureHandler($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $httpUtils), + ['require_previous_session' => false, 'post_only' => $postOnly] + ); + $event = new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST); + $listener->handle($event); + } + public function postOnlyDataProvider() { return [ @@ -115,3 +188,11 @@ class UsernamePasswordFormAuthenticationListenerTest extends TestCase ]; } } + +class DummyUserClass +{ + public function __toString() + { + return ''; + } +} diff --git a/src/Symfony/Component/Serializer/Mapping/ClassDiscriminatorFromClassMetadata.php b/src/Symfony/Component/Serializer/Mapping/ClassDiscriminatorFromClassMetadata.php index 1178f03cfb..23554ffda9 100644 --- a/src/Symfony/Component/Serializer/Mapping/ClassDiscriminatorFromClassMetadata.php +++ b/src/Symfony/Component/Serializer/Mapping/ClassDiscriminatorFromClassMetadata.php @@ -55,7 +55,7 @@ class ClassDiscriminatorFromClassMetadata implements ClassDiscriminatorResolverI } $cacheKey = \is_object($object) ? \get_class($object) : $object; - if (!array_key_exists($cacheKey, $this->mappingForMappedObjectCache)) { + if (!\array_key_exists($cacheKey, $this->mappingForMappedObjectCache)) { $this->mappingForMappedObjectCache[$cacheKey] = $this->resolveMappingForMappedObject($object); } diff --git a/src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php index 300c7f1b3c..e1f5d136dd 100644 --- a/src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php @@ -398,14 +398,14 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn $allowed = false === $allowedAttributes || \in_array($paramName, $allowedAttributes); $ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context); if ($constructorParameter->isVariadic()) { - if ($allowed && !$ignored && (isset($data[$key]) || array_key_exists($key, $data))) { + if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) { if (!\is_array($data[$paramName])) { throw new RuntimeException(sprintf('Cannot create an instance of %s from serialized data because the variadic parameter %s can only accept an array.', $class, $constructorParameter->name)); } $params = array_merge($params, $data[$paramName]); } - } elseif ($allowed && !$ignored && (isset($data[$key]) || array_key_exists($key, $data))) { + } elseif ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) { $parameterData = $data[$key]; if (null === $parameterData && $constructorParameter->allowsNull()) { $params[] = null; @@ -417,9 +417,9 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn // Don't run set for a parameter passed to the constructor $params[] = $this->denormalizeParameter($reflectionClass, $constructorParameter, $paramName, $parameterData, $context, $format); unset($data[$key]); - } elseif (array_key_exists($key, $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class] ?? [])) { + } elseif (\array_key_exists($key, $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class] ?? [])) { $params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key]; - } elseif (array_key_exists($key, $this->defaultContext[self::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class] ?? [])) { + } elseif (\array_key_exists($key, $this->defaultContext[self::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class] ?? [])) { $params[] = $this->defaultContext[self::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key]; } elseif ($constructorParameter->isDefaultValueAvailable()) { $params[] = $constructorParameter->getDefaultValue(); diff --git a/src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php index d3de806e18..51ad59a7e7 100644 --- a/src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php @@ -157,6 +157,7 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface, private function getTimezone(array $context) { $dateTimeZone = $context[self::TIMEZONE_KEY] ?? $this->defaultContext[self::TIMEZONE_KEY]; + if (null === $dateTimeZone) { return null; } diff --git a/src/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.php index 530f168c6a..94ed6d8b63 100644 --- a/src/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.php @@ -113,7 +113,7 @@ class ObjectNormalizer extends AbstractObjectNormalizer protected function getAttributeValue($object, $attribute, $format = null, array $context = []) { $cacheKey = \get_class($object); - if (!array_key_exists($cacheKey, $this->discriminatorCache)) { + if (!\array_key_exists($cacheKey, $this->discriminatorCache)) { $this->discriminatorCache[$cacheKey] = null; if (null !== $this->classDiscriminatorResolver) { $mapping = $this->classDiscriminatorResolver->getMappingForMappedObject($object); diff --git a/src/Symfony/Component/Templating/TemplateReference.php b/src/Symfony/Component/Templating/TemplateReference.php index 18c6bda2df..ddff4db857 100644 --- a/src/Symfony/Component/Templating/TemplateReference.php +++ b/src/Symfony/Component/Templating/TemplateReference.php @@ -41,7 +41,7 @@ class TemplateReference implements TemplateReferenceInterface */ public function set($name, $value) { - if (array_key_exists($name, $this->parameters)) { + if (\array_key_exists($name, $this->parameters)) { $this->parameters[$name] = $value; } else { throw new \InvalidArgumentException(sprintf('The template does not support the "%s" parameter.', $name)); @@ -55,7 +55,7 @@ class TemplateReference implements TemplateReferenceInterface */ public function get($name) { - if (array_key_exists($name, $this->parameters)) { + if (\array_key_exists($name, $this->parameters)) { return $this->parameters[$name]; } diff --git a/src/Symfony/Component/Translation/Dumper/FileDumper.php b/src/Symfony/Component/Translation/Dumper/FileDumper.php index 57ce9d2141..8457ecc7ec 100644 --- a/src/Symfony/Component/Translation/Dumper/FileDumper.php +++ b/src/Symfony/Component/Translation/Dumper/FileDumper.php @@ -63,7 +63,7 @@ abstract class FileDumper implements DumperInterface */ public function dump(MessageCatalogue $messages, $options = []) { - if (!array_key_exists('path', $options)) { + if (!\array_key_exists('path', $options)) { throw new InvalidArgumentException('The file dumper needs a path option.'); } diff --git a/src/Symfony/Component/Translation/Dumper/XliffFileDumper.php b/src/Symfony/Component/Translation/Dumper/XliffFileDumper.php index 2718da010d..8d2694f24e 100644 --- a/src/Symfony/Component/Translation/Dumper/XliffFileDumper.php +++ b/src/Symfony/Component/Translation/Dumper/XliffFileDumper.php @@ -27,11 +27,11 @@ class XliffFileDumper extends FileDumper public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = []) { $xliffVersion = '1.2'; - if (array_key_exists('xliff_version', $options)) { + if (\array_key_exists('xliff_version', $options)) { $xliffVersion = $options['xliff_version']; } - if (array_key_exists('default_locale', $options)) { + if (\array_key_exists('default_locale', $options)) { $defaultLocale = $options['default_locale']; } else { $defaultLocale = \Locale::getDefault(); @@ -58,7 +58,7 @@ class XliffFileDumper extends FileDumper private function dumpXliff1($defaultLocale, MessageCatalogue $messages, $domain, array $options = []) { $toolInfo = ['tool-id' => 'symfony', 'tool-name' => 'Symfony']; - if (array_key_exists('tool_info', $options)) { + if (\array_key_exists('tool_info', $options)) { $toolInfo = array_merge($toolInfo, $options['tool_info']); } @@ -204,6 +204,6 @@ class XliffFileDumper extends FileDumper */ private function hasMetadataArrayInfo($key, $metadata = null) { - return null !== $metadata && array_key_exists($key, $metadata) && ($metadata[$key] instanceof \Traversable || \is_array($metadata[$key])); + return null !== $metadata && \array_key_exists($key, $metadata) && ($metadata[$key] instanceof \Traversable || \is_array($metadata[$key])); } } diff --git a/src/Symfony/Component/Validator/Constraint.php b/src/Symfony/Component/Validator/Constraint.php index ae27ba2163..b1a5e0c1a2 100644 --- a/src/Symfony/Component/Validator/Constraint.php +++ b/src/Symfony/Component/Validator/Constraint.php @@ -122,7 +122,7 @@ abstract class Constraint } if ($options && \is_array($options) && \is_string(key($options))) { foreach ($options as $option => $value) { - if (array_key_exists($option, $knownOptions)) { + if (\array_key_exists($option, $knownOptions)) { $this->$option = $value; unset($missingOptions[$option]); } else { @@ -136,7 +136,7 @@ abstract class Constraint throw new ConstraintDefinitionException(sprintf('No default option is configured for constraint %s', \get_class($this))); } - if (array_key_exists($option, $knownOptions)) { + if (\array_key_exists($option, $knownOptions)) { $this->$option = $options; unset($missingOptions[$option]); } else { diff --git a/src/Symfony/Component/Validator/Constraints/CollectionValidator.php b/src/Symfony/Component/Validator/Constraints/CollectionValidator.php index 731501e08d..cbc3e198a3 100644 --- a/src/Symfony/Component/Validator/Constraints/CollectionValidator.php +++ b/src/Symfony/Component/Validator/Constraints/CollectionValidator.php @@ -51,7 +51,7 @@ class CollectionValidator extends ConstraintValidator foreach ($constraint->fields as $field => $fieldConstraint) { // bug fix issue #2779 - $existsInArray = \is_array($value) && array_key_exists($field, $value); + $existsInArray = \is_array($value) && \array_key_exists($field, $value); $existsInArrayAccess = $value instanceof \ArrayAccess && $value->offsetExists($field); if ($existsInArray || $existsInArrayAccess) { diff --git a/src/Symfony/Component/Validator/Constraints/Email.php b/src/Symfony/Component/Validator/Constraints/Email.php index 7d13eceaf7..c6c760c2c0 100644 --- a/src/Symfony/Component/Validator/Constraints/Email.php +++ b/src/Symfony/Component/Validator/Constraints/Email.php @@ -76,19 +76,19 @@ class Email extends Constraint public function __construct($options = null) { - if (\is_array($options) && array_key_exists('strict', $options)) { + if (\is_array($options) && \array_key_exists('strict', $options)) { @trigger_error(sprintf('The "strict" property is deprecated since Symfony 4.1. Use "mode"=>"%s" instead.', self::VALIDATION_MODE_STRICT), E_USER_DEPRECATED); } - if (\is_array($options) && array_key_exists('checkMX', $options)) { + if (\is_array($options) && \array_key_exists('checkMX', $options)) { @trigger_error('The "checkMX" option is deprecated since Symfony 4.2.', E_USER_DEPRECATED); } - if (\is_array($options) && array_key_exists('checkHost', $options)) { + if (\is_array($options) && \array_key_exists('checkHost', $options)) { @trigger_error('The "checkHost" option is deprecated since Symfony 4.2.', E_USER_DEPRECATED); } - if (\is_array($options) && array_key_exists('mode', $options) && !\in_array($options['mode'], self::$validationModes, true)) { + if (\is_array($options) && \array_key_exists('mode', $options) && !\in_array($options['mode'], self::$validationModes, true)) { throw new \InvalidArgumentException('The "mode" parameter value is not valid.'); } diff --git a/src/Symfony/Component/Validator/Constraints/IbanValidator.php b/src/Symfony/Component/Validator/Constraints/IbanValidator.php index d6530ab101..e927f013aa 100644 --- a/src/Symfony/Component/Validator/Constraints/IbanValidator.php +++ b/src/Symfony/Component/Validator/Constraints/IbanValidator.php @@ -182,7 +182,7 @@ class IbanValidator extends ConstraintValidator } // ...have a format available - if (!array_key_exists($countryCode, self::$formats)) { + if (!\array_key_exists($countryCode, self::$formats)) { $this->context->buildViolation($constraint->message) ->setParameter('{{ value }}', $this->formatValue($value)) ->setCode(Iban::NOT_SUPPORTED_COUNTRY_CODE_ERROR) diff --git a/src/Symfony/Component/Validator/Constraints/LessThanOrEqual.php b/src/Symfony/Component/Validator/Constraints/LessThanOrEqual.php index 74f7aeb8fa..806ca4990f 100644 --- a/src/Symfony/Component/Validator/Constraints/LessThanOrEqual.php +++ b/src/Symfony/Component/Validator/Constraints/LessThanOrEqual.php @@ -20,7 +20,7 @@ namespace Symfony\Component\Validator\Constraints; */ class LessThanOrEqual extends AbstractComparison { - const TOO_HIGH_ERROR = '079d7420-2d13-460c-8756-de810eeb37d2'; + const TOO_HIGH_ERROR = '30fbb013-d015-4232-8b3b-8f3be97a7e14'; protected static $errorNames = [ self::TOO_HIGH_ERROR => 'TOO_HIGH_ERROR', diff --git a/src/Symfony/Component/Validator/Constraints/Regex.php b/src/Symfony/Component/Validator/Constraints/Regex.php index a71e4de259..dc9e5ea885 100644 --- a/src/Symfony/Component/Validator/Constraints/Regex.php +++ b/src/Symfony/Component/Validator/Constraints/Regex.php @@ -79,7 +79,7 @@ class Regex extends Constraint // Unescape the delimiter $pattern = str_replace('\\'.$delimiter, $delimiter, substr($this->pattern, 1, -1)); - // If the pattern is inverted, we can simply wrap it in + // If the pattern is inverted, we can wrap it in // ((?!pattern).)* if (!$this->match) { return '((?!'.$pattern.').)*'; diff --git a/src/Symfony/Component/Validator/Constraints/Traverse.php b/src/Symfony/Component/Validator/Constraints/Traverse.php index 4572c9b219..78d115fdbb 100644 --- a/src/Symfony/Component/Validator/Constraints/Traverse.php +++ b/src/Symfony/Component/Validator/Constraints/Traverse.php @@ -25,7 +25,7 @@ class Traverse extends Constraint public function __construct($options = null) { - if (\is_array($options) && array_key_exists('groups', $options)) { + if (\is_array($options) && \array_key_exists('groups', $options)) { throw new ConstraintDefinitionException(sprintf('The option "groups" is not supported by the constraint %s', __CLASS__)); } diff --git a/src/Symfony/Component/Validator/Constraints/Url.php b/src/Symfony/Component/Validator/Constraints/Url.php index 2a237bffad..815d73be7c 100644 --- a/src/Symfony/Component/Validator/Constraints/Url.php +++ b/src/Symfony/Component/Validator/Constraints/Url.php @@ -109,10 +109,10 @@ class Url extends Constraint public function __construct($options = null) { if (\is_array($options)) { - if (array_key_exists('checkDNS', $options)) { + if (\array_key_exists('checkDNS', $options)) { @trigger_error(sprintf('The "checkDNS" option in "%s" is deprecated since Symfony 4.1. Its false-positive rate is too high to be relied upon.', self::class), E_USER_DEPRECATED); } - if (array_key_exists('dnsMessage', $options)) { + if (\array_key_exists('dnsMessage', $options)) { @trigger_error(sprintf('The "dnsMessage" option in "%s" is deprecated since Symfony 4.1.', self::class), E_USER_DEPRECATED); } } diff --git a/src/Symfony/Component/Validator/Mapping/ClassMetadata.php b/src/Symfony/Component/Validator/Mapping/ClassMetadata.php index afbe72b735..6e0256c290 100644 --- a/src/Symfony/Component/Validator/Mapping/ClassMetadata.php +++ b/src/Symfony/Component/Validator/Mapping/ClassMetadata.php @@ -366,7 +366,7 @@ class ClassMetadata extends GenericMetadata implements ClassMetadataInterface */ public function hasPropertyMetadata($property) { - return array_key_exists($property, $this->members); + return \array_key_exists($property, $this->members); } /** diff --git a/src/Symfony/Component/Validator/Mapping/ClassMetadataInterface.php b/src/Symfony/Component/Validator/Mapping/ClassMetadataInterface.php index e48e241ab8..1b6f07ac8e 100644 --- a/src/Symfony/Component/Validator/Mapping/ClassMetadataInterface.php +++ b/src/Symfony/Component/Validator/Mapping/ClassMetadataInterface.php @@ -86,8 +86,8 @@ interface ClassMetadataInterface extends MetadataInterface /** * Returns all metadata instances for the given named property. * - * If your implementation does not support properties, simply throw an - * exception in this method (for example a BadMethodCallException). + * If your implementation does not support properties, throw an exception + * in this method (for example a BadMethodCallException). * * @param string $property The property name * diff --git a/src/Symfony/Component/Validator/Resources/translations/validators.af.xlf b/src/Symfony/Component/Validator/Resources/translations/validators.af.xlf index 177bb0038f..731e64aa7f 100644 --- a/src/Symfony/Component/Validator/Resources/translations/validators.af.xlf +++ b/src/Symfony/Component/Validator/Resources/translations/validators.af.xlf @@ -222,6 +222,118 @@ Unsupported card type or invalid card number. Nie-ondersteunde tipe kaart of ongeldige kredietkaart nommer. + + This is not a valid International Bank Account Number (IBAN). + Hierdie is nie 'n geldige Internationale Bank Rekening Nommer (IBAN) nie. + + + This value is not a valid ISBN-10. + Hierdie waarde is nie 'n geldige ISBN-10 nie. + + + This value is not a valid ISBN-13. + Hierdie waarde is nie 'n geldige ISBN-13 nie. + + + This value is neither a valid ISBN-10 nor a valid ISBN-13. + Hierdie waarde is nie 'n geldige ISBN-10 of ISBN-13 nie. + + + This value is not a valid ISSN. + Hierdie waarde is nie 'n geldige ISSN nie. + + + This value is not a valid currency. + Hierdie waarde is nie 'n geldige geldeenheid nie. + + + This value should be equal to {{ compared_value }}. + Hierdie waarde moet gelyk aan {{ compared_value }} wees. + + + This value should be greater than {{ compared_value }}. + Hierdie waarde moet meer as {{ compared_value }} wees. + + + This value should be greater than or equal to {{ compared_value }}. + Hierdie waarde moet meer of gelyk aan {{ compared_value }} wees. + + + This value should be identical to {{ compared_value_type }} {{ compared_value }}. + Hierdie waarde moet identies aan {{ compared_value_type }} {{ compared_value }} wees. + + + This value should be less than {{ compared_value }}. + Hierdie waarde moet minder as {{ compared_value }} wees. + + + This value should be less than or equal to {{ compared_value }}. + Hierdie waarde moet minder of gelyk aan {{ compared_value }} wees. + + + This value should not be equal to {{ compared_value }}. + Hierdie waarde moet nie dieselfde as {{ compared_value }} wees nie. + + + This value should not be identical to {{ compared_value_type }} {{ compared_value }}. + Hierdie waarde moet nie identies as {{ compared_value_type }} {{ compared_value }} wees nie. + + + The image ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}. + Die beeld aspek is te groot ({{ ratio }}). Die maksimum toegelate aspek is {{ max_ratio }}. + + + The image ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}. + Die beeld aspek is te klein ({{ ratio }}). Die minimum toegelate aspek is {{ min_ratio }}. + + + The image is square ({{ width }}x{{ height }}px). Square images are not allowed. + Die beeld is vierkantig ({{ width }}x{{ height }}px). Vierkantige beelde word nie toegelaat nie. + + + The image is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented images are not allowed. + Die beeld is landskap georiënteerd ({{ width }}x{{ height }}px). Landskap georiënteerde beelde word nie toegelaat nie. + + + The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed. + Die beeld dis portret georiënteerd ({{ width }}x{{ height }}px). Portret georiënteerde beelde word nie toegelaat nie. + + + An empty file is not allowed. + 'n Leë lêer word nie toegelaat nie. + + + The host could not be resolved. + Die gasheer kon nie opgelos word nie. + + + This value does not match the expected {{ charset }} charset. + Die waarde stem nie ooreen met die verwagte {{ charset }} karakterstel nie. + + + This is not a valid Business Identifier Code (BIC). + Hierdie is nie 'n geldige Besigheids Identifikasie Kode (BIC) nie. + + + Error + Fout + + + This is not a valid UUID. + Hierdie is nie 'n geldige UUID nie. + + + This value should be a multiple of {{ compared_value }}. + Hierdie waarde moet 'n veelvoud van {{ compared_value }} wees. + + + This Business Identifier Code (BIC) is not associated with IBAN {{ iban }}. + Hierdie Besigheids Identifikasie Kode (BIK) is nie geassosieer met IBAN {{ iban }} nie. + + + This value should be valid JSON. + Hierdie waarde moet geldige JSON wees. + diff --git a/src/Symfony/Component/Validator/Resources/translations/validators.el.xlf b/src/Symfony/Component/Validator/Resources/translations/validators.el.xlf index a3199bcc9d..3b9bbef66e 100644 --- a/src/Symfony/Component/Validator/Resources/translations/validators.el.xlf +++ b/src/Symfony/Component/Validator/Resources/translations/validators.el.xlf @@ -278,6 +278,58 @@ This value should not be identical to {{ compared_value_type }} {{ compared_value }}. Αυτή η τιμή δεν πρέπει να είναι πανομοιότυπη με {{ compared_value_type }} {{ compared_value }}. + + The image ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}. + Η αναλογία πλάτους-ύψους της εικόνας είναι πολύ μεγάλη ({{ ratio }}). Μέγιστη επιτρεπτή αναλογία {{ max_ratio }}. + + + The image ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}. + Η αναλογία πλάτους-ύψους της εικόνας είναι πολύ μικρή ({{ ratio }}). Ελάχιστη επιτρεπτή αναλογία {{ min_ratio }}. + + + The image is square ({{ width }}x{{ height }}px). Square images are not allowed. + Η εικόνα είναι τετράγωνη ({{ width }}x{{ height }}px). Δεν επιτρέπονται τετράγωνες εικόνες. + + + The image is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented images are not allowed. + Η εικόνα έχει οριζόντιο προσανατολισμό ({{ width }}x{{ height }}px). Δεν επιτρέπονται εικόνες με οριζόντιο προσανατολισμό. + + + The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed. + Η εικόνα έχει κάθετο προσανατολισμό ({{ width }}x{{ height }}px). Δεν επιτρέπονται εικόνες με κάθετο προσανατολισμό. + + + An empty file is not allowed. + Δεν επιτρέπεται κενό αρχείο. + + + The host could not be resolved. + Η διεύθυνση δεν μπόρεσε να επιλυθεί. + + + This value does not match the expected {{ charset }} charset. + Αυτή η τιμή δεν ταιριάζει στο αναμενόμενο {{ charset }} σύνολο χαρακτήρων. + + + This is not a valid Business Identifier Code (BIC). + Αυτός δεν έιναι ένας έγκυρος κωδικός BIC. + + + Error + Σφάλμα + + + This is not a valid UUID. + Αυτό δεν είναι ένα έγκυρο UUID. + + + This value should be a multiple of {{ compared_value }}. + Αυτή η τιμή θα έπρεπε να είναι πολλαπλάσιο του {{ compared_value }}. + + + This Business Identifier Code (BIC) is not associated with IBAN {{ iban }}. + Αυτός ο κωδικός BIC δεν σχετίζεται με το IBAN {{ iban }}. + diff --git a/src/Symfony/Component/Validator/Resources/translations/validators.hr.xlf b/src/Symfony/Component/Validator/Resources/translations/validators.hr.xlf index 126ef90332..ab033a11c3 100644 --- a/src/Symfony/Component/Validator/Resources/translations/validators.hr.xlf +++ b/src/Symfony/Component/Validator/Resources/translations/validators.hr.xlf @@ -318,6 +318,22 @@ Error Greška + + This is not a valid UUID. + Ovo nije validan UUID. + + + This value should be a multiple of {{ compared_value }}. + Ova vrijednost treba biti višekratnik od {{ compared_value }}. + + + This Business Identifier Code (BIC) is not associated with IBAN {{ iban }}. + Poslovni identifikacijski broj (BIC) nije povezan sa IBAN brojem {{ iban }}. + + + This value should be valid JSON. + Ova vrijednost treba biti validan JSON. + diff --git a/src/Symfony/Component/Validator/Resources/translations/validators.pt_BR.xlf b/src/Symfony/Component/Validator/Resources/translations/validators.pt_BR.xlf index b617062318..8616edf4b9 100644 --- a/src/Symfony/Component/Validator/Resources/translations/validators.pt_BR.xlf +++ b/src/Symfony/Component/Validator/Resources/translations/validators.pt_BR.xlf @@ -314,6 +314,26 @@ This is not a valid Business Identifier Code (BIC). Este não é um Código Identificador Bancário (BIC) válido. + + Error + Erro + + + This is not a valid UUID. + Este não é um UUID válido. + + + This value should be a multiple of {{ compared_value }}. + Este valor deve ser múltiplo de {{ compared_value }}. + + + This Business Identifier Code (BIC) is not associated with IBAN {{ iban }}. + Este Código Identificador Bancário (BIC) não está associado ao IBAN {{ iban }}. + + + This value should be valid JSON. + Este valor deve ser um JSON válido. + diff --git a/src/Symfony/Component/Validator/Tests/Fixtures/CustomArrayObject.php b/src/Symfony/Component/Validator/Tests/Fixtures/CustomArrayObject.php index ac48a512c6..1edf1de081 100644 --- a/src/Symfony/Component/Validator/Tests/Fixtures/CustomArrayObject.php +++ b/src/Symfony/Component/Validator/Tests/Fixtures/CustomArrayObject.php @@ -26,7 +26,7 @@ class CustomArrayObject implements \ArrayAccess, \IteratorAggregate, \Countable, public function offsetExists($offset) { - return array_key_exists($offset, $this->array); + return \array_key_exists($offset, $this->array); } public function offsetGet($offset) diff --git a/src/Symfony/Component/VarDumper/Caster/DoctrineCaster.php b/src/Symfony/Component/VarDumper/Caster/DoctrineCaster.php index 6adf9dd837..696b87816e 100644 --- a/src/Symfony/Component/VarDumper/Caster/DoctrineCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/DoctrineCaster.php @@ -26,7 +26,7 @@ class DoctrineCaster public static function castCommonProxy(CommonProxy $proxy, array $a, Stub $stub, $isNested) { foreach (['__cloner__', '__initializer__'] as $k) { - if (array_key_exists($k, $a)) { + if (\array_key_exists($k, $a)) { unset($a[$k]); ++$stub->cut; } @@ -38,7 +38,7 @@ class DoctrineCaster public static function castOrmProxy(OrmProxy $proxy, array $a, Stub $stub, $isNested) { foreach (['_entityPersister', '_identifier'] as $k) { - if (array_key_exists($k = "\0Doctrine\\ORM\\Proxy\\Proxy\0".$k, $a)) { + if (\array_key_exists($k = "\0Doctrine\\ORM\\Proxy\\Proxy\0".$k, $a)) { unset($a[$k]); ++$stub->cut; } @@ -50,7 +50,7 @@ class DoctrineCaster public static function castPersistentCollection(PersistentCollection $coll, array $a, Stub $stub, $isNested) { foreach (['snapshot', 'association', 'typeClass'] as $k) { - if (array_key_exists($k = "\0Doctrine\\ORM\\PersistentCollection\0".$k, $a)) { + if (\array_key_exists($k = "\0Doctrine\\ORM\\PersistentCollection\0".$k, $a)) { $a[$k] = new CutStub($a[$k]); } } diff --git a/src/Symfony/Component/VarDumper/Cloner/Data.php b/src/Symfony/Component/VarDumper/Cloner/Data.php index 92a6f41cdd..838aeb0c6a 100644 --- a/src/Symfony/Component/VarDumper/Cloner/Data.php +++ b/src/Symfony/Component/VarDumper/Cloner/Data.php @@ -245,7 +245,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate $children = $this->data[$item->position]; foreach ($keys as $key) { - if (isset($children[$key]) || array_key_exists($key, $children)) { + if (isset($children[$key]) || \array_key_exists($key, $children)) { $data = clone $this; $data->key = $key; $data->position = $item->position; diff --git a/src/Symfony/Component/VarDumper/Cloner/VarCloner.php b/src/Symfony/Component/VarDumper/Cloner/VarCloner.php index a50adef9f5..b8318c514f 100644 --- a/src/Symfony/Component/VarDumper/Cloner/VarCloner.php +++ b/src/Symfony/Component/VarDumper/Cloner/VarCloner.php @@ -31,6 +31,7 @@ class VarCloner extends AbstractCloner $indexedArrays = []; // Map of queue indexes that hold numerically indexed arrays $hardRefs = []; // Map of original zval ids to stub objects $objRefs = []; // Map of original object handles to their stub object counterpart + $objects = []; // Keep a ref to objects to ensure their handle cannot be reused while cloning $resRefs = []; // Map of original resource handles to their stub object counterpart $values = []; // Map of stub objects' ids to original values $maxItems = $this->maxItems; @@ -193,6 +194,7 @@ class VarCloner extends AbstractCloner } if (empty($objRefs[$h])) { $objRefs[$h] = $stub; + $objects[] = $v; } else { $stub = $objRefs[$h]; ++$stub->refCount; diff --git a/src/Symfony/Component/Workflow/DependencyInjection/ValidateWorkflowsPass.php b/src/Symfony/Component/Workflow/DependencyInjection/ValidateWorkflowsPass.php index b4e222d335..175a1f5b96 100644 --- a/src/Symfony/Component/Workflow/DependencyInjection/ValidateWorkflowsPass.php +++ b/src/Symfony/Component/Workflow/DependencyInjection/ValidateWorkflowsPass.php @@ -34,13 +34,13 @@ class ValidateWorkflowsPass implements CompilerPassInterface $taggedServices = $container->findTaggedServiceIds($this->definitionTag, true); foreach ($taggedServices as $id => $tags) { foreach ($tags as $tag) { - if (!array_key_exists('name', $tag)) { + if (!\array_key_exists('name', $tag)) { throw new RuntimeException(sprintf('The "name" for the tag "%s" of service "%s" must be set.', $this->definitionTag, $id)); } - if (!array_key_exists('type', $tag)) { + if (!\array_key_exists('type', $tag)) { throw new RuntimeException(sprintf('The "type" for the tag "%s" of service "%s" must be set.', $this->definitionTag, $id)); } - if (!array_key_exists('marking_store', $tag)) { + if (!\array_key_exists('marking_store', $tag)) { throw new RuntimeException(sprintf('The "marking_store" for the tag "%s" of service "%s" must be set.', $this->definitionTag, $id)); } diff --git a/src/Symfony/Component/Workflow/Tests/Validator/StateMachineValidatorTest.php b/src/Symfony/Component/Workflow/Tests/Validator/StateMachineValidatorTest.php index c43292899b..4e34456055 100644 --- a/src/Symfony/Component/Workflow/Tests/Validator/StateMachineValidatorTest.php +++ b/src/Symfony/Component/Workflow/Tests/Validator/StateMachineValidatorTest.php @@ -94,7 +94,7 @@ class StateMachineValidatorTest extends TestCase (new StateMachineValidator())->validate($definition, 'foo'); - // the test simply ensures that the validation does not fail (i.e. it does not throw any exceptions) + // the test ensures that the validation does not fail (i.e. it does not throw any exceptions) $this->addToAssertionCount(1); // The graph looks like: diff --git a/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php b/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php index cdf10ecdab..4a5c5a57dd 100644 --- a/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php +++ b/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php @@ -29,7 +29,7 @@ class WorkflowValidatorTest extends TestCase (new WorkflowValidator(true))->validate($definition, 'foo'); - // the test simply ensures that the validation does not fail (i.e. it does not throw any exceptions) + // the test ensures that the validation does not fail (i.e. it does not throw any exceptions) $this->addToAssertionCount(1); } @@ -64,7 +64,7 @@ class WorkflowValidatorTest extends TestCase (new WorkflowValidator())->validate($definition, 'foo'); - // the test simply ensures that the validation does not fail (i.e. it does not throw any exceptions) + // the test ensures that the validation does not fail (i.e. it does not throw any exceptions) $this->addToAssertionCount(1); } } diff --git a/src/Symfony/Component/Yaml/Inline.php b/src/Symfony/Component/Yaml/Inline.php index 1619b3183a..4b12b9b11a 100644 --- a/src/Symfony/Component/Yaml/Inline.php +++ b/src/Symfony/Component/Yaml/Inline.php @@ -555,7 +555,7 @@ class Inline throw new ParseException('A reference must contain at least one character.', self::$parsedLineNumber + 1, $value, self::$parsedFilename); } - if (!array_key_exists($value, $references)) { + if (!\array_key_exists($value, $references)) { throw new ParseException(sprintf('Reference "%s" does not exist.', $value), self::$parsedLineNumber + 1, $value, self::$parsedFilename); } diff --git a/src/Symfony/Component/Yaml/Parser.php b/src/Symfony/Component/Yaml/Parser.php index 04b00d9870..4519edb840 100644 --- a/src/Symfony/Component/Yaml/Parser.php +++ b/src/Symfony/Component/Yaml/Parser.php @@ -237,7 +237,7 @@ class Parser $allowOverwrite = true; if (isset($values['value'][0]) && '*' === $values['value'][0]) { $refName = substr(rtrim($values['value']), 1); - if (!array_key_exists($refName, $this->refs)) { + if (!\array_key_exists($refName, $this->refs)) { if (false !== $pos = array_search($refName, $this->refsBeingParsed, true)) { throw new ParseException(sprintf('Circular reference [%s, %s] detected for reference "%s".', implode(', ', \array_slice($this->refsBeingParsed, $pos)), $refName, $refName), $this->currentLineNb + 1, $this->currentLine, $this->filename); } @@ -653,7 +653,7 @@ class Parser $value = substr($value, 1); } - if (!array_key_exists($value, $this->refs)) { + if (!\array_key_exists($value, $this->refs)) { if (false !== $pos = array_search($value, $this->refsBeingParsed, true)) { throw new ParseException(sprintf('Circular reference [%s, %s] detected for reference "%s".', implode(', ', \array_slice($this->refsBeingParsed, $pos)), $value, $value), $this->currentLineNb + 1, $this->currentLine, $this->filename); }