diff --git a/.php_cs.dist b/.php_cs.dist index 3f0e86f4c38d..0fd2436e791f 100644 --- a/.php_cs.dist +++ b/.php_cs.dist @@ -13,6 +13,7 @@ return PhpCsFixer\Config::create() 'array_syntax' => ['syntax' => 'short'], 'fopen_flags' => false, 'protected_to_private' => false, + 'native_constant_invocation' => true, 'combine_nested_dirname' => true, ]) ->setRiskyAllowed(true) diff --git a/.travis.yml b/.travis.yml index cbf4eee7dd1f..75568167b31f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -183,7 +183,7 @@ before_install: tfold ext.redis tpecl redis-5.2.2 redis.so $INI "no" fi - tfold ext.igbinary tpecl igbinary-3.1.2 igbinary.so $INI + tfold ext.igbinary tpecl igbinary-3.1.5 igbinary.so $INI done - | # List all php extensions with versions diff --git a/CHANGELOG-4.4.md b/CHANGELOG-4.4.md index ce1903a9587b..2c30e0de97e6 100644 --- a/CHANGELOG-4.4.md +++ b/CHANGELOG-4.4.md @@ -7,6 +7,15 @@ in 4.4 minor versions. To get the diff for a specific change, go to https://github.com/symfony/symfony/commit/XXX where XXX is the change hash To get the diff between two versions, go to https://github.com/symfony/symfony/compare/v4.4.0...v4.4.1 +* 4.4.13 (2020-09-02) + + * security #cve-2020-15094 Remove headers with internal meaning from HttpClient responses (mpdude) + * bug #38024 [Console] Fix undefined index for inconsistent command name definition (chalasr) + * bug #38023 [DI] fix inlining of non-shared services (nicolas-grekas) + * bug #38020 [PhpUnitBridge] swallow deprecations (xabbuh) + * bug #38010 [Cache] Psr16Cache does not handle Proxy cache items (alex-dev) + * bug #37937 [Serializer] fixed fix encoding of cache keys with anonymous classes (michaelzangerle) + * 4.4.12 (2020-08-31) * bug #37966 [HttpClient][MockHttpClient][DX] Throw when the response factory callable does not return a valid response (fancyweb) diff --git a/CHANGELOG-5.1.md b/CHANGELOG-5.1.md index cae872acb5e5..ba3d7459092f 100644 --- a/CHANGELOG-5.1.md +++ b/CHANGELOG-5.1.md @@ -7,6 +7,66 @@ in 5.1 minor versions. To get the diff for a specific change, go to https://github.com/symfony/symfony/commit/XXX where XXX is the change hash To get the diff between two versions, go to https://github.com/symfony/symfony/compare/v5.1.0...v5.1.1 +* 5.1.6 (2020-09-27) + + * bug #38291 [OptionsResolver] Fix deprecation message access (fancyweb) + * bug #38248 [HttpClient] Allow bearer token with colon (stephanvierkant) + * bug #37837 [Form] Fix custom formats deprecation with HTML5 widgets (fancyweb) + * bug #38285 [Contracts][Translation] Optional Intl dependency (ro0NL) + * bug #38283 [Translator] Optional Intl dependency (ro0NL) + * bug #38271 [ErrorHandler] Escape JSON encoded log context (ro0NL) + * bug #38284 [Cache][Lock][Messenger] fix compatibility with Doctrine DBAL 3 (xabbuh) + * bug #38228 [Yaml Parser] Fix edge cases when parsing multiple documents (digilist) + * bug #38226 [FrameworkBundle] loadRoutes shoud receive RoutingPhpFileLoader (grachevko) + * bug #38229 [Yaml] fix parsing comments not prefixed by a space (xabbuh) + * bug #38127 [Translator] Make sure a null locale is handled properly (jschaedl) + * bug #38221 [Cache] Allow cache tags to be objects implementing __toString() (lstrojny) + * bug #38212 [HttpKernel] Do not override max_redirects option in HttpClientKernel (dmolineus) + * bug #38215 [HttpClient] Support for CURLOPT_LOCALPORT (derrabus) + * bug #38202 [FrameworkBundle] Fix xsd definition which prevent to add more than one workflow metadata (l-vo) + * bug #38195 [String] improve slugger's portability accross implementations of iconv() (nicolas-grekas) + * bug #38166 [Console] work around disabled putenv() (SenTisso) + * bug #38190 [Notifier] Fix errors parsing in FirebaseTransport (jderusse) + * bug #38173 [HttpClient][HttpClientTrait] don't calculate alternatives if option is auth_ntlm (ybenhssaien) + * bug #38169 [PhpUnitBridge] Internal classes are not legacy (derrabus) + * feature #38160 [Security] In the new authenticator system, no auth listener is valid (weaverryan) + * bug #38156 [Cache] fix ProxyAdapter not persisting items with infinite expiration (dmaicher) + * bug #38148 [HttpClient] fail properly when the server replies with HTTP/0.9 (nicolas-grekas) + * bug #38131 [Validator] allow consumers to mock all methods (xabbuh) + * bug #38140 [DI] dump OS-indepent paths in the preload file (nicolas-grekas) + * bug #38139 [DI] dump OS-indepent paths in the compiled container (nicolas-grekas) + * bug #38147 [Mailer] Fixed Mailgun API bridge JsonException when API response is not applicaton/json (asprega) + * bug #38126 [Cache] Limit cache version character range (lstrojny) + * bug #38136 [Messenger] Run postgres setup trigger in transaction (akondas) + * bug #38142 [FrameworkBundle] adopt src/.preload.php (nicolas-grekas) + * bug #38108 [Cache] Fix key encoding issue in Memcached adapter (lstrojny) + * bug #38122 [HttpClient] Fix Array to string conversion notice when parsing JSON error body with non-scalar detail property (emarref) + * bug #37097 DateTime validator support for trailing data (stefankleff) + * bug #38116 [Console] Silence warnings on sapi_windows_cp_set() call (chalasr) + * bug #38114 [Console] guard $argv + $token against null, preventing unnecessary exceptions (bilogic) + * bug #38094 [PhpUnitBridge] Skip internal classes in CoverageListenerTrait (sanmai) + * bug #38101 [VarExporter] unserialize() might throw an Exception on php 8 (derrabus) + * bug #38100 [ErrorHandler] Parse "x not found" errors correctly on php 8 (derrabus) + * bug #38099 Prevent parsing invalid octal digits as octal numbers (julienfalque) + * bug #38095 [Mailer] Remove unnecessary check for existing request (jschaedl) + * bug #38091 [DI] fix ContainerBuilder on PHP8 (nicolas-grekas) + * bug #38086 [HttpClient] with "bindto" with NativeHttpClient (nicolas-grekas) + * bug #38063 [FrameworkBundle] generate preload.php in src/ to make opcache.preload predictable (nicolas-grekas) + * bug #38080 [Console] Make sure $maxAttempts is an int or null (derrabus) + * bug #38075 esmtp error not being thrown properly (Anton Zagorskii) + * bug #38040 [Yaml Parser] fixed Parser to skip comments when inlining sequences (korve) + * bug #38073 [VarDumper] Fix caster for invalid SplFileInfo objects on php 8 (derrabus) + * bug #38074 [Messenger] Remove DelaySeconds parameter for FIFO queues (netbull) + * bug #38071 [PhpUnitBridge] Adjust output parsing of CoverageListenerTrait for PHPUnit 9.3 (sanmai, derrabus) + * bug #38062 [DI] fix generating preload file when cache_dir is outside project_dir (nicolas-grekas) + * bug #38059 [Cache] Fix CacheCollectorPass with decorated cache pools (shyim) + * bug #38054 [PhpUnitBridge] CoverageListenerTrait update for PHPUnit 8.5/9.x (sanmai) + * bug #38049 [Debug] Parse "x not found" errors correctly on php 8 (derrabus) + * bug #38041 [PropertyInfo] Fix typed collections in PHP 7.4 (ndench) + * bug #38013 [PHPUnitBridge] Fix deprecation type detection when trigger_deprecation is used (l-vo) + * bug #37959 [PhpunitBridge] Fix deprecation type detection (when several autoload files are used) (l-vo) + * bug #38031 Allow Drupal to wrap the Symfony test listener (5.1 backport) (fabpot, alexpott) + * 5.1.5 (2020-09-02) * security #cve-2020-15094 Remove headers with internal meaning from HttpClient responses (mpdude) diff --git a/UPGRADE-5.1.md b/UPGRADE-5.1.md index a0560277ab12..3143e173bd05 100644 --- a/UPGRADE-5.1.md +++ b/UPGRADE-5.1.md @@ -4,8 +4,8 @@ UPGRADE FROM 5.0 to 5.1 Config ------ - * The signature of method `NodeDefinition::setDeprecated()` has been updated to `NodeDefinition::setDeprecation(string $package, string $version, string $message)`. - * The signature of method `BaseNode::setDeprecated()` has been updated to `BaseNode::setDeprecation(string $package, string $version, string $message)`. + * The signature of method `NodeDefinition::setDeprecated()` has been updated to `NodeDefinition::setDeprecated(string $package, string $version, string $message)`. + * The signature of method `BaseNode::setDeprecated()` has been updated to `BaseNode::setDeprecated(string $package, string $version, string $message)`. * Passing a null message to `BaseNode::setDeprecated()` to un-deprecate a node is deprecated * Deprecated `BaseNode::getDeprecationMessage()`, use `BaseNode::getDeprecation()` instead diff --git a/phpunit b/phpunit index 2b4412dc4d4f..e1b1aea0e46c 100755 --- a/phpunit +++ b/phpunit @@ -12,10 +12,10 @@ if (!getenv('SYMFONY_PHPUNIT_VERSION')) { if (false === getenv('SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT') && false !== strpos(@file_get_contents(__DIR__.'/src/Symfony/Component/HttpKernel/Kernel.php'), 'const MAJOR_VERSION = 3;')) { putenv('SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT=1'); } - if (\PHP_VERSION_ID >= 80000) { - putenv('SYMFONY_PHPUNIT_VERSION=9.3'); + if (\PHP_VERSION_ID < 70300) { + putenv('SYMFONY_PHPUNIT_VERSION=8.5'); } else { - putenv('SYMFONY_PHPUNIT_VERSION=8.3'); + putenv('SYMFONY_PHPUNIT_VERSION=9.3'); } } elseif (\PHP_VERSION_ID >= 70000) { putenv('SYMFONY_PHPUNIT_VERSION=6.5'); diff --git a/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php b/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php index 0a50e9d48bc3..ac4c5f68d4d1 100644 --- a/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php +++ b/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php @@ -242,11 +242,11 @@ protected function detectMetadataDriver(string $dir, ContainerBuilder $container $configPath = $this->getMappingResourceConfigDirectory(); $extension = $this->getMappingResourceExtension(); - if (glob($dir.'/'.$configPath.'/*.'.$extension.'.xml', GLOB_NOSORT)) { + if (glob($dir.'/'.$configPath.'/*.'.$extension.'.xml', \GLOB_NOSORT)) { $driver = 'xml'; - } elseif (glob($dir.'/'.$configPath.'/*.'.$extension.'.yml', GLOB_NOSORT)) { + } elseif (glob($dir.'/'.$configPath.'/*.'.$extension.'.yml', \GLOB_NOSORT)) { $driver = 'yml'; - } elseif (glob($dir.'/'.$configPath.'/*.'.$extension.'.php', GLOB_NOSORT)) { + } elseif (glob($dir.'/'.$configPath.'/*.'.$extension.'.php', \GLOB_NOSORT)) { $driver = 'php'; } else { // add the closest existing directory as a resource diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php index 0b0c62bff223..8d106ca53d2a 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php @@ -137,6 +137,39 @@ public function testInvalidClassOption() ]); } + /** + * @dataProvider choiceTranslationDomainProvider + */ + public function testChoiceTranslationDomainIsDisabledByDefault($expanded) + { + $entity1 = new SingleIntIdEntity(1, 'Foo'); + + $this->persist([$entity1]); + + $field = $this->factory->createNamed('name', static::TESTED_TYPE, null, [ + 'choices' => [ + $entity1, + ], + 'class' => SingleIntIdEntity::class, + 'em' => 'default', + 'expanded' => $expanded, + ]); + + if ($expanded) { + $this->assertFalse($field->get('1')->getConfig()->getOption('translation_domain')); + } else { + $this->assertFalse($field->getConfig()->getOption('choice_translation_domain')); + } + } + + public function choiceTranslationDomainProvider() + { + return [ + [false], + [true], + ]; + } + public function testSetDataToUninitializedEntityWithNonRequired() { $entity1 = new SingleIntIdEntity(1, 'Foo'); diff --git a/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php b/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php index cb809abbafd6..257c6f7a93fb 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php @@ -70,7 +70,7 @@ public function testLoadUserByUsernameWithUserLoaderRepositoryAndWithoutProperty { $user = new User(1, 1, 'user1'); - $repository = $this->createMock([ObjectRepository::class, UserLoaderInterface::class]); + $repository = $this->createMock(UserLoaderRepository::class); $repository ->expects($this->once()) ->method('loadUserByUsername') @@ -156,7 +156,7 @@ public function testSupportProxy() public function testLoadUserByUserNameShouldLoadUserWhenProperInterfaceProvided() { - $repository = $this->createMock([ObjectRepository::class, UserLoaderInterface::class]); + $repository = $this->createMock(UserLoaderRepository::class); $repository->expects($this->once()) ->method('loadUserByUsername') ->with('name') @@ -189,7 +189,7 @@ public function testPasswordUpgrades() { $user = new User(1, 1, 'user1'); - $repository = $this->createMock([interface_exists(ObjectRepository::class) ? ObjectRepository::class : LegacyObjectRepository::class, PasswordUpgraderInterface::class]); + $repository = $this->createMock(PasswordUpgraderRepository::class); $repository->expects($this->once()) ->method('upgradePassword') ->with($user, 'foobar'); @@ -233,3 +233,11 @@ private function createSchema($em) ]); } } + +abstract class UserLoaderRepository implements ObjectRepository, UserLoaderInterface +{ +} + +abstract class PasswordUpgraderRepository implements ObjectRepository, PasswordUpgraderInterface +{ +} diff --git a/src/Symfony/Bridge/Doctrine/composer.json b/src/Symfony/Bridge/Doctrine/composer.json index b12d62110577..1e05d0a55966 100644 --- a/src/Symfony/Bridge/Doctrine/composer.json +++ b/src/Symfony/Bridge/Doctrine/composer.json @@ -30,7 +30,7 @@ "symfony/cache": "^5.1", "symfony/config": "^4.4|^5.0", "symfony/dependency-injection": "^4.4|^5.0", - "symfony/form": "^5.1", + "symfony/form": "^5.1.3", "symfony/http-kernel": "^5.0", "symfony/messenger": "^4.4|^5.0", "symfony/doctrine-messenger": "^5.1", diff --git a/src/Symfony/Bridge/Monolog/Handler/ServerLogHandler.php b/src/Symfony/Bridge/Monolog/Handler/ServerLogHandler.php index d6d0c5dabfbe..056b4ab9a9bb 100644 --- a/src/Symfony/Bridge/Monolog/Handler/ServerLogHandler.php +++ b/src/Symfony/Bridge/Monolog/Handler/ServerLogHandler.php @@ -99,7 +99,7 @@ protected function write(array $record): void try { if (-1 === stream_socket_sendto($this->socket, $recordFormatted)) { - stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR); + stream_socket_shutdown($this->socket, \STREAM_SHUT_RDWR); // Let's retry: the persistent connection might just be stale if ($this->socket = $this->createSocket()) { @@ -125,7 +125,7 @@ private static function nullErrorHandler() private function createSocket() { - $socket = stream_socket_client($this->host, $errno, $errstr, 0, STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT | STREAM_CLIENT_PERSISTENT, $this->context); + $socket = stream_socket_client($this->host, $errno, $errstr, 0, \STREAM_CLIENT_CONNECT | \STREAM_CLIENT_ASYNC_CONNECT | \STREAM_CLIENT_PERSISTENT, $this->context); if ($socket) { stream_set_blocking($socket, false); diff --git a/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler.php b/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler.php index ed77d1417b47..b17c4bfc88b3 100644 --- a/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler.php +++ b/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler.php @@ -88,7 +88,7 @@ public static function collectDeprecations($outputFile) { $deprecations = []; $previousErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = []) use (&$deprecations, &$previousErrorHandler) { - if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type && (E_WARNING !== $type || false === strpos($msg, '" targeting switch is equivalent to "break'))) { + if (\E_USER_DEPRECATED !== $type && \E_DEPRECATED !== $type && (\E_WARNING !== $type || false === strpos($msg, '" targeting switch is equivalent to "break'))) { if ($previousErrorHandler) { return $previousErrorHandler($type, $msg, $file, $line, $context); } @@ -120,7 +120,7 @@ public static function collectDeprecations($outputFile) */ public function handleError($type, $msg, $file, $line, $context = []) { - if ((E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type && (E_WARNING !== $type || false === strpos($msg, '" targeting switch is equivalent to "break'))) || !$this->getConfiguration()->isEnabled()) { + if ((\E_USER_DEPRECATED !== $type && \E_DEPRECATED !== $type && (\E_WARNING !== $type || false === strpos($msg, '" targeting switch is equivalent to "break'))) || !$this->getConfiguration()->isEnabled()) { return \call_user_func(self::getPhpUnitErrorHandler(), $type, $msg, $file, $line, $context); } @@ -336,7 +336,7 @@ private static function getPhpUnitErrorHandler() return 'PHPUnit\Util\ErrorHandler::handleError'; } - foreach (debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS) as $frame) { + foreach (debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS) as $frame) { if (isset($frame['object']) && $frame['object'] instanceof TestResult) { return new ErrorHandler( $frame['object']->getConvertDeprecationsToExceptions(), @@ -375,21 +375,21 @@ private static function hasColorSupport() if (\DIRECTORY_SEPARATOR === '\\') { return (\function_exists('sapi_windows_vt100_support') - && sapi_windows_vt100_support(STDOUT)) + && sapi_windows_vt100_support(\STDOUT)) || false !== getenv('ANSICON') || 'ON' === getenv('ConEmuANSI') || 'xterm' === getenv('TERM'); } if (\function_exists('stream_isatty')) { - return stream_isatty(STDOUT); + return stream_isatty(\STDOUT); } if (\function_exists('posix_isatty')) { - return posix_isatty(STDOUT); + return posix_isatty(\STDOUT); } - $stat = fstat(STDOUT); + $stat = fstat(\STDOUT); // Check if formatted mode is S_IFCHR return $stat ? 0020000 === ($stat['mode'] & 0170000) : false; diff --git a/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler/Deprecation.php b/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler/Deprecation.php index daab2d2ad57a..54d7b216c29b 100644 --- a/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler/Deprecation.php +++ b/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler/Deprecation.php @@ -12,7 +12,6 @@ namespace Symfony\Bridge\PhpUnit\DeprecationErrorHandler; use PHPUnit\Util\Test; -use Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerFor; /** * @internal @@ -52,19 +51,24 @@ class Deprecation */ public function __construct($message, array $trace, $file) { + if (isset($trace[2]['function']) && 'trigger_deprecation' === $trace[2]['function']) { + $file = $trace[2]['file']; + array_splice($trace, 1, 1); + } + $this->trace = $trace; $this->message = $message; - $i = \count($trace); - while (1 < $i && $this->lineShouldBeSkipped($trace[--$i])) { + $i = \count($this->trace); + while (1 < $i && $this->lineShouldBeSkipped($this->trace[--$i])) { // No-op } - $line = $trace[$i]; + $line = $this->trace[$i]; $this->triggeringFile = $file; if (isset($line['object']) || isset($line['class'])) { - if (isset($line['class']) && 0 === strpos($line['class'], SymfonyTestsListenerFor::class)) { - set_error_handler(function () {}); - $parsedMsg = unserialize($this->message); - restore_error_handler(); + set_error_handler(function () {}); + $parsedMsg = unserialize($this->message); + restore_error_handler(); + if ($parsedMsg && isset($parsedMsg['deprecation'])) { $this->message = $parsedMsg['deprecation']; $this->originClass = $parsedMsg['class']; $this->originMethod = $parsedMsg['method']; @@ -143,6 +147,10 @@ public function getMessage() public function isLegacy() { $class = $this->originatingClass(); + if ((new \ReflectionClass($class))->isInternal()) { + return false; + } + $method = $this->originatingMethod(); return 0 === strpos($method, 'testLegacy') @@ -266,7 +274,10 @@ private static function getVendors() if (file_exists($v.'/composer/installed.json')) { self::$vendors[] = $v; $loader = require $v.'/autoload.php'; - $paths = self::getSourcePathsFromPrefixes(array_merge($loader->getPrefixes(), $loader->getPrefixesPsr4())); + $paths = self::addSourcePathsFromPrefixes( + array_merge($loader->getPrefixes(), $loader->getPrefixesPsr4()), + $paths + ); } } } @@ -282,15 +293,17 @@ private static function getVendors() return self::$vendors; } - private static function getSourcePathsFromPrefixes(array $prefixesByNamespace) + private static function addSourcePathsFromPrefixes(array $prefixesByNamespace, array $paths) { foreach ($prefixesByNamespace as $prefixes) { foreach ($prefixes as $prefix) { if (false !== realpath($prefix)) { - yield realpath($prefix); + $paths[] = realpath($prefix); } } } + + return $paths; } /** diff --git a/src/Symfony/Bridge/PhpUnit/Legacy/CoverageListenerTrait.php b/src/Symfony/Bridge/PhpUnit/Legacy/CoverageListenerTrait.php index 2bc6de070587..c1b276cea22d 100644 --- a/src/Symfony/Bridge/PhpUnit/Legacy/CoverageListenerTrait.php +++ b/src/Symfony/Bridge/PhpUnit/Legacy/CoverageListenerTrait.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use PHPUnit\Framework\Warning; +use PHPUnit\Util\Annotation\Registry; use PHPUnit\Util\Test; /** @@ -66,9 +67,6 @@ public function startTest($test) return; } - $r = new \ReflectionProperty(Test::class, 'annotationCache'); - $r->setAccessible(true); - $covers = $sutFqcn; if (!\is_array($sutFqcn)) { $covers = [$sutFqcn]; @@ -78,15 +76,49 @@ public function startTest($test) } } + if (class_exists(Registry::class)) { + $this->addCoversForDocBlockInsideRegistry($test, $covers); + + return; + } + + $this->addCoversForClassToAnnotationCache($test, $covers); + } + + private function addCoversForClassToAnnotationCache($test, $covers) + { + $r = new \ReflectionProperty(Test::class, 'annotationCache'); + $r->setAccessible(true); + $cache = $r->getValue(); $cache = array_replace_recursive($cache, [ \get_class($test) => [ 'covers' => $covers, ], ]); + $r->setValue(Test::class, $cache); } + private function addCoversForDocBlockInsideRegistry($test, $covers) + { + $docBlock = Registry::getInstance()->forClassName(\get_class($test)); + + $symbolAnnotations = new \ReflectionProperty($docBlock, 'symbolAnnotations'); + $symbolAnnotations->setAccessible(true); + + // Exclude internal classes; PHPUnit 9.1+ is picky about tests covering, say, a \RuntimeException + $covers = array_filter($covers, function ($class) { + $reflector = new \ReflectionClass($class); + + return $reflector->isUserDefined(); + }); + + $symbolAnnotations->setValue($docBlock, array_replace($docBlock->symbolAnnotations(), [ + 'covers' => $covers, + ])); + } + private function findSutFqcn($test) { if ($this->sutFqcnResolver) { diff --git a/src/Symfony/Bridge/PhpUnit/Tests/CoverageListenerTest.php b/src/Symfony/Bridge/PhpUnit/Tests/CoverageListenerTest.php index 7aae33bbad4b..53b2bb8d6cdf 100644 --- a/src/Symfony/Bridge/PhpUnit/Tests/CoverageListenerTest.php +++ b/src/Symfony/Bridge/PhpUnit/Tests/CoverageListenerTest.php @@ -27,13 +27,19 @@ public function test() $dir = __DIR__.'/../Tests/Fixtures/coverage'; $phpunit = $_SERVER['argv'][0]; - exec("$php $phpunit -c $dir/phpunit-without-listener.xml.dist $dir/tests/ --coverage-text 2> /dev/null", $output); + exec("$php $phpunit -c $dir/phpunit-without-listener.xml.dist $dir/tests/ --coverage-text --colors=never 2> /dev/null", $output); $output = implode("\n", $output); - $this->assertStringContainsString('FooCov', $output); + $this->assertMatchesRegularExpression('/FooCov\n\s*Methods:\s+100.00%[^\n]+Lines:\s+100.00%/', $output); - exec("$php $phpunit -c $dir/phpunit-with-listener.xml.dist $dir/tests/ --coverage-text 2> /dev/null", $output); + exec("$php $phpunit -c $dir/phpunit-with-listener.xml.dist $dir/tests/ --coverage-text --colors=never 2> /dev/null", $output); $output = implode("\n", $output); - $this->assertStringNotContainsString('FooCov', $output); + + if (false === strpos($output, 'FooCov')) { + $this->addToAssertionCount(1); + } else { + $this->assertMatchesRegularExpression('/FooCov\n\s*Methods:\s+0.00%[^\n]+Lines:\s+0.00%/', $output); + } + $this->assertStringContainsString("SutNotFoundTest::test\nCould not find the tested class.", $output); $this->assertStringNotContainsString("CoversTest::test\nCould not find the tested class.", $output); $this->assertStringNotContainsString("CoversDefaultClassTest::test\nCould not find the tested class.", $output); diff --git a/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_app/AppService.php b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_app/AppService.php new file mode 100644 index 000000000000..7d9af1ef3ecf --- /dev/null +++ b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_app/AppService.php @@ -0,0 +1,50 @@ +deprecatedApi(); + + $service2 = new SomeOtherService(); + $service2->deprecatedApi(); + } + + public function selfDeprecation(bool $useContracts = false) + { + $args = [__FUNCTION__, __FUNCTION__]; + if ($useContracts) { + trigger_deprecation('App', '3.0', sprintf('%s is deprecated, use %s_new instead.', ...$args)); + } else { + @trigger_error(sprintf('Since App 3.0: %s is deprecated, use %s_new instead.', ...$args), E_USER_DEPRECATED); + } + } + + public function directDeprecation(bool $useContracts = false) + { + $service = new SomeService(); + $service->deprecatedApi($useContracts); + } + + public function indirectDeprecation(bool $useContracts = false) + { + $service = new SomeService(); + $service->indirectDeprecatedApi($useContracts); + } + + public function directDeprecations() + { + $service1 = new SomeService(); + $service1->deprecatedApi(); + + $service2 = new SomeOtherService(); + $service2->deprecatedApi(); + } +} + diff --git a/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor/acme/lib/SomeService.php b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor/acme/lib/SomeService.php index 6a354103ff3c..1e8dce330414 100644 --- a/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor/acme/lib/SomeService.php +++ b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor/acme/lib/SomeService.php @@ -2,13 +2,22 @@ namespace acme\lib; +use bar\lib\AnotherService; + class SomeService { - public function deprecatedApi() + public function deprecatedApi(bool $useContracts = false) + { + $args = [__FUNCTION__, __FUNCTION__]; + if ($useContracts) { + trigger_deprecation('acme/lib', '3.0', sprintf('%s is deprecated, use %s_new instead.', ...$args)); + } else { + @trigger_error(sprintf('Since acme/lib 3.0: %s is deprecated, use %s_new instead.', ...$args), E_USER_DEPRECATED); + } + } + + public function indirectDeprecatedApi(bool $useContracts = false) { - @trigger_error( - __FUNCTION__.' is deprecated! You should stop relying on it!', - E_USER_DEPRECATED - ); + (new AnotherService())->deprecatedApi($useContracts); } } diff --git a/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor/bar/lib/AnotherService.php b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor/bar/lib/AnotherService.php new file mode 100644 index 000000000000..ae072a027a55 --- /dev/null +++ b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor/bar/lib/AnotherService.php @@ -0,0 +1,16 @@ + [__DIR__.'/../../fake_app/'], + 'acme\\lib\\' => [__DIR__.'/../acme/lib/'], + 'bar\\lib\\' => [__DIR__.'/../bar/lib/'], + ]; + } + + public function loadClass($className) + { + foreach ($this->getPrefixesPsr4() as $prefix => $baseDirs) { + if (strpos($className, $prefix) !== 0) { + continue; + } + + foreach ($baseDirs as $baseDir) { + $file = str_replace([$prefix, '\\'], [$baseDir, '/'], $className.'.php'); + if (file_exists($file)) { + require $file; + } + } + } } } class ComposerAutoloaderInitFake { + private static $loader; + public static function getLoader() { - return new ComposerLoaderFake(); + if (null === self::$loader) { + self::$loader = new ComposerLoaderFake(); + spl_autoload_register([self::$loader, 'loadClass']); + } + + return self::$loader; } } diff --git a/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor_bis/autoload.php b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor_bis/autoload.php new file mode 100644 index 000000000000..c1c963926bd3 --- /dev/null +++ b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor_bis/autoload.php @@ -0,0 +1,5 @@ + [__DIR__.'/../foo/lib/'], + ]; + } + + public function loadClass($className) + { + foreach ($this->getPrefixesPsr4() as $prefix => $baseDirs) { + if (strpos($className, $prefix) !== 0) { + continue; + } + + foreach ($baseDirs as $baseDir) { + $file = str_replace([$prefix, '\\'], [$baseDir, '/'], $className.'.php'); + if (file_exists($file)) { + require $file; + } + } + } + } +} + +class ComposerAutoloaderInitFakeBis +{ + private static $loader; + + public static function getLoader() + { + if (null === self::$loader) { + self::$loader = new ComposerLoaderFakeBis(); + spl_autoload_register([self::$loader, 'loadClass']); + } + + return self::$loader; + } +} diff --git a/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor_bis/composer/installed.json b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor_bis/composer/installed.json new file mode 100644 index 000000000000..bf4fecc9fbf7 --- /dev/null +++ b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor_bis/composer/installed.json @@ -0,0 +1 @@ +{"just here": "for the detection"} diff --git a/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor_bis/foo/lib/SomeOtherService.php b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor_bis/foo/lib/SomeOtherService.php new file mode 100644 index 000000000000..b1e8fab2bd24 --- /dev/null +++ b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/fake_vendor_bis/foo/lib/SomeOtherService.php @@ -0,0 +1,14 @@ +directDeprecations(); +?> +--EXPECTF-- +Remaining direct deprecation notices (2) + + 1x: Since acme/lib 3.0: deprecatedApi is deprecated, use deprecatedApi_new instead. + 1x in AppService::directDeprecations from App\Services + + 1x: deprecatedApi from foo is deprecated! You should stop relying on it! + 1x in AppService::directDeprecations from App\Services diff --git a/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/partially_quiet.phpt b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/partially_quiet.phpt index d45c6f9af268..f1fb64ed137b 100644 --- a/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/partially_quiet.phpt +++ b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/partially_quiet.phpt @@ -28,7 +28,7 @@ Remaining direct deprecation notices (1) Remaining indirect deprecation notices (1) - 1x: deprecatedApi is deprecated! You should stop relying on it! + 1x: Since acme/lib 3.0: deprecatedApi is deprecated, use deprecatedApi_new instead. 1x in SomeService::deprecatedApi from acme\lib Legacy deprecation notices (2) diff --git a/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/quiet_but_failing.phpt b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/quiet_but_failing.phpt index 9c73d3c4430a..8d8f8b4ff490 100644 --- a/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/quiet_but_failing.phpt +++ b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/quiet_but_failing.phpt @@ -35,5 +35,5 @@ require __DIR__.'/fake_vendor/acme/outdated-lib/outdated_file.php'; --EXPECTF-- Remaining indirect deprecation notices (1) - 1x: deprecatedApi is deprecated! You should stop relying on it! + 1x: Since acme/lib 3.0: deprecatedApi is deprecated, use deprecatedApi_new instead. 1x in SomeService::deprecatedApi from acme\lib diff --git a/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/trigger_deprecation_types.phpt b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/trigger_deprecation_types.phpt new file mode 100644 index 000000000000..261b6ec83f67 --- /dev/null +++ b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/trigger_deprecation_types.phpt @@ -0,0 +1,58 @@ +--TEST-- +Test deprecation types with trigger_deprecation +--FILE-- +selfDeprecation(true); +(new \App\Services\AppService())->directDeprecation(true); +(new \App\Services\AppService())->indirectDeprecation(true); +trigger_deprecation('foo/bar', '2.0', 'func is deprecated, use new instead.'); +?> +--EXPECTF-- +Remaining self deprecation notices (1) + + 1x: Since App 3.0: selfDeprecation is deprecated, use selfDeprecation_new instead. + 1x in AppService::selfDeprecation from App\Services + +Remaining direct deprecation notices (1) + + 1x: Since acme/lib 3.0: deprecatedApi is deprecated, use deprecatedApi_new instead. + 1x in AppService::directDeprecation from App\Services + +Remaining indirect deprecation notices (1) + + 1x: Since bar/lib 3.0: deprecatedApi is deprecated, use deprecatedApi_new instead. + 1x in AppService::indirectDeprecation from App\Services + +Other deprecation notices (1) + + 1x: Since foo/bar 2.0: func is deprecated, use new instead. diff --git a/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/trigger_error_types.phpt b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/trigger_error_types.phpt new file mode 100644 index 000000000000..4dd6bdaed9f0 --- /dev/null +++ b/src/Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/trigger_error_types.phpt @@ -0,0 +1,58 @@ +--TEST-- +Test deprecation types with trigger_error +--FILE-- +selfDeprecation(); +(new \App\Services\AppService())->directDeprecation(); +(new \App\Services\AppService())->indirectDeprecation(); +@trigger_error('Since foo/bar 2.0: func is deprecated, use new instead.', E_USER_DEPRECATED); +?> +--EXPECTF-- +Remaining self deprecation notices (1) + + 1x: Since App 3.0: selfDeprecation is deprecated, use selfDeprecation_new instead. + 1x in AppService::selfDeprecation from App\Services + +Remaining direct deprecation notices (1) + + 1x: Since acme/lib 3.0: deprecatedApi is deprecated, use deprecatedApi_new instead. + 1x in AppService::directDeprecation from App\Services + +Remaining indirect deprecation notices (1) + + 1x: Since bar/lib 3.0: deprecatedApi is deprecated, use deprecatedApi_new instead. + 1x in AppService::indirectDeprecation from App\Services + +Other deprecation notices (1) + + 1x: Since foo/bar 2.0: func is deprecated, use new instead. diff --git a/src/Symfony/Bridge/PhpUnit/Tests/DnsMockTest.php b/src/Symfony/Bridge/PhpUnit/Tests/DnsMockTest.php index 635c43c4af06..f47ba9fa22f7 100644 --- a/src/Symfony/Bridge/PhpUnit/Tests/DnsMockTest.php +++ b/src/Symfony/Bridge/PhpUnit/Tests/DnsMockTest.php @@ -141,8 +141,8 @@ public function testDnsGetRecord() $this->assertFalse(DnsMock::dns_get_record('foobar.com')); $this->assertSame($records, DnsMock::dns_get_record('example.com')); - $this->assertSame($records, DnsMock::dns_get_record('example.com', DNS_ALL)); - $this->assertSame($records, DnsMock::dns_get_record('example.com', DNS_A | DNS_PTR)); - $this->assertSame([$ptr], DnsMock::dns_get_record('example.com', DNS_PTR)); + $this->assertSame($records, DnsMock::dns_get_record('example.com', \DNS_ALL)); + $this->assertSame($records, DnsMock::dns_get_record('example.com', \DNS_A | \DNS_PTR)); + $this->assertSame([$ptr], DnsMock::dns_get_record('example.com', \DNS_PTR)); } } diff --git a/src/Symfony/Bridge/PhpUnit/Tests/ExpectDeprecationTraitTest.php b/src/Symfony/Bridge/PhpUnit/Tests/ExpectDeprecationTraitTest.php index 2830daef6ebd..5e6350e67310 100644 --- a/src/Symfony/Bridge/PhpUnit/Tests/ExpectDeprecationTraitTest.php +++ b/src/Symfony/Bridge/PhpUnit/Tests/ExpectDeprecationTraitTest.php @@ -26,7 +26,7 @@ final class ExpectDeprecationTraitTest extends TestCase public function testOne() { $this->expectDeprecation('foo'); - @trigger_error('foo', E_USER_DEPRECATED); + @trigger_error('foo', \E_USER_DEPRECATED); } /** @@ -38,7 +38,7 @@ public function testOne() public function testOneInIsolation() { $this->expectDeprecation('foo'); - @trigger_error('foo', E_USER_DEPRECATED); + @trigger_error('foo', \E_USER_DEPRECATED); } /** @@ -50,8 +50,8 @@ public function testMany() { $this->expectDeprecation('foo'); $this->expectDeprecation('bar'); - @trigger_error('foo', E_USER_DEPRECATED); - @trigger_error('bar', E_USER_DEPRECATED); + @trigger_error('foo', \E_USER_DEPRECATED); + @trigger_error('bar', \E_USER_DEPRECATED); } /** @@ -64,8 +64,8 @@ public function testMany() public function testOneWithAnnotation() { $this->expectDeprecation('bar'); - @trigger_error('foo', E_USER_DEPRECATED); - @trigger_error('bar', E_USER_DEPRECATED); + @trigger_error('foo', \E_USER_DEPRECATED); + @trigger_error('bar', \E_USER_DEPRECATED); } /** @@ -80,9 +80,9 @@ public function testManyWithAnnotation() { $this->expectDeprecation('ccc'); $this->expectDeprecation('fcy'); - @trigger_error('foo', E_USER_DEPRECATED); - @trigger_error('bar', E_USER_DEPRECATED); - @trigger_error('ccc', E_USER_DEPRECATED); - @trigger_error('fcy', E_USER_DEPRECATED); + @trigger_error('foo', \E_USER_DEPRECATED); + @trigger_error('bar', \E_USER_DEPRECATED); + @trigger_error('ccc', \E_USER_DEPRECATED); + @trigger_error('fcy', \E_USER_DEPRECATED); } } diff --git a/src/Symfony/Bridge/PhpUnit/Tests/ExpectedDeprecationAnnotationTest.php b/src/Symfony/Bridge/PhpUnit/Tests/ExpectedDeprecationAnnotationTest.php index 259c99162a83..329bf694d295 100644 --- a/src/Symfony/Bridge/PhpUnit/Tests/ExpectedDeprecationAnnotationTest.php +++ b/src/Symfony/Bridge/PhpUnit/Tests/ExpectedDeprecationAnnotationTest.php @@ -24,7 +24,7 @@ final class ExpectedDeprecationAnnotationTest extends TestCase */ public function testOne() { - @trigger_error('foo', E_USER_DEPRECATED); + @trigger_error('foo', \E_USER_DEPRECATED); } /** @@ -37,7 +37,7 @@ public function testOne() */ public function testMany() { - @trigger_error('foo', E_USER_DEPRECATED); - @trigger_error('bar', E_USER_DEPRECATED); + @trigger_error('foo', \E_USER_DEPRECATED); + @trigger_error('bar', \E_USER_DEPRECATED); } } diff --git a/src/Symfony/Bridge/PhpUnit/Tests/FailTests/ExpectDeprecationTraitTestFail.php b/src/Symfony/Bridge/PhpUnit/Tests/FailTests/ExpectDeprecationTraitTestFail.php index 43a3e34f96cf..ba35b268deeb 100644 --- a/src/Symfony/Bridge/PhpUnit/Tests/FailTests/ExpectDeprecationTraitTestFail.php +++ b/src/Symfony/Bridge/PhpUnit/Tests/FailTests/ExpectDeprecationTraitTestFail.php @@ -32,7 +32,7 @@ final class ExpectDeprecationTraitTestFail extends TestCase public function testOne() { $this->expectDeprecation('foo'); - @trigger_error('bar', E_USER_DEPRECATED); + @trigger_error('bar', \E_USER_DEPRECATED); } /** @@ -44,6 +44,6 @@ public function testOne() public function testOneInIsolation() { $this->expectDeprecation('foo'); - @trigger_error('bar', E_USER_DEPRECATED); + @trigger_error('bar', \E_USER_DEPRECATED); } } diff --git a/src/Symfony/Bridge/PhpUnit/Tests/ProcessIsolationTest.php b/src/Symfony/Bridge/PhpUnit/Tests/ProcessIsolationTest.php index 28277161b9ca..1471e9c7be0c 100644 --- a/src/Symfony/Bridge/PhpUnit/Tests/ProcessIsolationTest.php +++ b/src/Symfony/Bridge/PhpUnit/Tests/ProcessIsolationTest.php @@ -18,7 +18,7 @@ class ProcessIsolationTest extends TestCase */ public function testIsolation() { - @trigger_error('Test abc', E_USER_DEPRECATED); + @trigger_error('Test abc', \E_USER_DEPRECATED); $this->addToAssertionCount(1); } @@ -27,6 +27,6 @@ public function testCallingOtherErrorHandler() $this->expectException('PHPUnit\Framework\Exception'); $this->expectExceptionMessage('Test that PHPUnit\'s error handler fires.'); - trigger_error('Test that PHPUnit\'s error handler fires.', E_USER_WARNING); + trigger_error('Test that PHPUnit\'s error handler fires.', \E_USER_WARNING); } } diff --git a/src/Symfony/Bridge/PhpUnit/bin/simple-phpunit.php b/src/Symfony/Bridge/PhpUnit/bin/simple-phpunit.php index 39b61ca5e13c..c03a4c2962d0 100644 --- a/src/Symfony/Bridge/PhpUnit/bin/simple-phpunit.php +++ b/src/Symfony/Bridge/PhpUnit/bin/simple-phpunit.php @@ -30,7 +30,7 @@ return null; } if (is_dir($probableConfig)) { - return $getPhpUnitConfig($probableConfig.DIRECTORY_SEPARATOR.'phpunit.xml'); + return $getPhpUnitConfig($probableConfig.\DIRECTORY_SEPARATOR.'phpunit.xml'); } if (file_exists($probableConfig)) { @@ -93,19 +93,19 @@ } }; -if (PHP_VERSION_ID >= 80000) { +if (\PHP_VERSION_ID >= 80000) { // PHP 8 requires PHPUnit 9.3+ $PHPUNIT_VERSION = $getEnvVar('SYMFONY_PHPUNIT_VERSION', '9.3'); -} elseif (PHP_VERSION_ID >= 70200) { +} elseif (\PHP_VERSION_ID >= 70200) { // PHPUnit 8 requires PHP 7.2+ $PHPUNIT_VERSION = $getEnvVar('SYMFONY_PHPUNIT_VERSION', '8.3'); -} elseif (PHP_VERSION_ID >= 70100) { +} elseif (\PHP_VERSION_ID >= 70100) { // PHPUnit 7 requires PHP 7.1+ $PHPUNIT_VERSION = $getEnvVar('SYMFONY_PHPUNIT_VERSION', '7.5'); -} elseif (PHP_VERSION_ID >= 70000) { +} elseif (\PHP_VERSION_ID >= 70000) { // PHPUnit 6 requires PHP 7.0+ $PHPUNIT_VERSION = $getEnvVar('SYMFONY_PHPUNIT_VERSION', '6.5'); -} elseif (PHP_VERSION_ID >= 50600) { +} elseif (\PHP_VERSION_ID >= 50600) { // PHPUnit 4 does not support PHP 7 $PHPUNIT_VERSION = $getEnvVar('SYMFONY_PHPUNIT_VERSION', '5.7'); } else { @@ -113,7 +113,7 @@ $PHPUNIT_VERSION = '4.8'; } -$PHPUNIT_REMOVE_RETURN_TYPEHINT = filter_var($getEnvVar('SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT', '0'), FILTER_VALIDATE_BOOLEAN); +$PHPUNIT_REMOVE_RETURN_TYPEHINT = filter_var($getEnvVar('SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT', '0'), \FILTER_VALIDATE_BOOLEAN); $COMPOSER_JSON = getenv('COMPOSER') ?: 'composer.json'; @@ -127,9 +127,9 @@ $oldPwd = getcwd(); $PHPUNIT_DIR = $getEnvVar('SYMFONY_PHPUNIT_DIR', $root.'/vendor/bin/.phpunit'); -$PHP = defined('PHP_BINARY') ? PHP_BINARY : 'php'; +$PHP = defined('PHP_BINARY') ? \PHP_BINARY : 'php'; $PHP = escapeshellarg($PHP); -if ('phpdbg' === PHP_SAPI) { +if ('phpdbg' === \PHP_SAPI) { $PHP .= ' -qrr'; } @@ -148,14 +148,14 @@ } $COMPOSER = file_exists($COMPOSER = $oldPwd.'/composer.phar') - || ($COMPOSER = rtrim('\\' === DIRECTORY_SEPARATOR ? preg_replace('/[\r\n].*/', '', `where.exe composer.phar`) : `which composer.phar 2> /dev/null`)) - || ($COMPOSER = rtrim('\\' === DIRECTORY_SEPARATOR ? preg_replace('/[\r\n].*/', '', `where.exe composer`) : `which composer 2> /dev/null`)) - || file_exists($COMPOSER = rtrim('\\' === DIRECTORY_SEPARATOR ? `git rev-parse --show-toplevel 2> NUL` : `git rev-parse --show-toplevel 2> /dev/null`).DIRECTORY_SEPARATOR.'composer.phar') + || ($COMPOSER = rtrim('\\' === \DIRECTORY_SEPARATOR ? preg_replace('/[\r\n].*/', '', `where.exe composer.phar`) : `which composer.phar 2> /dev/null`)) + || ($COMPOSER = rtrim('\\' === \DIRECTORY_SEPARATOR ? preg_replace('/[\r\n].*/', '', `where.exe composer`) : `which composer 2> /dev/null`)) + || file_exists($COMPOSER = rtrim('\\' === \DIRECTORY_SEPARATOR ? `git rev-parse --show-toplevel 2> NUL` : `git rev-parse --show-toplevel 2> /dev/null`).\DIRECTORY_SEPARATOR.'composer.phar') ? ('#!/usr/bin/env php' === file_get_contents($COMPOSER, false, null, 0, 18) ? $PHP : '').' '.escapeshellarg($COMPOSER) // detect shell wrappers by looking at the shebang : 'composer'; $SYMFONY_PHPUNIT_REMOVE = $getEnvVar('SYMFONY_PHPUNIT_REMOVE', 'phpspec/prophecy'.($PHPUNIT_VERSION < 6.0 ? ' symfony/yaml' : '')); -$configurationHash = md5(implode(PHP_EOL, [md5_file(__FILE__), $SYMFONY_PHPUNIT_REMOVE, (int) $PHPUNIT_REMOVE_RETURN_TYPEHINT])); +$configurationHash = md5(implode(\PHP_EOL, [md5_file(__FILE__), $SYMFONY_PHPUNIT_REMOVE, (int) $PHPUNIT_REMOVE_RETURN_TYPEHINT])); $PHPUNIT_VERSION_DIR = sprintf('phpunit-%s-%d', $PHPUNIT_VERSION, $PHPUNIT_REMOVE_RETURN_TYPEHINT); if (!file_exists("$PHPUNIT_DIR/$PHPUNIT_VERSION_DIR/phpunit") || $configurationHash !== @file_get_contents("$PHPUNIT_DIR/.$PHPUNIT_VERSION_DIR.md5")) { // Build a standalone phpunit without symfony/yaml nor prophecy by default @@ -163,9 +163,9 @@ @mkdir($PHPUNIT_DIR, 0777, true); chdir($PHPUNIT_DIR); if (file_exists("$PHPUNIT_VERSION_DIR")) { - passthru(sprintf('\\' === DIRECTORY_SEPARATOR ? 'rmdir /S /Q %s > NUL' : 'rm -rf %s', "$PHPUNIT_VERSION_DIR.old")); + passthru(sprintf('\\' === \DIRECTORY_SEPARATOR ? 'rmdir /S /Q %s > NUL' : 'rm -rf %s', "$PHPUNIT_VERSION_DIR.old")); rename("$PHPUNIT_VERSION_DIR", "$PHPUNIT_VERSION_DIR.old"); - passthru(sprintf('\\' === DIRECTORY_SEPARATOR ? 'rmdir /S /Q %s' : 'rm -rf %s', "$PHPUNIT_VERSION_DIR.old")); + passthru(sprintf('\\' === \DIRECTORY_SEPARATOR ? 'rmdir /S /Q %s' : 'rm -rf %s', "$PHPUNIT_VERSION_DIR.old")); } $info = []; @@ -216,15 +216,15 @@ $passthruOrFail("$COMPOSER require --no-update phpunit/phpunit-mock-objects \"~3.1.0\""); } - if (preg_match('{\^((\d++\.)\d++)[\d\.]*$}', $info['requires']['php'], $phpVersion) && version_compare($phpVersion[2].'99', PHP_VERSION, '<')) { + if (preg_match('{\^((\d++\.)\d++)[\d\.]*$}', $info['requires']['php'], $phpVersion) && version_compare($phpVersion[2].'99', \PHP_VERSION, '<')) { $passthruOrFail("$COMPOSER config platform.php \"$phpVersion[1].99\""); } else { $passthruOrFail("$COMPOSER config --unset platform.php"); } if (file_exists($path = $root.'/vendor/symfony/phpunit-bridge')) { $passthruOrFail("$COMPOSER require --no-update symfony/phpunit-bridge \"*@dev\""); - $passthruOrFail("$COMPOSER config repositories.phpunit-bridge path ".escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $path))); - if ('\\' === DIRECTORY_SEPARATOR) { + $passthruOrFail("$COMPOSER config repositories.phpunit-bridge path ".escapeshellarg(str_replace('/', \DIRECTORY_SEPARATOR, $path))); + if ('\\' === \DIRECTORY_SEPARATOR) { file_put_contents('composer.json', preg_replace('/^( {8})"phpunit-bridge": \{$/m', "$0\n$1 ".'"options": {"symlink": false},', file_get_contents('composer.json'))); } } else { @@ -232,7 +232,7 @@ } $prevRoot = getenv('COMPOSER_ROOT_VERSION'); putenv("COMPOSER_ROOT_VERSION=$PHPUNIT_VERSION.99"); - $q = '\\' === DIRECTORY_SEPARATOR ? '"' : ''; + $q = '\\' === \DIRECTORY_SEPARATOR ? '"' : ''; // --no-suggest is not in the list to keep compat with composer 1.0, which is shipped with Ubuntu 16.04LTS $exit = proc_close(proc_open("$q$COMPOSER install --no-dev --prefer-dist --no-progress $q", [], $p, getcwd())); putenv('COMPOSER_ROOT_VERSION'.(false !== $prevRoot ? '='.$prevRoot : '')); @@ -245,12 +245,12 @@ if ($PHPUNIT_REMOVE_RETURN_TYPEHINT) { $alteredCode = preg_replace('/^ ((?:protected|public)(?: static)? function \w+\(\)): void/m', ' $1', $alteredCode); } - $alteredCode = preg_replace('/abstract class (?:TestCase|PHPUnit_Framework_TestCase)[^\{]+\{/', '$0 '.PHP_EOL." use \Symfony\Bridge\PhpUnit\Legacy\PolyfillTestCaseTrait;", $alteredCode, 1); + $alteredCode = preg_replace('/abstract class (?:TestCase|PHPUnit_Framework_TestCase)[^\{]+\{/', '$0 '.\PHP_EOL." use \Symfony\Bridge\PhpUnit\Legacy\PolyfillTestCaseTrait;", $alteredCode, 1); file_put_contents($alteredFile, $alteredCode); // Mutate Assert code $alteredCode = file_get_contents($alteredFile = './src/Framework/Assert.php'); - $alteredCode = preg_replace('/abstract class (?:Assert|PHPUnit_Framework_Assert)[^\{]+\{/', '$0 '.PHP_EOL." use \Symfony\Bridge\PhpUnit\Legacy\PolyfillAssertTrait;", $alteredCode, 1); + $alteredCode = preg_replace('/abstract class (?:Assert|PHPUnit_Framework_Assert)[^\{]+\{/', '$0 '.\PHP_EOL." use \Symfony\Bridge\PhpUnit\Legacy\PolyfillAssertTrait;", $alteredCode, 1); file_put_contents($alteredFile, $alteredCode); file_put_contents('phpunit', <<<'EOPHP' @@ -303,7 +303,7 @@ class SymfonyExcludeListPhpunit {} return false; }); -} elseif (filter_var(getenv('SYMFONY_PHPUNIT_DISABLE_RESULT_CACHE'), FILTER_VALIDATE_BOOLEAN)) { +} elseif (filter_var(getenv('SYMFONY_PHPUNIT_DISABLE_RESULT_CACHE'), \FILTER_VALIDATE_BOOLEAN)) { $argv[] = '--do-not-cache-result'; ++$argc; } @@ -335,7 +335,7 @@ class SymfonyExcludeListPhpunit {} $cmd[0] = sprintf('%s %s --colors=always', $PHP, escapeshellarg("$PHPUNIT_DIR/$PHPUNIT_VERSION_DIR/phpunit")); $cmd = str_replace('%', '%%', implode(' ', $cmd)).' %1$s'; -if ('\\' === DIRECTORY_SEPARATOR) { +if ('\\' === \DIRECTORY_SEPARATOR) { $cmd = 'cmd /v:on /d /c "('.$cmd.')%2$s"'; } else { $cmd .= '%2$s'; @@ -385,7 +385,7 @@ class SymfonyExcludeListPhpunit {} // STATUS_STACK_BUFFER_OVERRUN (-1073740791/0xC0000409) // STATUS_ACCESS_VIOLATION (-1073741819/0xC0000005) // STATUS_HEAP_CORRUPTION (-1073740940/0xC0000374) - if ($procStatus && ('\\' !== DIRECTORY_SEPARATOR || !extension_loaded('apcu') || !filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN) || !in_array($procStatus, [-1073740791, -1073741819, -1073740940]))) { + if ($procStatus && ('\\' !== \DIRECTORY_SEPARATOR || !extension_loaded('apcu') || !filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN) || !in_array($procStatus, [-1073740791, -1073741819, -1073740940]))) { $exit = $procStatus; echo "\033[41mKO\033[0m $component\n\n"; } else { diff --git a/src/Symfony/Bridge/PhpUnit/bootstrap.php b/src/Symfony/Bridge/PhpUnit/bootstrap.php index 286e166ba571..490b1bfded12 100644 --- a/src/Symfony/Bridge/PhpUnit/bootstrap.php +++ b/src/Symfony/Bridge/PhpUnit/bootstrap.php @@ -115,7 +115,7 @@ class_alias('PHPUnit_Framework_Constraint_Xor', 'PHPUnit\Framework\Constraint\Lo } // Enforce a consistent locale -setlocale(LC_ALL, 'C'); +setlocale(\LC_ALL, 'C'); if (!class_exists('Doctrine\Common\Annotations\AnnotationRegistry', false) && class_exists('Doctrine\Common\Annotations\AnnotationRegistry')) { if (method_exists('Doctrine\Common\Annotations\AnnotationRegistry', 'registerUniqueLoader')) { diff --git a/src/Symfony/Bridge/PhpUnit/composer.json b/src/Symfony/Bridge/PhpUnit/composer.json index a285a435ce9b..60c13a0aabc7 100644 --- a/src/Symfony/Bridge/PhpUnit/composer.json +++ b/src/Symfony/Bridge/PhpUnit/composer.json @@ -45,5 +45,8 @@ "name": "phpunit/phpunit", "url": "https://github.com/sebastianbergmann/phpunit" } + }, + "require-dev": { + "symfony/deprecation-contracts": "^2.1" } } diff --git a/src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/LazyLoadingValueHolderGenerator.php b/src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/LazyLoadingValueHolderGenerator.php index 54d0483f7d8b..2ff31bbda353 100644 --- a/src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/LazyLoadingValueHolderGenerator.php +++ b/src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/LazyLoadingValueHolderGenerator.php @@ -66,7 +66,7 @@ public function generate(\ReflectionClass $originalClass, ClassGenerator $classG if (null !== $docBlock = $method->getDocBlock()) { $code = substr($code, \strlen($docBlock->generate())); } - $refAmp = (strpos($code, '&') ?: PHP_INT_MAX) <= strpos($code, '(') ? '&' : ''; + $refAmp = (strpos($code, '&') ?: \PHP_INT_MAX) <= strpos($code, '(') ? '&' : ''; $body = preg_replace( '/\nreturn (\$this->valueHolder[0-9a-f]++)(->[^;]++);$/', "\nif ($1 === \$returnValue = {$refAmp}$1$2) {\n \$returnValue = \$this;\n}\n\nreturn \$returnValue;", diff --git a/src/Symfony/Bridge/Twig/Command/DebugCommand.php b/src/Symfony/Bridge/Twig/Command/DebugCommand.php index 219613eb2f16..974a38a9c3dc 100644 --- a/src/Symfony/Bridge/Twig/Command/DebugCommand.php +++ b/src/Symfony/Bridge/Twig/Command/DebugCommand.php @@ -262,7 +262,7 @@ private function displayGeneralJson(SymfonyStyle $io, ?string $filter) $data['warnings'] = $this->buildWarningMessages($wrongBundles); } - $data = json_encode($data, JSON_PRETTY_PRINT); + $data = json_encode($data, \JSON_PRETTY_PRINT); $io->writeln($decorated ? OutputFormatter::escape($data) : $data); } @@ -392,7 +392,7 @@ private function findWrongBundleOverrides(): array $bundleNames = []; if ($this->twigDefaultPath && $this->projectDir) { - $folders = glob($this->twigDefaultPath.'/bundles/*', GLOB_ONLYDIR); + $folders = glob($this->twigDefaultPath.'/bundles/*', \GLOB_ONLYDIR); $relativePath = ltrim(substr($this->twigDefaultPath.'/bundles/', \strlen($this->projectDir)), \DIRECTORY_SEPARATOR); $bundleNames = array_reduce($folders, function ($carry, $absolutePath) use ($relativePath) { if (0 === strpos($absolutePath, $this->projectDir)) { @@ -532,7 +532,7 @@ private function findAlternatives(string $name, array $collection): array $threshold = 1e3; $alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; }); - ksort($alternatives, SORT_NATURAL | SORT_FLAG_CASE); + ksort($alternatives, \SORT_NATURAL | \SORT_FLAG_CASE); return array_keys($alternatives); } @@ -548,7 +548,7 @@ private function getRelativePath(string $path): string private function isAbsolutePath(string $file): bool { - return strspn($file, '/\\', 0, 1) || (\strlen($file) > 3 && ctype_alpha($file[0]) && ':' === $file[1] && strspn($file, '/\\', 2, 1)) || null !== parse_url($file, PHP_URL_SCHEME); + return strspn($file, '/\\', 0, 1) || (\strlen($file) > 3 && ctype_alpha($file[0]) && ':' === $file[1] && strspn($file, '/\\', 2, 1)) || null !== parse_url($file, \PHP_URL_SCHEME); } /** diff --git a/src/Symfony/Bridge/Twig/Command/LintCommand.php b/src/Symfony/Bridge/Twig/Command/LintCommand.php index 66c108af35b7..505f05959bb6 100644 --- a/src/Symfony/Bridge/Twig/Command/LintCommand.php +++ b/src/Symfony/Bridge/Twig/Command/LintCommand.php @@ -101,7 +101,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if ($showDeprecations) { $prevErrorHandler = set_error_handler(static function ($level, $message, $file, $line) use (&$prevErrorHandler) { - if (E_USER_DEPRECATED === $level) { + if (\E_USER_DEPRECATED === $level) { $templateLine = 0; if (preg_match('/ at line (\d+)[ .]/', $message, $matches)) { $templateLine = $matches[1]; @@ -214,7 +214,7 @@ private function displayJson(OutputInterface $output, array $filesInfo) } }); - $output->writeln(json_encode($filesInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + $output->writeln(json_encode($filesInfo, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES)); return min($errors, 1); } diff --git a/src/Symfony/Bridge/Twig/Extension/CodeExtension.php b/src/Symfony/Bridge/Twig/Extension/CodeExtension.php index f35725af0da9..0ff70eccd688 100644 --- a/src/Symfony/Bridge/Twig/Extension/CodeExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/CodeExtension.php @@ -97,7 +97,7 @@ public function formatArgs(array $args): string } elseif ('resource' === $item[0]) { $formattedValue = 'resource'; } else { - $formattedValue = str_replace("\n", '', htmlspecialchars(var_export($item[1], true), ENT_COMPAT | ENT_SUBSTITUTE, $this->charset)); + $formattedValue = str_replace("\n", '', htmlspecialchars(var_export($item[1], true), \ENT_COMPAT | \ENT_SUBSTITUTE, $this->charset)); } $result[] = \is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue); @@ -166,7 +166,7 @@ public function formatFile(string $file, int $line, string $text = null): string } if (false !== $link = $this->getFileLink($file, $line)) { - return sprintf('%s', htmlspecialchars($link, ENT_COMPAT | ENT_SUBSTITUTE, $this->charset), $text); + return sprintf('%s', htmlspecialchars($link, \ENT_COMPAT | \ENT_SUBSTITUTE, $this->charset), $text); } return $text; @@ -222,7 +222,7 @@ public function formatLogMessage(string $message, array $context): string } } - return htmlspecialchars($message, ENT_COMPAT | ENT_SUBSTITUTE, $this->charset); + return htmlspecialchars($message, \ENT_COMPAT | \ENT_SUBSTITUTE, $this->charset); } protected static function fixCodeMarkup(string $line): string diff --git a/src/Symfony/Bridge/Twig/Translation/TwigExtractor.php b/src/Symfony/Bridge/Twig/Translation/TwigExtractor.php index e9e13395c75d..e79ec697e0f5 100644 --- a/src/Symfony/Bridge/Twig/Translation/TwigExtractor.php +++ b/src/Symfony/Bridge/Twig/Translation/TwigExtractor.php @@ -89,7 +89,7 @@ protected function extractTemplate(string $template, MessageCatalogue $catalogue */ protected function canBeExtracted(string $file) { - return $this->isFile($file) && 'twig' === pathinfo($file, PATHINFO_EXTENSION); + return $this->isFile($file) && 'twig' === pathinfo($file, \PATHINFO_EXTENSION); } /** diff --git a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/AbstractPhpFileCacheWarmer.php b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/AbstractPhpFileCacheWarmer.php index c18a44d11c54..29276a0dcecc 100644 --- a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/AbstractPhpFileCacheWarmer.php +++ b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/AbstractPhpFileCacheWarmer.php @@ -17,9 +17,6 @@ use Symfony\Component\Config\Resource\ClassExistenceResource; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; -/** - * @internal - */ abstract class AbstractPhpFileCacheWarmer implements CacheWarmerInterface { private $phpArrayFile; diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/AboutCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/AboutCommand.php index e2ea9dfa7a93..a776e18d163d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/AboutCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/AboutCommand.php @@ -80,12 +80,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int new TableSeparator(), ['PHP'], new TableSeparator(), - ['Version', PHP_VERSION], + ['Version', \PHP_VERSION], ['Architecture', (\PHP_INT_SIZE * 8).' bits'], ['Intl locale', class_exists('Locale', false) && \Locale::getDefault() ? \Locale::getDefault() : 'n/a'], ['Timezone', date_default_timezone_get().' ('.(new \DateTime())->format(\DateTime::W3C).')'], - ['OPcache', \extension_loaded('Zend OPcache') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN) ? 'true' : 'false'], - ['APCu', \extension_loaded('apcu') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? 'true' : 'false'], + ['OPcache', \extension_loaded('Zend OPcache') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN) ? 'true' : 'false'], + ['APCu', \extension_loaded('apcu') && filter_var(ini_get('apc.enabled'), \FILTER_VALIDATE_BOOLEAN) ? 'true' : 'false'], ['Xdebug', \extension_loaded('xdebug') ? 'true' : 'false'], ]; diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/AbstractConfigCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/AbstractConfigCommand.php index 9caefac32f42..bda4956df7fa 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/AbstractConfigCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/AbstractConfigCommand.php @@ -63,7 +63,7 @@ protected function listBundles($output) protected function findExtension(string $name) { $bundles = $this->initializeBundles(); - $minScore = INF; + $minScore = \INF; $kernel = $this->getApplication()->getKernel(); if ($kernel instanceof ExtensionInterface && ($kernel instanceof ConfigurationInterface || $kernel instanceof ConfigurationExtensionInterface)) { diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php index 29791ab119c3..f4711b126d76 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php @@ -175,6 +175,20 @@ protected function execute(InputInterface $input, OutputInterface $output): int } } + $kernelDir = \dirname((new \ReflectionObject($kernel))->getFileName()); + $preloadFile = $fs->makePathRelative(\dirname($containerFile, 2), $kernelDir); + $preloadFile .= substr_replace(basename($containerFile), '.preload', -4, 0); + $preloadFile = var_export('/'.$preloadFile, true); + @file_put_contents($kernelDir.'/.preload.php', <<isVerbose()) { $io->comment('Finished'); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php index dc0fe17937ed..3eb98fc921d6 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php @@ -183,7 +183,7 @@ private function writeData(array $data, array $options) { $flags = isset($options['json_encoding']) ? $options['json_encoding'] : 0; - $this->write(json_encode($data, $flags | JSON_PRETTY_PRINT)."\n"); + $this->write(json_encode($data, $flags | \JSON_PRETTY_PRINT)."\n"); } protected function getRouteData(Route $route): array diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php b/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php index 58f06d5df9f0..1be9f99f238c 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php +++ b/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php @@ -119,7 +119,7 @@ public function urlRedirectAction(Request $request, string $path, bool $permanen } // redirect if the path is a full URL - if (parse_url($path, PHP_URL_SCHEME)) { + if (parse_url($path, \PHP_URL_SCHEME)) { return new RedirectResponse($path, $statusCode); } diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/ProfilerPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/ProfilerPass.php index d6e61cc60552..4318081db32b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/ProfilerPass.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/ProfilerPass.php @@ -32,7 +32,7 @@ public function process(ContainerBuilder $container) $definition = $container->getDefinition('profiler'); $collectors = new \SplPriorityQueue(); - $order = PHP_INT_MAX; + $order = \PHP_INT_MAX; foreach ($container->findTaggedServiceIds('data_collector', true) as $id => $attributes) { $priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0; $template = null; diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php index eab898b8829f..0070353a71d6 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php @@ -1197,7 +1197,7 @@ function ($a) { return $middleware; } if (1 < \count($middleware)) { - throw new \InvalidArgumentException(sprintf('Invalid middleware at path "framework.messenger": a map with a single factory id as key and its arguments as value was expected, %s given.', json_encode($middleware))); + throw new \InvalidArgumentException('Invalid middleware at path "framework.messenger": a map with a single factory id as key and its arguments as value was expected, '.json_encode($middleware).' given.'); } return [ diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php index bf1bcec63fcd..8cfe260ddd4d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php @@ -1060,7 +1060,7 @@ private function createVersion(ContainerBuilder $container, ?string $version, ?s if (null !== $jsonManifestPath) { $definitionName = 'assets.json_manifest_version_strategy'; - if (0 === strpos(parse_url($jsonManifestPath, PHP_URL_SCHEME), 'http')) { + if (0 === strpos(parse_url($jsonManifestPath, \PHP_URL_SCHEME), 'http')) { $definitionName = 'assets.remote_json_manifest_version_strategy'; } diff --git a/src/Symfony/Bundle/FrameworkBundle/Kernel/MicroKernelTrait.php b/src/Symfony/Bundle/FrameworkBundle/Kernel/MicroKernelTrait.php index efd99784e489..8e5247faea7a 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Kernel/MicroKernelTrait.php +++ b/src/Symfony/Bundle/FrameworkBundle/Kernel/MicroKernelTrait.php @@ -152,7 +152,7 @@ public function loadRoutes(LoaderInterface $loader) { $file = (new \ReflectionObject($this))->getFileName(); /* @var RoutingPhpFileLoader $kernelLoader */ - $kernelLoader = $loader->getResolver()->resolve($file); + $kernelLoader = $loader->getResolver()->resolve($file, 'php'); $kernelLoader->setCurrentDir(\dirname($file)); $collection = new RouteCollection(); diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd b/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd index e2bc23f936b8..815efd887065 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd @@ -331,7 +331,7 @@ - + diff --git a/src/Symfony/Bundle/FrameworkBundle/Secrets/SodiumVault.php b/src/Symfony/Bundle/FrameworkBundle/Secrets/SodiumVault.php index 029ef3463e4b..7b2740fea728 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Secrets/SodiumVault.php +++ b/src/Symfony/Bundle/FrameworkBundle/Secrets/SodiumVault.php @@ -89,7 +89,7 @@ public function seal(string $name, string $value): void $list = $this->list(); $list[$name] = null; uksort($list, 'strnatcmp'); - file_put_contents($this->pathPrefix.'list.php', sprintf("pathPrefix.'list.php', sprintf("lastMessage = sprintf('Secret "%s" encrypted in "%s"; you can commit it.', $name, $this->getPrettyPath(\dirname($this->pathPrefix).\DIRECTORY_SEPARATOR)); } @@ -141,7 +141,7 @@ public function remove(string $name): bool $list = $this->list(); unset($list[$name]); - file_put_contents($this->pathPrefix.'list.php', sprintf("pathPrefix.'list.php', sprintf("lastMessage = sprintf('Secret "%s" removed from "%s".', $name, $this->getPrettyPath(\dirname($this->pathPrefix).\DIRECTORY_SEPARATOR)); @@ -205,9 +205,9 @@ private function export(string $file, string $data): void $this->createSecretsDir(); - if (false === file_put_contents($this->pathPrefix.$file.'.php', $data, LOCK_EX)) { + if (false === file_put_contents($this->pathPrefix.$file.'.php', $data, \LOCK_EX)) { $e = error_get_last(); - throw new \ErrorException($e['message'] ?? 'Failed to write secrets data.', 0, $e['type'] ?? E_USER_WARNING); + throw new \ErrorException($e['message'] ?? 'Failed to write secrets data.', 0, $e['type'] ?? \E_USER_WARNING); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/CacheClearCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/CacheClearCommandTest.php index 4b557011a9d2..41769f49d1e0 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/CacheClearCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/CacheClearCommandTest.php @@ -38,6 +38,7 @@ protected function setUp(): void protected function tearDown(): void { $this->fs->remove($this->kernel->getProjectDir()); + $this->fs->remove(__DIR__.'/Fixture/.preload.php'); } public function testCacheIsFreshAfterCacheClearedWithWarmup() @@ -82,5 +83,7 @@ public function testCacheIsFreshAfterCacheClearedWithWarmup() $containerRef = new \ReflectionClass(require $containerFile); $containerFile = str_replace('tes_'.\DIRECTORY_SEPARATOR, 'test'.\DIRECTORY_SEPARATOR, $containerRef->getFileName()); $this->assertMatchesRegularExpression(sprintf('/\'kernel.container_class\'\s*=>\s*\'%s\'/', $containerClass), file_get_contents($containerFile), 'kernel.container_class is properly set on the dumped container'); + + $this->assertFileEquals(__DIR__.'/Fixture/preload.php.expected', __DIR__.'/Fixture/.preload.php'); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/Fixture/preload.php.expected b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/Fixture/preload.php.expected new file mode 100644 index 000000000000..7caee2246860 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/Fixture/preload.php.expected @@ -0,0 +1,5 @@ +getDescriptor()->describe($output, $describedObject, $options); if ('json' === $this->getFormat()) { - $this->assertEquals(json_encode(json_decode($expectedDescription), JSON_PRETTY_PRINT), json_encode(json_decode($output->fetch()), JSON_PRETTY_PRINT)); + $this->assertEquals(json_encode(json_decode($expectedDescription), \JSON_PRETTY_PRINT), json_encode(json_decode($output->fetch()), \JSON_PRETTY_PRINT)); } else { - $this->assertEquals(trim($expectedDescription), trim(str_replace(PHP_EOL, "\n", $output->fetch()))); + $this->assertEquals(trim($expectedDescription), trim(str_replace(\PHP_EOL, "\n", $output->fetch()))); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php index 0b30d684d863..447f48984b62 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php @@ -224,7 +224,7 @@ public function testJsonWithSerializerContextOverride() $response = $controller->json([], 200, [], ['json_encode_options' => 0, 'other' => 'context']); $this->assertInstanceOf(JsonResponse::class, $response); $this->assertEquals('[]', $response->getContent()); - $response->setEncodingOptions(JSON_FORCE_OBJECT); + $response->setEncodingOptions(\JSON_FORCE_OBJECT); $this->assertEquals('{}', $response->getContent()); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflows.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflows.php index 7c7f7ed0b45f..d0abe507e5ef 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflows.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflows.php @@ -10,6 +10,10 @@ FrameworkExtensionTest::class, ], 'initial_marking' => ['draft'], + 'metadata' => [ + 'title' => 'article workflow', + 'description' => 'workflow for articles' + ], 'places' => [ 'draft', 'wait_for_journalist', diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflows.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflows.xml index 0c6a638df45c..290ab50e7d8d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflows.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflows.xml @@ -35,6 +35,10 @@ approved_by_spellchecker published + + article workflow + workflow for articles + diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflows.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflows.yml index 225106383d1f..e4ac9c01890e 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflows.yml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflows.yml @@ -5,6 +5,9 @@ framework: supports: - Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\FrameworkExtensionTest initial_marking: [draft] + metadata: + title: article workflow + description: workflow for articles places: # simple format - draft diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php index 2fb91c36f067..c6f158eb8c0d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php @@ -54,6 +54,7 @@ use Symfony\Component\Validator\DependencyInjection\AddConstraintValidatorsPass; use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader; use Symfony\Component\Workflow; +use Symfony\Component\Workflow\Metadata\InMemoryMetadataStore; abstract class FrameworkExtensionTest extends TestCase { @@ -231,6 +232,12 @@ public function testWorkflows() ); $this->assertCount(4, $workflowDefinition->getArgument(1)); $this->assertSame(['draft'], $workflowDefinition->getArgument(2)); + $metadataStoreDefinition = $workflowDefinition->getArgument(3); + $this->assertSame(InMemoryMetadataStore::class, $metadataStoreDefinition->getClass()); + $this->assertSame([ + 'title' => 'article workflow', + 'description' => 'workflow for articles', + ], $metadataStoreDefinition->getArgument(0)); $this->assertTrue($container->hasDefinition('state_machine.pull_request'), 'State machine is registered as a service'); $this->assertSame('state_machine.abstract', $container->getDefinition('state_machine.pull_request')->getParent()); @@ -255,7 +262,7 @@ public function testWorkflows() $metadataStoreDefinition = $stateMachineDefinition->getArgument(3); $this->assertInstanceOf(Definition::class, $metadataStoreDefinition); - $this->assertSame(Workflow\Metadata\InMemoryMetadataStore::class, $metadataStoreDefinition->getClass()); + $this->assertSame(InMemoryMetadataStore::class, $metadataStoreDefinition->getClass()); $workflowMetadata = $metadataStoreDefinition->getArgument(0); $this->assertSame(['title' => 'workflow title'], $workflowMetadata); @@ -1265,16 +1272,20 @@ public function testCachePoolServices() $this->assertSame(ChainAdapter::class, $chain->getClass()); + $this->assertCount(2, $chain->getArguments()); + $this->assertCount(3, $chain->getArguments()[0]); + + $expectedSeed = $chain->getArgument(0)[1]->getArgument(0); $expected = [ [ (new ChildDefinition('cache.adapter.array')) ->replaceArgument(0, 12), (new ChildDefinition('cache.adapter.filesystem')) - ->replaceArgument(0, 'xctxZ1lyiH') + ->replaceArgument(0, $expectedSeed) ->replaceArgument(1, 12), (new ChildDefinition('cache.adapter.redis')) ->replaceArgument(0, new Reference('.cache_connection.kYdiLgf')) - ->replaceArgument(1, 'xctxZ1lyiH') + ->replaceArgument(1, $expectedSeed) ->replaceArgument(2, 12), ], 12, diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Test/WebTestCaseTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Test/WebTestCaseTest.php index a68c9f510c43..efa3fbfb1f67 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Test/WebTestCaseTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Test/WebTestCaseTest.php @@ -71,7 +71,7 @@ public function testAssertResponseRedirectsWithLocationAndStatusCode() { $this->getResponseTester(new Response('', 302, ['Location' => 'https://example.com/']))->assertResponseRedirects('https://example.com/', 302); $this->expectException(AssertionFailedError::class); - $this->expectExceptionMessage('is redirected and has header "Location" with value "https://example.com/" and status code is 301.'); + $this->expectExceptionMessageMatches('#(:?\( )?is redirected and has header "Location" with value "https://example\.com/" (:?\) )?and status code is 301\.#'); $this->getResponseTester(new Response('', 302))->assertResponseRedirects('https://example.com/', 301); } diff --git a/src/Symfony/Bundle/SecurityBundle/Command/UserPasswordEncoderCommand.php b/src/Symfony/Bundle/SecurityBundle/Command/UserPasswordEncoderCommand.php index 24f289f0fb30..de23fdd618a1 100644 --- a/src/Symfony/Bundle/SecurityBundle/Command/UserPasswordEncoderCommand.php +++ b/src/Symfony/Bundle/SecurityBundle/Command/UserPasswordEncoderCommand.php @@ -134,7 +134,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($input->isInteractive() && !$emptySalt) { $emptySalt = true; - $errorIo->note('The command will take care of generating a salt for you. Be aware that some encoders advise to let them generate their own salt. If you\'re using one of those encoders, please answer \'no\' to the question below. '.PHP_EOL.'Provide the \'empty-salt\' option in order to let the encoder handle the generation itself.'); + $errorIo->note('The command will take care of generating a salt for you. Be aware that some encoders advise to let them generate their own salt. If you\'re using one of those encoders, please answer \'no\' to the question below. '.\PHP_EOL.'Provide the \'empty-salt\' option in order to let the encoder handle the generation itself.'); if ($errorIo->confirm('Confirm salt generation ?')) { $salt = $this->generateSalt(); diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php index e3f263329817..3d3000d8cd92 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php @@ -16,6 +16,7 @@ use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Security\Core\Authorization\AccessDecisionManager; +use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; use Symfony\Component\Security\Http\Event\LogoutEvent; use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy; @@ -194,7 +195,9 @@ private function addFirewallsSection(ArrayNodeDefinition $rootNode, array $facto ->scalarNode('request_matcher')->end() ->scalarNode('access_denied_url')->end() ->scalarNode('access_denied_handler')->end() - ->scalarNode('entry_point')->end() + ->scalarNode('entry_point') + ->info(sprintf('An enabled authenticator name or a service id that implements "%s"', AuthenticationEntryPointInterface::class)) + ->end() ->scalarNode('provider')->end() ->booleanNode('stateless')->defaultFalse()->end() ->booleanNode('lazy')->defaultFalse()->end() diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php index 198bf08a24d0..7202b2e5a95e 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php @@ -588,7 +588,7 @@ private function createAuthenticationListeners(ContainerBuilder $container, stri } } - if (false === $hasListeners) { + if (false === $hasListeners && !$this->authenticatorManagerEnabled) { throw new InvalidConfigurationException(sprintf('No authentication listener registered for firewall "%s".', $id)); } @@ -680,7 +680,7 @@ private function createEncoder(array $config) // bcrypt encoder if ('bcrypt' === $config['algorithm']) { $config['algorithm'] = 'native'; - $config['native_algorithm'] = PASSWORD_BCRYPT; + $config['native_algorithm'] = \PASSWORD_BCRYPT; return $this->createEncoder($config); } @@ -691,7 +691,7 @@ private function createEncoder(array $config) $config['algorithm'] = 'sodium'; } elseif (\defined('PASSWORD_ARGON2I')) { $config['algorithm'] = 'native'; - $config['native_algorithm'] = PASSWORD_ARGON2I; + $config['native_algorithm'] = \PASSWORD_ARGON2I; } else { throw new InvalidConfigurationException(sprintf('Algorithm "argon2i" is not available. Either use "%s" or upgrade to PHP 7.2+ instead.', \defined('SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13') ? 'argon2id", "auto' : 'auto')); } @@ -704,7 +704,7 @@ private function createEncoder(array $config) $config['algorithm'] = 'sodium'; } elseif (\defined('PASSWORD_ARGON2ID')) { $config['algorithm'] = 'native'; - $config['native_algorithm'] = PASSWORD_ARGON2ID; + $config['native_algorithm'] = \PASSWORD_ARGON2ID; } else { throw new InvalidConfigurationException(sprintf('Algorithm "argon2id" is not available. Either use "%s", upgrade to PHP 7.3+ or use libsodium 1.0.15+ instead.', \defined('PASSWORD_ARGON2I') || $hasSodium ? 'argon2i", "auto' : 'auto')); } @@ -928,7 +928,7 @@ private function isValidIp(string $cidr): bool $cidrParts = explode('/', $cidr); if (1 === \count($cidrParts)) { - return false !== filter_var($cidrParts[0], FILTER_VALIDATE_IP); + return false !== filter_var($cidrParts[0], \FILTER_VALIDATE_IP); } $ip = $cidrParts[0]; @@ -938,11 +938,11 @@ private function isValidIp(string $cidr): bool return false; } - if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + if (filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) { return $netmask <= 32; } - if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { + if (filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) { return $netmask <= 128; } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/RegisterGlobalSecurityEventListenersPassTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/RegisterGlobalSecurityEventListenersPassTest.php index 8576d24c26bf..adbbbb9f5867 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/RegisterGlobalSecurityEventListenersPassTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/RegisterGlobalSecurityEventListenersPassTest.php @@ -23,7 +23,7 @@ use Symfony\Component\Security\Http\Event\LoginSuccessEvent; use Symfony\Component\Security\Http\Event\LogoutEvent; -class RegisterGlobalSecurtyEventListenersPassTest extends TestCase +class RegisterGlobalSecurityEventListenersPassTest extends TestCase { private $container; diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php index 77b6933ffd8e..a7f56e995878 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php @@ -432,7 +432,7 @@ public function testEncodersWithArgon2i() ], 'JMS\FooBundle\Entity\User7' => [ 'class' => $sodium ? SodiumPasswordEncoder::class : NativePasswordEncoder::class, - 'arguments' => $sodium ? [256, 1] : [1, 262144, null, PASSWORD_ARGON2I], + 'arguments' => $sodium ? [256, 1] : [1, 262144, null, \PASSWORD_ARGON2I], ], ]], $container->getDefinition('security.encoder_factory.generic')->getArguments()); } @@ -542,7 +542,7 @@ public function testEncodersWithBCrypt() ], 'JMS\FooBundle\Entity\User7' => [ 'class' => NativePasswordEncoder::class, - 'arguments' => [null, null, 15, PASSWORD_BCRYPT], + 'arguments' => [null, null, 15, \PASSWORD_BCRYPT], ], ]], $container->getDefinition('security.encoder_factory.generic')->getArguments()); } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php index 06460993f85c..6eb936c48bae 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php @@ -362,6 +362,7 @@ public function testRememberMeCookieInheritFrameworkSessionCookie($config, $same $container->setParameter('kernel.bundles_metadata', []); $container->setParameter('kernel.project_dir', __DIR__); $container->setParameter('kernel.cache_dir', __DIR__); + $container->setParameter('kernel.container_class', 'FooContainer'); $container->loadFromExtension('security', [ 'firewalls' => [ diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/UserPasswordEncoderCommandTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/UserPasswordEncoderCommandTest.php index 40653dec8015..f4cb1c72ba39 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/UserPasswordEncoderCommandTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/UserPasswordEncoderCommandTest.php @@ -38,7 +38,7 @@ public function testEncodePasswordEmptySalt() 'user-class' => 'Symfony\Component\Security\Core\User\User', '--empty-salt' => true, ], ['decorated' => false]); - $expected = str_replace("\n", PHP_EOL, file_get_contents(__DIR__.'/app/PasswordEncode/emptysalt.txt')); + $expected = str_replace("\n", \PHP_EOL, file_get_contents(__DIR__.'/app/PasswordEncode/emptysalt.txt')); $this->assertEquals($expected, $this->passwordEncoderCommandTester->getDisplay()); } @@ -65,7 +65,7 @@ public function testEncodePasswordBcrypt() $output = $this->passwordEncoderCommandTester->getDisplay(); $this->assertStringContainsString('Password encoding succeeded', $output); - $encoder = new NativePasswordEncoder(null, null, 17, PASSWORD_BCRYPT); + $encoder = new NativePasswordEncoder(null, null, 17, \PASSWORD_BCRYPT); preg_match('# Encoded password\s{1,}([\w+\/$.]+={0,2})\s+#', $output, $matches); $hash = $matches[1]; $this->assertTrue($encoder->isPasswordValid($hash, 'password', null)); @@ -86,7 +86,7 @@ public function testEncodePasswordArgon2i() $output = $this->passwordEncoderCommandTester->getDisplay(); $this->assertStringContainsString('Password encoding succeeded', $output); - $encoder = $sodium ? new SodiumPasswordEncoder() : new NativePasswordEncoder(null, null, null, PASSWORD_ARGON2I); + $encoder = $sodium ? new SodiumPasswordEncoder() : new NativePasswordEncoder(null, null, null, \PASSWORD_ARGON2I); preg_match('# Encoded password\s+(\$argon2i?\$[\w,=\$+\/]+={0,2})\s+#', $output, $matches); $hash = $matches[1]; $this->assertTrue($encoder->isPasswordValid($hash, 'password', null)); @@ -107,7 +107,7 @@ public function testEncodePasswordArgon2id() $output = $this->passwordEncoderCommandTester->getDisplay(); $this->assertStringContainsString('Password encoding succeeded', $output); - $encoder = $sodium ? new SodiumPasswordEncoder() : new NativePasswordEncoder(null, null, null, PASSWORD_ARGON2ID); + $encoder = $sodium ? new SodiumPasswordEncoder() : new NativePasswordEncoder(null, null, null, \PASSWORD_ARGON2ID); preg_match('# Encoded password\s+(\$argon2id?\$[\w,=\$+\/]+={0,2})\s+#', $output, $matches); $hash = $matches[1]; $this->assertTrue($encoder->isPasswordValid($hash, 'password', null)); @@ -314,7 +314,7 @@ public function testThrowsExceptionOnNoConfiguredEncoders() protected function setUp(): void { - putenv('COLUMNS='.(119 + \strlen(PHP_EOL))); + putenv('COLUMNS='.(119 + \strlen(\PHP_EOL))); $kernel = $this->createKernel(['test_case' => 'PasswordEncode']); $kernel->boot(); @@ -332,7 +332,7 @@ protected function tearDown(): void private function setupArgon2i() { - putenv('COLUMNS='.(119 + \strlen(PHP_EOL))); + putenv('COLUMNS='.(119 + \strlen(\PHP_EOL))); $kernel = $this->createKernel(['test_case' => 'PasswordEncode', 'root_config' => 'argon2i.yml']); $kernel->boot(); @@ -345,7 +345,7 @@ private function setupArgon2i() private function setupArgon2id() { - putenv('COLUMNS='.(119 + \strlen(PHP_EOL))); + putenv('COLUMNS='.(119 + \strlen(\PHP_EOL))); $kernel = $this->createKernel(['test_case' => 'PasswordEncode', 'root_config' => 'argon2id.yml']); $kernel->boot(); @@ -358,7 +358,7 @@ private function setupArgon2id() private function setupBcrypt() { - putenv('COLUMNS='.(119 + \strlen(PHP_EOL))); + putenv('COLUMNS='.(119 + \strlen(\PHP_EOL))); $kernel = $this->createKernel(['test_case' => 'PasswordEncode', 'root_config' => 'bcrypt.yml']); $kernel->boot(); @@ -371,7 +371,7 @@ private function setupBcrypt() private function setupSodium() { - putenv('COLUMNS='.(119 + \strlen(PHP_EOL))); + putenv('COLUMNS='.(119 + \strlen(\PHP_EOL))); $kernel = $this->createKernel(['test_case' => 'PasswordEncode', 'root_config' => 'sodium.yml']); $kernel->boot(); diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php index d9ece4216d5b..46b88456147e 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php @@ -382,10 +382,12 @@ public function testDefaultPanel(string $expectedPanel, Profile $profile) ->with($profile->getToken()) ->willReturn($profile); + $collectorsNames = array_keys($profile->getCollectors()); + $profiler ->expects($this->atLeastOnce()) ->method('has') - ->with($this->logicalXor($collectorsNames = array_keys($profile->getCollectors()))) + ->with($this->logicalXor(...$collectorsNames)) ->willReturn(true); $expectedTemplate = 'expected_template.html.twig'; diff --git a/src/Symfony/Bundle/WebProfilerBundle/WebProfilerBundle.php b/src/Symfony/Bundle/WebProfilerBundle/WebProfilerBundle.php index 897c3ffb7ff8..7fcc4ec47f78 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/WebProfilerBundle.php +++ b/src/Symfony/Bundle/WebProfilerBundle/WebProfilerBundle.php @@ -21,7 +21,7 @@ class WebProfilerBundle extends Bundle public function boot() { if ('prod' === $this->container->getParameter('kernel.environment')) { - @trigger_error('Using WebProfilerBundle in production is not supported and puts your project at risk, disable it.', E_USER_WARNING); + @trigger_error('Using WebProfilerBundle in production is not supported and puts your project at risk, disable it.', \E_USER_WARNING); } } } diff --git a/src/Symfony/Component/Asset/UrlPackage.php b/src/Symfony/Component/Asset/UrlPackage.php index bc4da2435f71..43351027d89b 100644 --- a/src/Symfony/Component/Asset/UrlPackage.php +++ b/src/Symfony/Component/Asset/UrlPackage.php @@ -123,7 +123,7 @@ private function getSslUrls(array $urls) foreach ($urls as $url) { if ('https://' === substr($url, 0, 8) || '//' === substr($url, 0, 2)) { $sslUrls[] = $url; - } elseif (null === parse_url($url, PHP_URL_SCHEME)) { + } elseif (null === parse_url($url, \PHP_URL_SCHEME)) { throw new InvalidArgumentException(sprintf('"%s" is not a valid URL.', $url)); } } diff --git a/src/Symfony/Component/BrowserKit/AbstractBrowser.php b/src/Symfony/Component/BrowserKit/AbstractBrowser.php index 60f2fcb182b3..f8c89871149e 100644 --- a/src/Symfony/Component/BrowserKit/AbstractBrowser.php +++ b/src/Symfony/Component/BrowserKit/AbstractBrowser.php @@ -352,12 +352,12 @@ public function request(string $method, string $uri, array $parameters = [], arr $server = array_merge($this->server, $server); - if (!empty($server['HTTP_HOST']) && null === parse_url($originalUri, PHP_URL_HOST)) { + if (!empty($server['HTTP_HOST']) && null === parse_url($originalUri, \PHP_URL_HOST)) { $uri = preg_replace('{^(https?\://)'.preg_quote($this->extractHost($uri)).'}', '${1}'.$server['HTTP_HOST'], $uri); } - if (isset($server['HTTPS']) && null === parse_url($originalUri, PHP_URL_SCHEME)) { - $uri = preg_replace('{^'.parse_url($uri, PHP_URL_SCHEME).'}', $server['HTTPS'] ? 'https' : 'http', $uri); + if (isset($server['HTTPS']) && null === parse_url($originalUri, \PHP_URL_SCHEME)) { + $uri = preg_replace('{^'.parse_url($uri, \PHP_URL_SCHEME).'}', $server['HTTPS'] ? 'https' : 'http', $uri); } if (!isset($server['HTTP_REFERER']) && !$this->history->isEmpty()) { @@ -368,7 +368,7 @@ public function request(string $method, string $uri, array $parameters = [], arr $server['HTTP_HOST'] = $this->extractHost($uri); } - $server['HTTPS'] = 'https' == parse_url($uri, PHP_URL_SCHEME); + $server['HTTPS'] = 'https' == parse_url($uri, \PHP_URL_SCHEME); $this->internalRequest = new Request($uri, $method, $parameters, $files, $this->cookieJar->allValues($uri), $server, $content); @@ -437,9 +437,9 @@ protected function doRequestInProcess($request) foreach ($deprecations ? unserialize($deprecations) : [] as $deprecation) { if ($deprecation[0]) { // unsilenced on purpose - trigger_error($deprecation[1], E_USER_DEPRECATED); + trigger_error($deprecation[1], \E_USER_DEPRECATED); } else { - @trigger_error($deprecation[1], E_USER_DEPRECATED); + @trigger_error($deprecation[1], \E_USER_DEPRECATED); } } } @@ -653,7 +653,7 @@ protected function getAbsoluteUri(string $uri) // protocol relative URL if (0 === strpos($uri, '//')) { - return parse_url($currentUri, PHP_URL_SCHEME).':'.$uri; + return parse_url($currentUri, \PHP_URL_SCHEME).':'.$uri; } // anchor or query string parameters? @@ -662,7 +662,7 @@ protected function getAbsoluteUri(string $uri) } if ('/' !== $uri[0]) { - $path = parse_url($currentUri, PHP_URL_PATH); + $path = parse_url($currentUri, \PHP_URL_PATH); if ('/' !== substr($path, -1)) { $path = substr($path, 0, strrpos($path, '/') + 1); @@ -689,7 +689,7 @@ protected function requestFromRequest(Request $request, $changeHistory = true) private function updateServerFromUri(array $server, string $uri): array { $server['HTTP_HOST'] = $this->extractHost($uri); - $scheme = parse_url($uri, PHP_URL_SCHEME); + $scheme = parse_url($uri, \PHP_URL_SCHEME); $server['HTTPS'] = null === $scheme ? $server['HTTPS'] : 'https' == $scheme; unset($server['HTTP_IF_NONE_MATCH'], $server['HTTP_IF_MODIFIED_SINCE']); @@ -698,9 +698,9 @@ private function updateServerFromUri(array $server, string $uri): array private function extractHost(string $uri): ?string { - $host = parse_url($uri, PHP_URL_HOST); + $host = parse_url($uri, \PHP_URL_HOST); - if ($port = parse_url($uri, PHP_URL_PORT)) { + if ($port = parse_url($uri, \PHP_URL_PORT)) { return $host.':'.$port; } diff --git a/src/Symfony/Component/BrowserKit/HttpBrowser.php b/src/Symfony/Component/BrowserKit/HttpBrowser.php index ed6c10028145..6f5749c2642a 100644 --- a/src/Symfony/Component/BrowserKit/HttpBrowser.php +++ b/src/Symfony/Component/BrowserKit/HttpBrowser.php @@ -91,7 +91,7 @@ private function getBodyAndExtraHeaders(Request $request, array $headers): array return ['', []]; } - return [http_build_query($fields, '', '&', PHP_QUERY_RFC1738), ['Content-Type' => 'application/x-www-form-urlencoded']]; + return [http_build_query($fields, '', '&', \PHP_QUERY_RFC1738), ['Content-Type' => 'application/x-www-form-urlencoded']]; } private function getHeaders(Request $request): array diff --git a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php index 2b276f60b6c0..b2faae2840d3 100644 --- a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php @@ -112,7 +112,7 @@ public static function createSystemCache(string $namespace, int $defaultLifetime return $opcache; } - if (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && !filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN)) { + if (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && !filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN)) { return $opcache; } diff --git a/src/Symfony/Component/Cache/Adapter/ApcuAdapter.php b/src/Symfony/Component/Cache/Adapter/ApcuAdapter.php index 48d2f5ec4bb6..b4906382d0a8 100644 --- a/src/Symfony/Component/Cache/Adapter/ApcuAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/ApcuAdapter.php @@ -44,7 +44,7 @@ public function __construct(string $namespace = '', int $defaultLifetime = 0, st public static function isSupported() { - return \function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN); + return \function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), \FILTER_VALIDATE_BOOLEAN); } /** @@ -63,7 +63,7 @@ protected function doFetch(array $ids) return $values; } catch (\Error $e) { - throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine()); + throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine()); } finally { ini_set('unserialize_callback_func', $unserializeCallbackHandler); } @@ -82,8 +82,8 @@ protected function doHave(string $id) */ protected function doClear(string $namespace) { - return isset($namespace[0]) && class_exists('APCuIterator', false) && ('cli' !== \PHP_SAPI || filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN)) - ? apcu_delete(new \APCuIterator(sprintf('/^%s/', preg_quote($namespace, '/')), APC_ITER_KEY)) + return isset($namespace[0]) && class_exists('APCuIterator', false) && ('cli' !== \PHP_SAPI || filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN)) + ? apcu_delete(new \APCuIterator(sprintf('/^%s/', preg_quote($namespace, '/')), \APC_ITER_KEY)) : apcu_clear_cache(); } diff --git a/src/Symfony/Component/Cache/Adapter/ArrayAdapter.php b/src/Symfony/Component/Cache/Adapter/ArrayAdapter.php index 46f7e646f59e..63761947e7e9 100644 --- a/src/Symfony/Component/Cache/Adapter/ArrayAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/ArrayAdapter.php @@ -78,7 +78,7 @@ public function get(string $key, callable $callback, float $beta = null, array & $metadata = $item->getMetadata(); // ArrayAdapter works in memory, we don't care about stampede protection - if (INF === $beta || !$item->isHit()) { + if (\INF === $beta || !$item->isHit()) { $save = true; $this->save($item->set($callback($item, $save))); } @@ -197,7 +197,7 @@ public function save(CacheItemInterface $item) $now = microtime(true); if (0 === $expiry) { - $expiry = PHP_INT_MAX; + $expiry = \PHP_INT_MAX; } if (null !== $expiry && $expiry <= $now) { @@ -229,7 +229,7 @@ public function save(CacheItemInterface $item) } $this->values[$key] = $value; - $this->expiries[$key] = null !== $expiry ? $expiry : PHP_INT_MAX; + $this->expiries[$key] = null !== $expiry ? $expiry : \PHP_INT_MAX; return true; } diff --git a/src/Symfony/Component/Cache/Adapter/ChainAdapter.php b/src/Symfony/Component/Cache/Adapter/ChainAdapter.php index d2ff15eb9de0..1029bbff698f 100644 --- a/src/Symfony/Component/Cache/Adapter/ChainAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/ChainAdapter.php @@ -51,7 +51,7 @@ public function __construct(array $adapters, int $defaultLifetime = 0) if (!$adapter instanceof CacheItemPoolInterface) { throw new InvalidArgumentException(sprintf('The class "%s" does not implement the "%s" interface.', get_debug_type($adapter), CacheItemPoolInterface::class)); } - if (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && $adapter instanceof ApcuAdapter && !filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN)) { + if (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && $adapter instanceof ApcuAdapter && !filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN)) { continue; // skip putting APCu in the chain when the backend is disabled } @@ -95,7 +95,7 @@ public function get(string $key, callable $callback, float $beta = null, array & $adapter = $this->adapters[$i]; if (isset($this->adapters[++$i])) { $callback = $wrap; - $beta = INF === $beta ? INF : 0; + $beta = \INF === $beta ? \INF : 0; } if ($adapter instanceof CacheInterface) { $value = $adapter->get($key, $callback, $beta, $metadata); diff --git a/src/Symfony/Component/Cache/Adapter/DoctrineAdapter.php b/src/Symfony/Component/Cache/Adapter/DoctrineAdapter.php index 55a36e17f86c..dc70ea69738b 100644 --- a/src/Symfony/Component/Cache/Adapter/DoctrineAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/DoctrineAdapter.php @@ -52,7 +52,7 @@ protected function doFetch(array $ids) case 'unserialize': case 'apcu_fetch': case 'apc_fetch': - throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine()); + throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine()); } } diff --git a/src/Symfony/Component/Cache/Adapter/FilesystemTagAwareAdapter.php b/src/Symfony/Component/Cache/Adapter/FilesystemTagAwareAdapter.php index bf6bee659ea9..e5cbf90ce7ac 100644 --- a/src/Symfony/Component/Cache/Adapter/FilesystemTagAwareAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/FilesystemTagAwareAdapter.php @@ -72,7 +72,7 @@ protected function doClear(string $namespace) if (!is_dir($d = $dir.$chars[$i].\DIRECTORY_SEPARATOR.$chars[$j])) { continue; } - foreach (scandir($d, SCANDIR_SORT_NONE) ?: [] as $link) { + foreach (scandir($d, \SCANDIR_SORT_NONE) ?: [] as $link) { if ('.' !== $link && '..' !== $link && (null !== $renamed || !realpath($d.\DIRECTORY_SEPARATOR.$link))) { unlink($d.\DIRECTORY_SEPARATOR.$link); } diff --git a/src/Symfony/Component/Cache/Adapter/MemcachedAdapter.php b/src/Symfony/Component/Cache/Adapter/MemcachedAdapter.php index abf706a84442..038892eabc3b 100644 --- a/src/Symfony/Component/Cache/Adapter/MemcachedAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/MemcachedAdapter.php @@ -22,6 +22,15 @@ */ class MemcachedAdapter extends AbstractAdapter { + /** + * We are replacing characters that are illegal in Memcached keys with reserved characters from + * {@see \Symfony\Contracts\Cache\ItemInterface::RESERVED_CHARACTERS} that are legal in Memcached. +This conversation was marked as resolved by lstrojny + * Note: don’t use {@see \Symfony\Component\Cache\Adapter\AbstractAdapter::NS_SEPARATOR}. + */ + private const RESERVED_MEMCACHED = " \n\r\t\v\f\0"; + private const RESERVED_PSR6 = '@()\{}/'; + protected $maxIdLength = 250; private static $defaultClientOptions = [ @@ -172,7 +181,7 @@ public static function createConnection($servers, array $options = []) // set client's options unset($options['persistent_id'], $options['username'], $options['password'], $options['weight'], $options['lazy']); - $options = array_change_key_case($options, CASE_UPPER); + $options = array_change_key_case($options, \CASE_UPPER); $client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true); $client->setOption(\Memcached::OPT_NO_BLOCK, true); $client->setOption(\Memcached::OPT_TCP_NODELAY, true); @@ -246,7 +255,7 @@ protected function doSave(array $values, int $lifetime) $encodedValues = []; foreach ($values as $key => $value) { - $encodedValues[rawurlencode($key)] = $value; + $encodedValues[self::encodeKey($key)] = $value; } return $this->checkResultCode($this->getClient()->setMulti($encodedValues, $lifetime)) ? $failed : false; @@ -258,18 +267,18 @@ protected function doSave(array $values, int $lifetime) protected function doFetch(array $ids) { try { - $encodedIds = array_map('rawurlencode', $ids); + $encodedIds = array_map('self::encodeKey', $ids); $encodedResult = $this->checkResultCode($this->getClient()->getMulti($encodedIds)); $result = []; foreach ($encodedResult as $key => $value) { - $result[rawurldecode($key)] = $this->marshaller->unmarshall($value); + $result[self::decodeKey($key)] = $this->marshaller->unmarshall($value); } return $result; } catch (\Error $e) { - throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine()); + throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine()); } } @@ -278,7 +287,7 @@ protected function doFetch(array $ids) */ protected function doHave(string $id) { - return false !== $this->getClient()->get(rawurlencode($id)) || $this->checkResultCode(\Memcached::RES_SUCCESS === $this->client->getResultCode()); + return false !== $this->getClient()->get(self::encodeKey($id)) || $this->checkResultCode(\Memcached::RES_SUCCESS === $this->client->getResultCode()); } /** @@ -287,7 +296,7 @@ protected function doHave(string $id) protected function doDelete(array $ids) { $ok = true; - $encodedIds = array_map('rawurlencode', $ids); + $encodedIds = array_map('self::encodeKey', $ids); foreach ($this->checkResultCode($this->getClient()->deleteMulti($encodedIds)) as $result) { if (\Memcached::RES_SUCCESS !== $result && \Memcached::RES_NOTFOUND !== $result) { $ok = false; @@ -332,4 +341,14 @@ private function getClient(): \Memcached return $this->client = $this->lazyClient; } + + private static function encodeKey(string $key): string + { + return strtr($key, self::RESERVED_MEMCACHED, self::RESERVED_PSR6); + } + + private static function decodeKey(string $key): string + { + return strtr($key, self::RESERVED_PSR6, self::RESERVED_MEMCACHED); + } } diff --git a/src/Symfony/Component/Cache/Adapter/PdoAdapter.php b/src/Symfony/Component/Cache/Adapter/PdoAdapter.php index 278152bc8fce..e4a3123c9ca8 100644 --- a/src/Symfony/Component/Cache/Adapter/PdoAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/PdoAdapter.php @@ -17,6 +17,7 @@ use Doctrine\DBAL\Driver\Result as DriverResult; use Doctrine\DBAL\Driver\ServerInfoAwareConnection; use Doctrine\DBAL\DriverManager; +use Doctrine\DBAL\Exception; use Doctrine\DBAL\Exception\TableNotFoundException; use Doctrine\DBAL\Schema\Schema; use Symfony\Component\Cache\Exception\InvalidArgumentException; @@ -109,6 +110,7 @@ public function __construct($connOrDsn, string $namespace = '', int $defaultLife * * @throws \PDOException When the table already exists * @throws DBALException When the table already exists + * @throws Exception When the table already exists * @throws \DomainException When an unsupported PDO driver is used */ public function createTable() @@ -417,7 +419,7 @@ protected function doSave(array $values, int $lifetime) if (null === $driver && !($result instanceof DriverResult ? $result : $stmt)->rowCount()) { try { $insertStmt->execute(); - } catch (DBALException $e) { + } catch (DBALException | Exception $e) { } catch (\PDOException $e) { // A concurrent write won, let it be } diff --git a/src/Symfony/Component/Cache/Adapter/PhpFilesAdapter.php b/src/Symfony/Component/Cache/Adapter/PhpFilesAdapter.php index ebdb8409788c..d3ac2293c046 100644 --- a/src/Symfony/Component/Cache/Adapter/PhpFilesAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/PhpFilesAdapter.php @@ -58,7 +58,7 @@ public static function isSupported() { self::$startTime = self::$startTime ?? $_SERVER['REQUEST_TIME'] ?? time(); - return \function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) || filter_var(ini_get('opcache.enable_cli'), FILTER_VALIDATE_BOOLEAN)); + return \function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) || filter_var(ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOLEAN)); } /** diff --git a/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php b/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php index c6667a9fbc3c..9527fa63ffae 100644 --- a/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php @@ -88,7 +88,7 @@ static function (CacheItemInterface $innerItem, array $item) { $item["\0*\0value"] = ["\x9D".pack('VN', (int) (0.1 + $metadata[self::METADATA_EXPIRY] - self::METADATA_EXPIRY_OFFSET), $metadata[self::METADATA_CTIME])."\x5F" => $item["\0*\0value"]]; } $innerItem->set($item["\0*\0value"]); - $innerItem->expiresAt(null !== $item["\0*\0expiry"] ? \DateTime::createFromFormat('U.u', sprintf('%.6f', $item["\0*\0expiry"])) : null); + $innerItem->expiresAt(null !== $item["\0*\0expiry"] ? \DateTime::createFromFormat('U.u', sprintf('%.6f', 0 === $item["\0*\0expiry"] ? \PHP_INT_MAX : $item["\0*\0expiry"])) : null); }, null, CacheItem::class diff --git a/src/Symfony/Component/Cache/CacheItem.php b/src/Symfony/Component/Cache/CacheItem.php index 295b0c136697..deb23ad3432f 100644 --- a/src/Symfony/Component/Cache/CacheItem.php +++ b/src/Symfony/Component/Cache/CacheItem.php @@ -119,9 +119,10 @@ public function tag($tags): ItemInterface $tags = [$tags]; } foreach ($tags as $tag) { - if (!\is_string($tag)) { - throw new InvalidArgumentException(sprintf('Cache tag must be string, "%s" given.', get_debug_type($tag))); + if (!\is_string($tag) && !(\is_object($tag) && method_exists($tag, '__toString'))) { + throw new InvalidArgumentException(sprintf('Cache tag must be string or object that implements __toString(), "%s" given.', \is_object($tag) ? \get_class($tag) : \gettype($tag))); } + $tag = (string) $tag; if (isset($this->newMetadata[self::METADATA_TAGS][$tag])) { continue; } @@ -183,7 +184,7 @@ public static function log(?LoggerInterface $logger, string $message, array $con $replace['{'.$k.'}'] = $v; } } - @trigger_error(strtr($message, $replace), E_USER_WARNING); + @trigger_error(strtr($message, $replace), \E_USER_WARNING); } } } diff --git a/src/Symfony/Component/Cache/DependencyInjection/CacheCollectorPass.php b/src/Symfony/Component/Cache/DependencyInjection/CacheCollectorPass.php index b534e5dc8a7f..6bbab9da4f47 100644 --- a/src/Symfony/Component/Cache/DependencyInjection/CacheCollectorPass.php +++ b/src/Symfony/Component/Cache/DependencyInjection/CacheCollectorPass.php @@ -47,15 +47,13 @@ public function process(ContainerBuilder $container) } foreach ($container->findTaggedServiceIds($this->cachePoolTag) as $id => $attributes) { - $this->addToCollector($id, $container); + $poolName = $attributes[0]['name'] ?? $id; - if (($attributes[0]['name'] ?? $id) !== $id) { - $this->addToCollector($attributes[0]['name'], $container); - } + $this->addToCollector($id, $poolName, $container); } } - private function addToCollector(string $id, ContainerBuilder $container) + private function addToCollector(string $id, string $name, ContainerBuilder $container) { $definition = $container->getDefinition($id); if ($definition->isAbstract()) { @@ -77,7 +75,7 @@ private function addToCollector(string $id, ContainerBuilder $container) $container->setDefinition($id, $recorder); // Tell the collector to add the new instance - $collectorDefinition->addMethodCall('addInstance', [$id, new Reference($id)]); + $collectorDefinition->addMethodCall('addInstance', [$name, new Reference($id)]); $collectorDefinition->setPublic(false); } } diff --git a/src/Symfony/Component/Cache/LockRegistry.php b/src/Symfony/Component/Cache/LockRegistry.php index ac2670c23137..c2ad45cdef3a 100644 --- a/src/Symfony/Component/Cache/LockRegistry.php +++ b/src/Symfony/Component/Cache/LockRegistry.php @@ -70,7 +70,7 @@ public static function setFiles(array $files): array foreach (self::$openedFiles as $file) { if ($file) { - flock($file, LOCK_UN); + flock($file, \LOCK_UN); fclose($file); } } @@ -90,7 +90,7 @@ public static function compute(callable $callback, ItemInterface $item, bool &$s while (true) { try { // race to get the lock in non-blocking mode - $locked = flock($lock, LOCK_EX | LOCK_NB, $wouldBlock); + $locked = flock($lock, \LOCK_EX | \LOCK_NB, $wouldBlock); if ($locked || !$wouldBlock) { $logger && $logger->info(sprintf('Lock %s, now computing item "{key}"', $locked ? 'acquired' : 'not supported'), ['key' => $item->getKey()]); @@ -111,9 +111,9 @@ public static function compute(callable $callback, ItemInterface $item, bool &$s } // if we failed the race, retry locking in blocking mode to wait for the winner $logger && $logger->info('Item "{key}" is locked, waiting for it to be released', ['key' => $item->getKey()]); - flock($lock, LOCK_SH); + flock($lock, \LOCK_SH); } finally { - flock($lock, LOCK_UN); + flock($lock, \LOCK_UN); unset(self::$lockedFiles[$key]); } static $signalingException, $signalingCallback; diff --git a/src/Symfony/Component/Cache/Marshaller/DefaultMarshaller.php b/src/Symfony/Component/Cache/Marshaller/DefaultMarshaller.php index 62f1a9082b1a..e00c8f4845c2 100644 --- a/src/Symfony/Component/Cache/Marshaller/DefaultMarshaller.php +++ b/src/Symfony/Component/Cache/Marshaller/DefaultMarshaller.php @@ -83,7 +83,7 @@ public function unmarshall(string $value) throw new \DomainException(error_get_last() ? error_get_last()['message'] : 'Failed to unserialize values.'); } catch (\Error $e) { - throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine()); + throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine()); } finally { ini_set('unserialize_callback_func', $unserializeCallbackHandler); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php b/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php index a8569406348e..05b863d1ac11 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php @@ -58,7 +58,7 @@ public function testGet() $isHit = false; $this->assertTrue($item->isHit()); $this->assertSame($value, $item->get()); - }, INF)); + }, \INF)); $this->assertFalse($isHit); $this->assertSame($value, $cache->get('bar', new class($value) implements CallbackInterface { diff --git a/src/Symfony/Component/Cache/Tests/Adapter/ApcuAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/ApcuAdapterTest.php index a4a7fc1b58ca..120a4e5a17a4 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/ApcuAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/ApcuAdapterTest.php @@ -25,10 +25,10 @@ class ApcuAdapterTest extends AdapterTestCase public function createCachePool(int $defaultLifetime = 0): CacheItemPoolInterface { - if (!\function_exists('apcu_fetch') || !filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN)) { + if (!\function_exists('apcu_fetch') || !filter_var(ini_get('apc.enabled'), \FILTER_VALIDATE_BOOLEAN)) { $this->markTestSkipped('APCu extension is required.'); } - if ('cli' === \PHP_SAPI && !filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN)) { + if ('cli' === \PHP_SAPI && !filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN)) { if ('testWithCliSapi' !== $this->getName()) { $this->markTestSkipped('apc.enable_cli=1 is required.'); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php index 3e723f1b6a0b..53295a1eef0e 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php @@ -16,8 +16,8 @@ use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\Adapter\ChainAdapter; use Symfony\Component\Cache\Adapter\FilesystemAdapter; -use Symfony\Component\Cache\PruneableInterface; use Symfony\Component\Cache\Tests\Fixtures\ExternalAdapter; +use Symfony\Component\Cache\Tests\Fixtures\PrunableAdapter; /** * @author Kévin Dunglas @@ -189,7 +189,7 @@ public function testMultipleCachesExpirationWhenCommonTtlIsSet() private function getPruneableMock(): AdapterInterface { - $pruneable = $this->createMock([PruneableInterface::class, AdapterInterface::class]); + $pruneable = $this->createMock(PrunableAdapter::class); $pruneable ->expects($this->atLeastOnce()) @@ -201,7 +201,7 @@ private function getPruneableMock(): AdapterInterface private function getFailingPruneableMock(): AdapterInterface { - $pruneable = $this->createMock([PruneableInterface::class, AdapterInterface::class]); + $pruneable = $this->createMock(PrunableAdapter::class); $pruneable ->expects($this->atLeastOnce()) diff --git a/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php index 5600d8b72b97..26609ff44386 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php @@ -42,11 +42,11 @@ public static function setUpBeforeClass(): void } } - public function createCachePool(int $defaultLifetime = 0): CacheItemPoolInterface + public function createCachePool(int $defaultLifetime = 0, string $testMethod = null, string $namespace = null): CacheItemPoolInterface { $client = $defaultLifetime ? AbstractAdapter::createConnection('memcached://'.getenv('MEMCACHED_HOST')) : self::$client; - return new MemcachedAdapter($client, str_replace('\\', '.', __CLASS__), $defaultLifetime); + return new MemcachedAdapter($client, $namespace ?? str_replace('\\', '.', __CLASS__), $defaultLifetime); } public function testOptions() @@ -146,7 +146,7 @@ public function provideServersSetting(): iterable 'localhost', 11222, ]; - if (filter_var(ini_get('memcached.use_sasl'), FILTER_VALIDATE_BOOLEAN)) { + if (filter_var(ini_get('memcached.use_sasl'), \FILTER_VALIDATE_BOOLEAN)) { yield [ 'memcached://user:password@127.0.0.1?weight=50', '127.0.0.1', @@ -163,7 +163,7 @@ public function provideServersSetting(): iterable '/var/local/run/memcached.socket', 0, ]; - if (filter_var(ini_get('memcached.use_sasl'), FILTER_VALIDATE_BOOLEAN)) { + if (filter_var(ini_get('memcached.use_sasl'), \FILTER_VALIDATE_BOOLEAN)) { yield [ 'memcached://user:password@/var/local/run/memcached.socket?weight=25', '/var/local/run/memcached.socket', @@ -248,4 +248,36 @@ public function testMultiServerDsn() ]; $this->assertSame($expected, $client->getServerList()); } + + public function testKeyEncoding() + { + $reservedMemcachedCharacters = " \n\r\t\v\f\0"; + + $namespace = $reservedMemcachedCharacters.random_int(0, \PHP_INT_MAX); + $pool = $this->createCachePool(0, null, $namespace); + + /** + * Choose a key that is below {@see \Symfony\Component\Cache\Adapter\MemcachedAdapter::$maxIdLength} so that + * {@see \Symfony\Component\Cache\Traits\AbstractTrait::getId()} does not shorten the key but choose special + * characters that would be encoded and therefore increase the key length over the Memcached limit. + */ + // 250 is Memcached’s max key length, 7 bytes for prefix seed + $key = str_repeat('%', 250 - 7 - \strlen($reservedMemcachedCharacters) - \strlen($namespace)).$reservedMemcachedCharacters; + + self::assertFalse($pool->hasItem($key)); + + $item = $pool->getItem($key); + self::assertFalse($item->isHit()); + self::assertSame($key, $item->getKey()); + + self::assertTrue($pool->save($item->set('foobar'))); + + self::assertTrue($pool->hasItem($key)); + $item = $pool->getItem($key); + self::assertTrue($item->isHit()); + self::assertSame($key, $item->getKey()); + + self::assertTrue($pool->deleteItem($key)); + self::assertFalse($pool->hasItem($key)); + } } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php index e0111c1d6cc5..4d60f4cbd418 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php @@ -18,7 +18,7 @@ use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Component\Cache\Adapter\TagAwareAdapter; -use Symfony\Component\Cache\PruneableInterface; +use Symfony\Component\Cache\Tests\Fixtures\PrunableAdapter; use Symfony\Component\Cache\Tests\Traits\TagAwareTestTrait; /** @@ -204,7 +204,7 @@ public function testGetItemReturnsCacheMissWhenPoolDoesNotHaveItemAndOnlyHasTags */ private function getPruneableMock(): AdapterInterface { - $pruneable = $this->createMock([PruneableInterface::class, AdapterInterface::class]); + $pruneable = $this->createMock(PrunableAdapter::class); $pruneable ->expects($this->atLeastOnce()) @@ -216,7 +216,7 @@ private function getPruneableMock(): AdapterInterface private function getFailingPruneableMock(): AdapterInterface { - $pruneable = $this->createMock([PruneableInterface::class, AdapterInterface::class]); + $pruneable = $this->createMock(PrunableAdapter::class); $pruneable ->expects($this->atLeastOnce()) diff --git a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAndProxyAdapterIntegrationTest.php b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAndProxyAdapterIntegrationTest.php index e53b40702860..4f30fdddd1b4 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAndProxyAdapterIntegrationTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAndProxyAdapterIntegrationTest.php @@ -24,6 +24,29 @@ public function testIntegrationUsingProxiedAdapter(CacheItemPoolInterface $proxi $cache->save($item); $this->assertSame('bar', $cache->getItem('foo')->get()); + + $cache->invalidateTags(['tag2']); + + $this->assertFalse($cache->getItem('foo')->isHit()); + } + + public function testIntegrationUsingProxiedAdapterForTagsPool() + { + $arrayAdapter = new ArrayAdapter(); + $cache = new TagAwareAdapter($arrayAdapter, new ProxyAdapter($arrayAdapter)); + + $item = $cache->getItem('foo'); + $item->expiresAfter(600); + $item->tag(['baz']); + $item->set('bar'); + $cache->save($item); + + $this->assertSame('bar', $cache->getItem('foo')->get()); + $this->assertTrue($cache->getItem('foo')->isHit()); + + $cache->invalidateTags(['baz']); + + $this->assertFalse($cache->getItem('foo')->isHit()); } public function dataProvider(): array diff --git a/src/Symfony/Component/Cache/Tests/CacheItemTest.php b/src/Symfony/Component/Cache/Tests/CacheItemTest.php index 3b756f571f69..01914e4a36db 100644 --- a/src/Symfony/Component/Cache/Tests/CacheItemTest.php +++ b/src/Symfony/Component/Cache/Tests/CacheItemTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Cache\CacheItem; +use Symfony\Component\Cache\Tests\Fixtures\StringableTag; class CacheItemTest extends TestCase { @@ -61,9 +62,11 @@ public function testTag() $this->assertSame($item, $item->tag('foo')); $this->assertSame($item, $item->tag(['bar', 'baz'])); + $this->assertSame($item, $item->tag(new StringableTag('qux'))); + $this->assertSame($item, $item->tag([new StringableTag('quux'), new StringableTag('quuux')])); (\Closure::bind(function () use ($item) { - $this->assertSame(['foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz'], $item->newMetadata[CacheItem::METADATA_TAGS]); + $this->assertSame(['foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz', 'qux' => 'qux', 'quux' => 'quux', 'quuux' => 'quuux'], $item->newMetadata[CacheItem::METADATA_TAGS]); }, $this, CacheItem::class))(); } diff --git a/src/Symfony/Component/Cache/Tests/DependencyInjection/CacheCollectorPassTest.php b/src/Symfony/Component/Cache/Tests/DependencyInjection/CacheCollectorPassTest.php index 8aff19fc3e14..d0ea55313b88 100644 --- a/src/Symfony/Component/Cache/Tests/DependencyInjection/CacheCollectorPassTest.php +++ b/src/Symfony/Component/Cache/Tests/DependencyInjection/CacheCollectorPassTest.php @@ -19,6 +19,8 @@ use Symfony\Component\Cache\Adapter\TraceableTagAwareAdapter; use Symfony\Component\Cache\DataCollector\CacheDataCollector; use Symfony\Component\Cache\DependencyInjection\CacheCollectorPass; +use Symfony\Component\Cache\Tests\Fixtures\ArrayCache; +use Symfony\Component\DependencyInjection\Compiler\PassConfig; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; @@ -48,16 +50,51 @@ public function testProcess() $this->assertEquals([ ['addInstance', ['fs', new Reference('fs')]], ['addInstance', ['tagged_fs', new Reference('tagged_fs')]], - ['addInstance', ['.php.inner', new Reference('.php.inner')]], - ['addInstance', ['php', new Reference('php')]], + ['addInstance', ['php', new Reference('.php.inner')]], ], $collector->getMethodCalls()); $this->assertSame(TraceableAdapter::class, $container->findDefinition('fs')->getClass()); $this->assertSame(TraceableTagAwareAdapter::class, $container->getDefinition('tagged_fs')->getClass()); $this->assertSame(TraceableAdapter::class, $container->findDefinition('.php.inner')->getClass()); - $this->assertSame(TraceableTagAwareAdapter::class, $container->getDefinition('php')->getClass()); + $this->assertSame(TagAwareAdapter::class, $container->getDefinition('php')->getClass()); $this->assertFalse($collector->isPublic(), 'The "data_collector.cache" should be private after processing'); } + + public function testProcessCacheObjectsAreDecorated() + { + $container = new ContainerBuilder(); + $collector = $container->register('data_collector.cache', CacheDataCollector::class); + + $container + ->register('cache.object', ArrayCache::class) + ->addTag('cache.pool', ['name' => 'cache.object']); + + $container + ->register('something_is_decorating_cache_object', TagAwareAdapter::class) + ->setPublic(true) + ->setDecoratedService('cache.object'); + + $container->register('some_service_using_cache_object', TraceableAdapter::class) + ->setPublic(true) + ->addArgument(new Reference('cache.object')); + + $container->addCompilerPass(new CacheCollectorPass(), PassConfig::TYPE_BEFORE_REMOVING); + + $container->compile(); + $this->assertCount(1, $collector->getMethodCalls()); + $this->assertEquals( + [ + [ + 'addInstance', + [ + 'cache.object', + new Reference('something_is_decorating_cache_object'), + ], + ], + ], + $collector->getMethodCalls() + ); + } } diff --git a/src/Symfony/Component/Cache/Tests/Fixtures/PrunableAdapter.php b/src/Symfony/Component/Cache/Tests/Fixtures/PrunableAdapter.php new file mode 100644 index 000000000000..9668ed595fa6 --- /dev/null +++ b/src/Symfony/Component/Cache/Tests/Fixtures/PrunableAdapter.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Cache\Tests\Fixtures; + +use Symfony\Component\Cache\Adapter\AdapterInterface; +use Symfony\Component\Cache\PruneableInterface; + +abstract class PrunableAdapter implements AdapterInterface, PruneableInterface +{ +} diff --git a/src/Symfony/Component/Cache/Tests/Fixtures/PrunableCache.php b/src/Symfony/Component/Cache/Tests/Fixtures/PrunableCache.php new file mode 100644 index 000000000000..c1b3f740129d --- /dev/null +++ b/src/Symfony/Component/Cache/Tests/Fixtures/PrunableCache.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Cache\Tests\Fixtures; + +use Psr\SimpleCache\CacheInterface; +use Symfony\Component\Cache\PruneableInterface; + +abstract class PrunableCache implements CacheInterface, PruneableInterface +{ +} diff --git a/src/Symfony/Component/Cache/Tests/Fixtures/StringableTag.php b/src/Symfony/Component/Cache/Tests/Fixtures/StringableTag.php new file mode 100644 index 000000000000..caaf55c026e0 --- /dev/null +++ b/src/Symfony/Component/Cache/Tests/Fixtures/StringableTag.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Cache\Tests\Fixtures; + +class StringableTag +{ + /** + * @var string + */ + private $tag; + + public function __construct(string $tag) + { + $this->tag = $tag; + } + + public function __toString(): string + { + return $this->tag; + } +} diff --git a/src/Symfony/Component/Cache/Traits/AbstractAdapterTrait.php b/src/Symfony/Component/Cache/Traits/AbstractAdapterTrait.php index 5e102bf318ad..de3dbfc7a8b3 100644 --- a/src/Symfony/Component/Cache/Traits/AbstractAdapterTrait.php +++ b/src/Symfony/Component/Cache/Traits/AbstractAdapterTrait.php @@ -128,7 +128,7 @@ public function clear(string $prefix = '') } } $namespaceToClear = $this->namespace.$namespaceVersionToClear; - $namespaceVersion = substr_replace(base64_encode(pack('V', mt_rand())), static::NS_SEPARATOR, 5); + $namespaceVersion = strtr(substr_replace(base64_encode(pack('V', mt_rand())), static::NS_SEPARATOR, 5), '/', '_'); try { $cleared = $this->doSave([static::NS_SEPARATOR.$this->namespace => $namespaceVersion], 0); } catch (\Exception $e) { @@ -340,7 +340,7 @@ private function generateItems(iterable $items, array &$keys): iterable try { foreach ($items as $id => $value) { if (!isset($keys[$id])) { - $id = key($keys); + throw new InvalidArgumentException(sprintf('Could not match value id "%s" to keys "%s".', $id, implode('", "', $keys))); } $key = $keys[$id]; unset($keys[$id]); @@ -365,7 +365,7 @@ private function getId($key) $this->namespaceVersion = $v; } if ('1'.static::NS_SEPARATOR === $this->namespaceVersion) { - $this->namespaceVersion = substr_replace(base64_encode(pack('V', time())), static::NS_SEPARATOR, 5); + $this->namespaceVersion = strtr(substr_replace(base64_encode(pack('V', time())), static::NS_SEPARATOR, 5), '/', '_'); $this->doSave([static::NS_SEPARATOR.$this->namespace => $this->namespaceVersion], 0); } } catch (\Exception $e) { diff --git a/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php b/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php index 3f2d49d412e3..99413a6b62e5 100644 --- a/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php +++ b/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php @@ -143,7 +143,7 @@ private function scanHashDir(string $directory): \Generator continue; } - foreach (@scandir($dir, SCANDIR_SORT_NONE) ?: [] as $file) { + foreach (@scandir($dir, \SCANDIR_SORT_NONE) ?: [] as $file) { if ('.' !== $file && '..' !== $file) { yield $dir.\DIRECTORY_SEPARATOR.$file; } diff --git a/src/Symfony/Component/Cache/Traits/MemcachedTrait.php b/src/Symfony/Component/Cache/Traits/MemcachedTrait.php new file mode 100644 index 000000000000..468656e333fa --- /dev/null +++ b/src/Symfony/Component/Cache/Traits/MemcachedTrait.php @@ -0,0 +1,343 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Cache\Traits; + +use Symfony\Component\Cache\Exception\CacheException; +use Symfony\Component\Cache\Exception\InvalidArgumentException; +use Symfony\Component\Cache\Marshaller\DefaultMarshaller; +use Symfony\Component\Cache\Marshaller\MarshallerInterface; + +/** + * @author Rob Frawley 2nd + * @author Nicolas Grekas + * + * @internal + */ +trait MemcachedTrait +{ + private static $defaultClientOptions = [ + 'persistent_id' => null, + 'username' => null, + 'password' => null, + \Memcached::OPT_SERIALIZER => \Memcached::SERIALIZER_PHP, + ]; + + /** + * We are replacing characters that are illegal in Memcached keys with reserved characters from + * {@see \Symfony\Contracts\Cache\ItemInterface::RESERVED_CHARACTERS} that are legal in Memcached. + * Note: don’t use {@see \Symfony\Component\Cache\Adapter\AbstractAdapter::NS_SEPARATOR}. + */ + private static $RESERVED_MEMCACHED = " \n\r\t\v\f\0"; + private static $RESERVED_PSR6 = '@()\{}/'; + + private $marshaller; + private $client; + private $lazyClient; + + public static function isSupported() + { + return \extension_loaded('memcached') && version_compare(phpversion('memcached'), '2.2.0', '>='); + } + + private function init(\Memcached $client, string $namespace, int $defaultLifetime, ?MarshallerInterface $marshaller) + { + if (!static::isSupported()) { + throw new CacheException('Memcached >= 2.2.0 is required.'); + } + if ('Memcached' === \get_class($client)) { + $opt = $client->getOption(\Memcached::OPT_SERIALIZER); + if (\Memcached::SERIALIZER_PHP !== $opt && \Memcached::SERIALIZER_IGBINARY !== $opt) { + throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".'); + } + $this->maxIdLength -= \strlen($client->getOption(\Memcached::OPT_PREFIX_KEY)); + $this->client = $client; + } else { + $this->lazyClient = $client; + } + + parent::__construct($namespace, $defaultLifetime); + $this->enableVersioning(); + $this->marshaller = $marshaller ?? new DefaultMarshaller(); + } + + /** + * Creates a Memcached instance. + * + * By default, the binary protocol, no block, and libketama compatible options are enabled. + * + * Examples for servers: + * - 'memcached://user:pass@localhost?weight=33' + * - [['localhost', 11211, 33]] + * + * @param array[]|string|string[] $servers An array of servers, a DSN, or an array of DSNs + * + * @return \Memcached + * + * @throws \ErrorException When invalid options or servers are provided + */ + public static function createConnection($servers, array $options = []) + { + if (\is_string($servers)) { + $servers = [$servers]; + } elseif (!\is_array($servers)) { + throw new InvalidArgumentException(sprintf('MemcachedAdapter::createClient() expects array or string as first argument, "%s" given.', \gettype($servers))); + } + if (!static::isSupported()) { + throw new CacheException('Memcached >= 2.2.0 is required.'); + } + set_error_handler(function ($type, $msg, $file, $line) { throw new \ErrorException($msg, 0, $type, $file, $line); }); + try { + $options += static::$defaultClientOptions; + $client = new \Memcached($options['persistent_id']); + $username = $options['username']; + $password = $options['password']; + + // parse any DSN in $servers + foreach ($servers as $i => $dsn) { + if (\is_array($dsn)) { + continue; + } + if (0 !== strpos($dsn, 'memcached:')) { + throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: "%s" does not start with "memcached:".', $dsn)); + } + $params = preg_replace_callback('#^memcached:(//)?(?:([^@]*+)@)?#', function ($m) use (&$username, &$password) { + if (!empty($m[2])) { + list($username, $password) = explode(':', $m[2], 2) + [1 => null]; + } + + return 'file:'.($m[1] ?? ''); + }, $dsn); + if (false === $params = parse_url($params)) { + throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: "%s".', $dsn)); + } + $query = $hosts = []; + if (isset($params['query'])) { + parse_str($params['query'], $query); + + if (isset($query['host'])) { + if (!\is_array($hosts = $query['host'])) { + throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: "%s".', $dsn)); + } + foreach ($hosts as $host => $weight) { + if (false === $port = strrpos($host, ':')) { + $hosts[$host] = [$host, 11211, (int) $weight]; + } else { + $hosts[$host] = [substr($host, 0, $port), (int) substr($host, 1 + $port), (int) $weight]; + } + } + $hosts = array_values($hosts); + unset($query['host']); + } + if ($hosts && !isset($params['host']) && !isset($params['path'])) { + unset($servers[$i]); + $servers = array_merge($servers, $hosts); + continue; + } + } + if (!isset($params['host']) && !isset($params['path'])) { + throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: "%s".', $dsn)); + } + if (isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) { + $params['weight'] = $m[1]; + $params['path'] = substr($params['path'], 0, -\strlen($m[0])); + } + $params += [ + 'host' => isset($params['host']) ? $params['host'] : $params['path'], + 'port' => isset($params['host']) ? 11211 : null, + 'weight' => 0, + ]; + if ($query) { + $params += $query; + $options = $query + $options; + } + + $servers[$i] = [$params['host'], $params['port'], $params['weight']]; + + if ($hosts) { + $servers = array_merge($servers, $hosts); + } + } + + // set client's options + unset($options['persistent_id'], $options['username'], $options['password'], $options['weight'], $options['lazy']); + $options = array_change_key_case($options, \CASE_UPPER); + $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)) { + $client->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true); + } + foreach ($options as $name => $value) { + if (\is_int($name)) { + continue; + } + if ('HASH' === $name || 'SERIALIZER' === $name || 'DISTRIBUTION' === $name) { + $value = \constant('Memcached::'.$name.'_'.strtoupper($value)); + } + $opt = \constant('Memcached::OPT_'.$name); + + unset($options[$name]); + $options[$opt] = $value; + } + $client->setOptions($options); + + // set client's servers, taking care of persistent connections + if (!$client->isPristine()) { + $oldServers = []; + foreach ($client->getServerList() as $server) { + $oldServers[] = [$server['host'], $server['port']]; + } + + $newServers = []; + foreach ($servers as $server) { + if (1 < \count($server)) { + $server = array_values($server); + unset($server[2]); + $server[1] = (int) $server[1]; + } + $newServers[] = $server; + } + + if ($oldServers !== $newServers) { + $client->resetServerList(); + $client->addServers($servers); + } + } else { + $client->addServers($servers); + } + + if (null !== $username || null !== $password) { + if (!method_exists($client, 'setSaslAuthData')) { + trigger_error('Missing SASL support: the memcached extension must be compiled with --enable-memcached-sasl.'); + } + $client->setSaslAuthData($username, $password); + } + + return $client; + } finally { + restore_error_handler(); + } + } + + /** + * {@inheritdoc} + */ + protected function doSave(array $values, int $lifetime) + { + if (!$values = $this->marshaller->marshall($values, $failed)) { + return $failed; + } + + if ($lifetime && $lifetime > 30 * 86400) { + $lifetime += time(); + } + + $encodedValues = []; + foreach ($values as $key => $value) { + $encodedValues[self::encodeKey($key)] = $value; + } + + return $this->checkResultCode($this->getClient()->setMulti($encodedValues, $lifetime)) ? $failed : false; + } + + /** + * {@inheritdoc} + */ + protected function doFetch(array $ids) + { + try { + $encodedIds = array_map('self::encodeKey', $ids); + + $encodedResult = $this->checkResultCode($this->getClient()->getMulti($encodedIds)); + + $result = []; + foreach ($encodedResult as $key => $value) { + $result[self::decodeKey($key)] = $this->marshaller->unmarshall($value); + } + + return $result; + } catch (\Error $e) { + throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine()); + } + } + + /** + * {@inheritdoc} + */ + protected function doHave($id) + { + return false !== $this->getClient()->get(self::encodeKey($id)) || $this->checkResultCode(\Memcached::RES_SUCCESS === $this->client->getResultCode()); + } + + /** + * {@inheritdoc} + */ + protected function doDelete(array $ids) + { + $ok = true; + $encodedIds = array_map('self::encodeKey', $ids); + foreach ($this->checkResultCode($this->getClient()->deleteMulti($encodedIds)) as $result) { + if (\Memcached::RES_SUCCESS !== $result && \Memcached::RES_NOTFOUND !== $result) { + $ok = false; + break; + } + } + + return $ok; + } + + /** + * {@inheritdoc} + */ + protected function doClear($namespace) + { + return '' === $namespace && $this->getClient()->flush(); + } + + private function checkResultCode($result) + { + $code = $this->client->getResultCode(); + + if (\Memcached::RES_SUCCESS === $code || \Memcached::RES_NOTFOUND === $code) { + return $result; + } + + throw new CacheException('MemcachedAdapter client error: '.strtolower($this->client->getResultMessage())); + } + + private function getClient(): \Memcached + { + if ($this->client) { + return $this->client; + } + + $opt = $this->lazyClient->getOption(\Memcached::OPT_SERIALIZER); + if (\Memcached::SERIALIZER_PHP !== $opt && \Memcached::SERIALIZER_IGBINARY !== $opt) { + throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".'); + } + if ('' !== $prefix = (string) $this->lazyClient->getOption(\Memcached::OPT_PREFIX_KEY)) { + throw new CacheException(sprintf('MemcachedAdapter: "prefix_key" option must be empty when using proxified connections, "%s" given.', $prefix)); + } + + return $this->client = $this->lazyClient; + } + + private static function encodeKey(string $key): string + { + return strtr($key, self::$RESERVED_MEMCACHED, self::$RESERVED_PSR6); + } + + private static function decodeKey(string $key): string + { + return strtr($key, self::$RESERVED_PSR6, self::$RESERVED_MEMCACHED); + } +} diff --git a/src/Symfony/Component/Config/Definition/ArrayNode.php b/src/Symfony/Component/Config/Definition/ArrayNode.php index ddb104fd2f08..2a828caf7853 100644 --- a/src/Symfony/Component/Config/Definition/ArrayNode.php +++ b/src/Symfony/Component/Config/Definition/ArrayNode.php @@ -298,7 +298,7 @@ protected function normalizeValue($value) $guesses = []; foreach (array_keys($value) as $subject) { - $minScore = INF; + $minScore = \INF; foreach ($proposals as $proposal) { $distance = levenshtein($subject, $proposal); if ($distance <= $minScore && $distance < 3) { diff --git a/src/Symfony/Component/Config/Definition/Dumper/XmlReferenceDumper.php b/src/Symfony/Component/Config/Definition/Dumper/XmlReferenceDumper.php index b86f7e77b57d..f686c53b5718 100644 --- a/src/Symfony/Component/Config/Definition/Dumper/XmlReferenceDumper.php +++ b/src/Symfony/Component/Config/Definition/Dumper/XmlReferenceDumper.php @@ -189,7 +189,7 @@ private function writeNode(NodeInterface $node, int $depth = 0, bool $root = fal $commentDepth = $depth + 4 + \strlen($attrName) + 2; $commentLines = explode("\n", $comment); $multiline = (\count($commentLines) > 1); - $comment = implode(PHP_EOL.str_repeat(' ', $commentDepth), $commentLines); + $comment = implode(\PHP_EOL.str_repeat(' ', $commentDepth), $commentLines); if ($multiline) { $this->writeLine(' diff --git a/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php index 693b1a2272b5..84df7d851680 100644 --- a/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php @@ -57,7 +57,7 @@ public function testSetDeprecated() $deprecationTriggered = 0; $deprecationHandler = function ($level, $message, $file, $line) use (&$prevErrorHandler, &$deprecationTriggered) { - if (E_USER_DEPRECATED === $level) { + if (\E_USER_DEPRECATED === $level) { return ++$deprecationTriggered; } diff --git a/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php b/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php index e1660da6e38d..d075764af2e4 100644 --- a/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php +++ b/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php @@ -107,7 +107,7 @@ public function load($resource, string $type = null) public function supports($resource, string $type = null): bool { - return \is_string($resource) && 'foo' === pathinfo($resource, PATHINFO_EXTENSION); + return \is_string($resource) && 'foo' === pathinfo($resource, \PATHINFO_EXTENSION); } public function getType() diff --git a/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php b/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php index a82e939d91cd..f0b77ae6f6f1 100644 --- a/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php +++ b/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php @@ -199,7 +199,7 @@ public function testLoadEmptyXmlFile() // test for issue https://github.com/symfony/symfony/issues/9731 public function testLoadWrongEmptyXMLWithErrorHandler() { - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { $originalDisableEntities = libxml_disable_entity_loader(false); } $errorReporting = error_reporting(-1); @@ -221,7 +221,7 @@ public function testLoadWrongEmptyXMLWithErrorHandler() error_reporting($errorReporting); } - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { $disableEntities = libxml_disable_entity_loader(true); libxml_disable_entity_loader($disableEntities); diff --git a/src/Symfony/Component/Config/Util/XmlUtils.php b/src/Symfony/Component/Config/Util/XmlUtils.php index a31347272278..196d44f07edc 100644 --- a/src/Symfony/Component/Config/Util/XmlUtils.php +++ b/src/Symfony/Component/Config/Util/XmlUtils.php @@ -51,15 +51,15 @@ public static function parse(string $content, $schemaOrCallable = null) } $internalErrors = libxml_use_internal_errors(true); - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { $disableEntities = libxml_disable_entity_loader(true); } libxml_clear_errors(); $dom = new \DOMDocument(); $dom->validateOnParse = true; - if (!$dom->loadXML($content, LIBXML_NONET | (\defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0))) { - if (LIBXML_VERSION < 20900) { + if (!$dom->loadXML($content, \LIBXML_NONET | (\defined('LIBXML_COMPACT') ? \LIBXML_COMPACT : 0))) { + if (\LIBXML_VERSION < 20900) { libxml_disable_entity_loader($disableEntities); } @@ -69,12 +69,12 @@ public static function parse(string $content, $schemaOrCallable = null) $dom->normalizeDocument(); libxml_use_internal_errors($internalErrors); - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { libxml_disable_entity_loader($disableEntities); } foreach ($dom->childNodes as $child) { - if (XML_DOCUMENT_TYPE_NODE === $child->nodeType) { + if (\XML_DOCUMENT_TYPE_NODE === $child->nodeType) { throw new XmlParsingException('Document types are not allowed.'); } } @@ -267,7 +267,7 @@ protected static function getXmlErrors(bool $internalErrors) $errors = []; foreach (libxml_get_errors() as $error) { $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)', - LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR', + \LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR', $error->code, trim($error->message), $error->file ?: 'n/a', diff --git a/src/Symfony/Component/Console/Application.php b/src/Symfony/Component/Console/Application.php index 80bbf876b553..784af89b3189 100644 --- a/src/Symfony/Component/Console/Application.php +++ b/src/Symfony/Component/Console/Application.php @@ -107,8 +107,10 @@ public function setCommandLoader(CommandLoaderInterface $commandLoader) */ public function run(InputInterface $input = null, OutputInterface $output = null) { - putenv('LINES='.$this->terminal->getHeight()); - putenv('COLUMNS='.$this->terminal->getWidth()); + if (\function_exists('putenv')) { + @putenv('LINES='.$this->terminal->getHeight()); + @putenv('COLUMNS='.$this->terminal->getWidth()); + } if (null === $input) { $input = new ArgvInput(); @@ -792,7 +794,7 @@ protected function doRenderThrowable(\Throwable $e, OutputInterface $output): vo }, $message); } - $width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : PHP_INT_MAX; + $width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : \PHP_INT_MAX; $lines = []; foreach ('' !== $message ? preg_split('/\r?\n/', $message) : [] as $line) { foreach ($this->splitStringByWidth($line, $width - 4) as $line) { @@ -891,7 +893,9 @@ protected function configureIO(InputInterface $input, OutputInterface $output) $input->setInteractive(false); } - putenv('SHELL_VERBOSITY='.$shellVerbosity); + if (\function_exists('putenv')) { + @putenv('SHELL_VERBOSITY='.$shellVerbosity); + } $_ENV['SHELL_VERBOSITY'] = $shellVerbosity; $_SERVER['SHELL_VERBOSITY'] = $shellVerbosity; } @@ -1075,7 +1079,7 @@ private function findAlternatives(string $name, iterable $collection): array } $alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; }); - ksort($alternatives, SORT_NATURAL | SORT_FLAG_CASE); + ksort($alternatives, \SORT_NATURAL | \SORT_FLAG_CASE); return array_keys($alternatives); } diff --git a/src/Symfony/Component/Console/Command/Command.php b/src/Symfony/Component/Console/Command/Command.php index 6c557a777ea7..bcb86cdfbebb 100644 --- a/src/Symfony/Component/Console/Command/Command.php +++ b/src/Symfony/Component/Console/Command/Command.php @@ -226,7 +226,7 @@ public function run(InputInterface $input, OutputInterface $output) if (null !== $this->processTitle) { if (\function_exists('cli_set_process_title')) { if (!@cli_set_process_title($this->processTitle)) { - if ('Darwin' === PHP_OS) { + if ('Darwin' === \PHP_OS) { $output->writeln('Running "cli_set_process_title" as an unprivileged user is not supported on MacOS.', OutputInterface::VERBOSITY_VERY_VERBOSE); } else { cli_set_process_title($this->processTitle); diff --git a/src/Symfony/Component/Console/Cursor.php b/src/Symfony/Component/Console/Cursor.php index 2da899b5564a..dcb5b5ad3985 100644 --- a/src/Symfony/Component/Console/Cursor.php +++ b/src/Symfony/Component/Console/Cursor.php @@ -24,7 +24,7 @@ final class Cursor public function __construct(OutputInterface $output, $input = null) { $this->output = $output; - $this->input = $input ?? (\defined('STDIN') ? STDIN : fopen('php://input', 'r+')); + $this->input = $input ?? (\defined('STDIN') ? \STDIN : fopen('php://input', 'r+')); } public function moveUp(int $lines = 1): self diff --git a/src/Symfony/Component/Console/Descriptor/JsonDescriptor.php b/src/Symfony/Component/Console/Descriptor/JsonDescriptor.php index 131fef1f1c3b..5ba588ee98a3 100644 --- a/src/Symfony/Component/Console/Descriptor/JsonDescriptor.php +++ b/src/Symfony/Component/Console/Descriptor/JsonDescriptor.php @@ -107,7 +107,7 @@ private function getInputArgumentData(InputArgument $argument): array 'is_required' => $argument->isRequired(), 'is_array' => $argument->isArray(), 'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $argument->getDescription()), - 'default' => INF === $argument->getDefault() ? 'INF' : $argument->getDefault(), + 'default' => \INF === $argument->getDefault() ? 'INF' : $argument->getDefault(), ]; } @@ -120,7 +120,7 @@ private function getInputOptionData(InputOption $option): array 'is_value_required' => $option->isValueRequired(), 'is_multiple' => $option->isArray(), 'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $option->getDescription()), - 'default' => INF === $option->getDefault() ? 'INF' : $option->getDefault(), + 'default' => \INF === $option->getDefault() ? 'INF' : $option->getDefault(), ]; } diff --git a/src/Symfony/Component/Console/Descriptor/TextDescriptor.php b/src/Symfony/Component/Console/Descriptor/TextDescriptor.php index bde620bfa7f8..05a32443d935 100644 --- a/src/Symfony/Component/Console/Descriptor/TextDescriptor.php +++ b/src/Symfony/Component/Console/Descriptor/TextDescriptor.php @@ -280,7 +280,7 @@ private function getCommandAliasesText(Command $command): string */ private function formatDefaultValue($default): string { - if (INF === $default) { + if (\INF === $default) { return 'INF'; } @@ -294,7 +294,7 @@ private function formatDefaultValue($default): string } } - return str_replace('\\\\', '\\', json_encode($default, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); + return str_replace('\\\\', '\\', json_encode($default, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE)); } /** diff --git a/src/Symfony/Component/Console/Formatter/OutputFormatter.php b/src/Symfony/Component/Console/Formatter/OutputFormatter.php index 8fc9f286ec67..edc6a1d71d6f 100644 --- a/src/Symfony/Component/Console/Formatter/OutputFormatter.php +++ b/src/Symfony/Component/Console/Formatter/OutputFormatter.php @@ -136,7 +136,7 @@ public function formatAndWrap(?string $message, int $width) $output = ''; $tagRegex = '[a-z][^<>]*+'; $currentLineLength = 0; - preg_match_all("#<(($tagRegex) | /($tagRegex)?)>#ix", $message, $matches, PREG_OFFSET_CAPTURE); + preg_match_all("#<(($tagRegex) | /($tagRegex)?)>#ix", $message, $matches, \PREG_OFFSET_CAPTURE); foreach ($matches[0] as $i => $match) { $pos = $match[1]; $text = $match[0]; @@ -194,7 +194,7 @@ private function createStyleFromString(string $string): ?OutputFormatterStyleInt return $this->styles[$string]; } - if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', $string, $matches, PREG_SET_ORDER)) { + if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', $string, $matches, \PREG_SET_ORDER)) { return null; } diff --git a/src/Symfony/Component/Console/Helper/ProgressBar.php b/src/Symfony/Component/Console/Helper/ProgressBar.php index 715bfef211b2..3fce6886e58b 100644 --- a/src/Symfony/Component/Console/Helper/ProgressBar.php +++ b/src/Symfony/Component/Console/Helper/ProgressBar.php @@ -474,7 +474,7 @@ private function overwrite(string $message): void } } } elseif ($this->step > 0) { - $message = PHP_EOL.$message; + $message = \PHP_EOL.$message; } $this->previousMessage = $originalMessage; @@ -533,7 +533,7 @@ private static function initPlaceholderFormatters(): array return Helper::formatMemory(memory_get_usage(true)); }, 'current' => function (self $bar) { - return str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', STR_PAD_LEFT); + return str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', \STR_PAD_LEFT); }, 'max' => function (self $bar) { return $bar->getMaxSteps(); diff --git a/src/Symfony/Component/Console/Helper/QuestionHelper.php b/src/Symfony/Component/Console/Helper/QuestionHelper.php index 18d148d77870..1d3483a3f1fe 100644 --- a/src/Symfony/Component/Console/Helper/QuestionHelper.php +++ b/src/Symfony/Component/Console/Helper/QuestionHelper.php @@ -107,12 +107,12 @@ private function doAsk(OutputInterface $output, Question $question) { $this->writePrompt($output, $question); - $inputStream = $this->inputStream ?: STDIN; + $inputStream = $this->inputStream ?: \STDIN; $autocomplete = $question->getAutocompleterCallback(); if (\function_exists('sapi_windows_cp_set')) { // Codepage used by cmd.exe on Windows to allow special characters (éàüñ). - sapi_windows_cp_set(1252); + @sapi_windows_cp_set(1252); } if (null === $autocomplete || !self::$stty || !Terminal::hasSttyAvailable()) { diff --git a/src/Symfony/Component/Console/Helper/TableStyle.php b/src/Symfony/Component/Console/Helper/TableStyle.php index 28c950cf673e..07265b467ae5 100644 --- a/src/Symfony/Component/Console/Helper/TableStyle.php +++ b/src/Symfony/Component/Console/Helper/TableStyle.php @@ -46,7 +46,7 @@ class TableStyle private $cellRowFormat = '%s'; private $cellRowContentFormat = ' %s '; private $borderFormat = '%s'; - private $padType = STR_PAD_RIGHT; + private $padType = \STR_PAD_RIGHT; /** * Sets padding character, used for cell padding. @@ -319,7 +319,7 @@ public function getBorderFormat() */ public function setPadType(int $padType) { - if (!\in_array($padType, [STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH], true)) { + if (!\in_array($padType, [\STR_PAD_LEFT, \STR_PAD_RIGHT, \STR_PAD_BOTH], true)) { throw new InvalidArgumentException('Invalid padding type. Expected one of (STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH).'); } diff --git a/src/Symfony/Component/Console/Input/ArgvInput.php b/src/Symfony/Component/Console/Input/ArgvInput.php index cbd9f41f2f86..c93bda5a9bf0 100644 --- a/src/Symfony/Component/Console/Input/ArgvInput.php +++ b/src/Symfony/Component/Console/Input/ArgvInput.php @@ -45,9 +45,7 @@ class ArgvInput extends Input public function __construct(array $argv = null, InputDefinition $definition = null) { - if (null === $argv) { - $argv = $_SERVER['argv']; - } + $argv = $argv ?? $_SERVER['argv'] ?? []; // strip the application name array_shift($argv); diff --git a/src/Symfony/Component/Console/Input/InputDefinition.php b/src/Symfony/Component/Console/Input/InputDefinition.php index 4e95e9b331b3..a32e913b7d5f 100644 --- a/src/Symfony/Component/Console/Input/InputDefinition.php +++ b/src/Symfony/Component/Console/Input/InputDefinition.php @@ -171,7 +171,7 @@ public function getArguments() */ public function getArgumentCount() { - return $this->hasAnArrayArgument ? PHP_INT_MAX : \count($this->arguments); + return $this->hasAnArrayArgument ? \PHP_INT_MAX : \count($this->arguments); } /** diff --git a/src/Symfony/Component/Console/Output/BufferedOutput.php b/src/Symfony/Component/Console/Output/BufferedOutput.php index a5ad7ada5000..d37c6e323805 100644 --- a/src/Symfony/Component/Console/Output/BufferedOutput.php +++ b/src/Symfony/Component/Console/Output/BufferedOutput.php @@ -39,7 +39,7 @@ protected function doWrite(string $message, bool $newline) $this->buffer .= $message; if ($newline) { - $this->buffer .= PHP_EOL; + $this->buffer .= \PHP_EOL; } } } diff --git a/src/Symfony/Component/Console/Output/ConsoleOutput.php b/src/Symfony/Component/Console/Output/ConsoleOutput.php index 8356d4d55417..96664f1508ab 100644 --- a/src/Symfony/Component/Console/Output/ConsoleOutput.php +++ b/src/Symfony/Component/Console/Output/ConsoleOutput.php @@ -131,7 +131,7 @@ private function isRunningOS400(): bool $checks = [ \function_exists('php_uname') ? php_uname('s') : '', getenv('OSTYPE'), - PHP_OS, + \PHP_OS, ]; return false !== stripos(implode(';', $checks), 'OS400'); diff --git a/src/Symfony/Component/Console/Output/ConsoleSectionOutput.php b/src/Symfony/Component/Console/Output/ConsoleSectionOutput.php index 024d99d96643..c19edbf95e9d 100644 --- a/src/Symfony/Component/Console/Output/ConsoleSectionOutput.php +++ b/src/Symfony/Component/Console/Output/ConsoleSectionOutput.php @@ -82,10 +82,10 @@ public function getContent(): string */ public function addContent(string $input) { - foreach (explode(PHP_EOL, $input) as $lineContent) { + foreach (explode(\PHP_EOL, $input) as $lineContent) { $this->lines += ceil($this->getDisplayLength($lineContent) / $this->terminal->getWidth()) ?: 1; $this->content[] = $lineContent; - $this->content[] = PHP_EOL; + $this->content[] = \PHP_EOL; } } diff --git a/src/Symfony/Component/Console/Output/StreamOutput.php b/src/Symfony/Component/Console/Output/StreamOutput.php index 9b78f432a035..ea434527b905 100644 --- a/src/Symfony/Component/Console/Output/StreamOutput.php +++ b/src/Symfony/Component/Console/Output/StreamOutput.php @@ -70,7 +70,7 @@ public function getStream() protected function doWrite(string $message, bool $newline) { if ($newline) { - $message .= PHP_EOL; + $message .= \PHP_EOL; } @fwrite($this->stream, $message); diff --git a/src/Symfony/Component/Console/Question/Question.php b/src/Symfony/Component/Console/Question/Question.php index 8b0e4d989a90..17d890d76347 100644 --- a/src/Symfony/Component/Console/Question/Question.php +++ b/src/Symfony/Component/Console/Question/Question.php @@ -213,8 +213,11 @@ public function getValidator() */ public function setMaxAttempts(?int $attempts) { - if (null !== $attempts && $attempts < 1) { - throw new InvalidArgumentException('Maximum number of attempts must be a positive value.'); + if (null !== $attempts) { + $attempts = (int) $attempts; + if ($attempts < 1) { + throw new InvalidArgumentException('Maximum number of attempts must be a positive value.'); + } } $this->attempts = $attempts; diff --git a/src/Symfony/Component/Console/Style/OutputStyle.php b/src/Symfony/Component/Console/Style/OutputStyle.php index d46947f053c4..67a98ff073fe 100644 --- a/src/Symfony/Component/Console/Style/OutputStyle.php +++ b/src/Symfony/Component/Console/Style/OutputStyle.php @@ -35,7 +35,7 @@ public function __construct(OutputInterface $output) */ public function newLine(int $count = 1) { - $this->output->write(str_repeat(PHP_EOL, $count)); + $this->output->write(str_repeat(\PHP_EOL, $count)); } /** diff --git a/src/Symfony/Component/Console/Style/SymfonyStyle.php b/src/Symfony/Component/Console/Style/SymfonyStyle.php index 271752f1444e..fa4dfa018bd1 100644 --- a/src/Symfony/Component/Console/Style/SymfonyStyle.php +++ b/src/Symfony/Component/Console/Style/SymfonyStyle.php @@ -422,7 +422,7 @@ private function getProgressBar(): ProgressBar private function autoPrependBlock(): void { - $chars = substr(str_replace(PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2); + $chars = substr(str_replace(\PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2); if (!isset($chars[0])) { $this->newLine(); //empty history, so we should start with a new line. @@ -467,7 +467,7 @@ private function createBlock(iterable $messages, string $type = null, string $st $message = OutputFormatter::escape($message); } - $lines = array_merge($lines, explode(PHP_EOL, wordwrap($message, $this->lineLength - $prefixLength - $indentLength, PHP_EOL, true))); + $lines = array_merge($lines, explode(\PHP_EOL, wordwrap($message, $this->lineLength - $prefixLength - $indentLength, \PHP_EOL, true))); if (\count($messages) > 1 && $key < \count($messages) - 1) { $lines[] = ''; diff --git a/src/Symfony/Component/Console/Tester/TesterTrait.php b/src/Symfony/Component/Console/Tester/TesterTrait.php index 73ee0103f917..4a344ca2e91b 100644 --- a/src/Symfony/Component/Console/Tester/TesterTrait.php +++ b/src/Symfony/Component/Console/Tester/TesterTrait.php @@ -42,7 +42,7 @@ public function getDisplay(bool $normalize = false) $display = stream_get_contents($this->output->getStream()); if ($normalize) { - $display = str_replace(PHP_EOL, "\n", $display); + $display = str_replace(\PHP_EOL, "\n", $display); } return $display; @@ -66,7 +66,7 @@ public function getErrorOutput(bool $normalize = false) $display = stream_get_contents($this->output->getErrorOutput()->getStream()); if ($normalize) { - $display = str_replace(PHP_EOL, "\n", $display); + $display = str_replace(\PHP_EOL, "\n", $display); } return $display; @@ -168,7 +168,7 @@ private static function createStream(array $inputs) $stream = fopen('php://memory', 'r+', false); foreach ($inputs as $input) { - fwrite($stream, $input.PHP_EOL); + fwrite($stream, $input.\PHP_EOL); } rewind($stream); diff --git a/src/Symfony/Component/Console/Tests/ApplicationTest.php b/src/Symfony/Component/Console/Tests/ApplicationTest.php index 8d25a88f33fc..f275ccac1ab0 100644 --- a/src/Symfony/Component/Console/Tests/ApplicationTest.php +++ b/src/Symfony/Component/Console/Tests/ApplicationTest.php @@ -81,7 +81,7 @@ public static function setUpBeforeClass(): void protected function normalizeLineBreaks($text) { - return str_replace(PHP_EOL, "\n", $text); + return str_replace(\PHP_EOL, "\n", $text); } /** @@ -1012,10 +1012,10 @@ public function testRun() $tester = new ApplicationTester($application); $tester->run(['command' => 'foo:bar', '--no-interaction' => true], ['decorated' => false]); - $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if --no-interaction is passed'); + $this->assertSame('called'.\PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if --no-interaction is passed'); $tester->run(['command' => 'foo:bar', '-n' => true], ['decorated' => false]); - $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if -n is passed'); + $this->assertSame('called'.\PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if -n is passed'); } public function testRunWithGlobalOptionAndNoCommand() @@ -1312,7 +1312,7 @@ public function testRunWithDispatcher() $tester = new ApplicationTester($application); $tester->run(['command' => 'foo']); - $this->assertEquals('before.foo.after.'.PHP_EOL, $tester->getDisplay()); + $this->assertEquals('before.foo.after.'.\PHP_EOL, $tester->getDisplay()); } public function testRunWithExceptionAndDispatcher() @@ -1596,7 +1596,7 @@ public function testSetRunCustomDefaultCommand() $tester = new ApplicationTester($application); $tester->run([], ['interactive' => false]); - $this->assertEquals('called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command'); + $this->assertEquals('called'.\PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command'); $application = new CustomDefaultCommandApplication(); $application->setAutoExit(false); @@ -1604,7 +1604,7 @@ public function testSetRunCustomDefaultCommand() $tester = new ApplicationTester($application); $tester->run([], ['interactive' => false]); - $this->assertEquals('called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command'); + $this->assertEquals('called'.\PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command'); } public function testSetRunCustomDefaultCommandWithOption() @@ -1619,7 +1619,7 @@ public function testSetRunCustomDefaultCommandWithOption() $tester = new ApplicationTester($application); $tester->run(['--fooopt' => 'opt'], ['interactive' => false]); - $this->assertEquals('called'.PHP_EOL.'opt'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command'); + $this->assertEquals('called'.\PHP_EOL.'opt'.\PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command'); } public function testSetRunCustomSingleCommand() diff --git a/src/Symfony/Component/Console/Tests/Command/CommandTest.php b/src/Symfony/Component/Console/Tests/Command/CommandTest.php index bbfd228ac751..c15555897be4 100644 --- a/src/Symfony/Component/Console/Tests/Command/CommandTest.php +++ b/src/Symfony/Component/Console/Tests/Command/CommandTest.php @@ -264,7 +264,7 @@ public function testRunInteractive() $tester->execute([], ['interactive' => true]); - $this->assertEquals('interact called'.PHP_EOL.'execute called'.PHP_EOL, $tester->getDisplay(), '->run() calls the interact() method if the input is interactive'); + $this->assertEquals('interact called'.\PHP_EOL.'execute called'.\PHP_EOL, $tester->getDisplay(), '->run() calls the interact() method if the input is interactive'); } public function testRunNonInteractive() @@ -273,7 +273,7 @@ public function testRunNonInteractive() $tester->execute([], ['interactive' => false]); - $this->assertEquals('execute called'.PHP_EOL, $tester->getDisplay(), '->run() does not call the interact() method if the input is not interactive'); + $this->assertEquals('execute called'.\PHP_EOL, $tester->getDisplay(), '->run() does not call the interact() method if the input is not interactive'); } public function testExecuteMethodNeedsToBeOverridden() @@ -316,7 +316,7 @@ public function testRunWithProcessTitle() $command->setProcessTitle('foo'); $this->assertSame(0, $command->run(new StringInput(''), new NullOutput())); if (\function_exists('cli_set_process_title')) { - if (null === @cli_get_process_title() && 'Darwin' === PHP_OS) { + if (null === @cli_get_process_title() && 'Darwin' === \PHP_OS) { $this->markTestSkipped('Running "cli_get_process_title" as an unprivileged user is not supported on MacOS.'); } $this->assertEquals('foo', cli_get_process_title()); @@ -332,7 +332,7 @@ public function testSetCode() $this->assertEquals($command, $ret, '->setCode() implements a fluent interface'); $tester = new CommandTester($command); $tester->execute([]); - $this->assertEquals('interact called'.PHP_EOL.'from the code...'.PHP_EOL, $tester->getDisplay()); + $this->assertEquals('interact called'.\PHP_EOL.'from the code...'.\PHP_EOL, $tester->getDisplay()); } public function getSetCodeBindToClosureTests() @@ -357,7 +357,7 @@ public function testSetCodeBindToClosure($previouslyBound, $expected) $command->setCode($code); $tester = new CommandTester($command); $tester->execute([]); - $this->assertEquals('interact called'.PHP_EOL.$expected.PHP_EOL, $tester->getDisplay()); + $this->assertEquals('interact called'.\PHP_EOL.$expected.\PHP_EOL, $tester->getDisplay()); } public function testSetCodeWithStaticClosure() @@ -367,7 +367,7 @@ public function testSetCodeWithStaticClosure() $tester = new CommandTester($command); $tester->execute([]); - $this->assertEquals('interact called'.PHP_EOL.'bound'.PHP_EOL, $tester->getDisplay()); + $this->assertEquals('interact called'.\PHP_EOL.'bound'.\PHP_EOL, $tester->getDisplay()); } private static function createClosure() @@ -384,7 +384,7 @@ public function testSetCodeWithNonClosureCallable() $this->assertEquals($command, $ret, '->setCode() implements a fluent interface'); $tester = new CommandTester($command); $tester->execute([]); - $this->assertEquals('interact called'.PHP_EOL.'from the code...'.PHP_EOL, $tester->getDisplay()); + $this->assertEquals('interact called'.\PHP_EOL.'from the code...'.\PHP_EOL, $tester->getDisplay()); } public function callableMethodCommand(InputInterface $input, OutputInterface $output) diff --git a/src/Symfony/Component/Console/Tests/CursorTest.php b/src/Symfony/Component/Console/Tests/CursorTest.php index 08e84fa2cdd5..3c22f252d6b0 100644 --- a/src/Symfony/Component/Console/Tests/CursorTest.php +++ b/src/Symfony/Component/Console/Tests/CursorTest.php @@ -198,7 +198,7 @@ protected function getOutputContent(StreamOutput $output) { rewind($output->getStream()); - return str_replace(PHP_EOL, "\n", stream_get_contents($output->getStream())); + return str_replace(\PHP_EOL, "\n", stream_get_contents($output->getStream())); } protected function getOutputStream(): StreamOutput diff --git a/src/Symfony/Component/Console/Tests/Descriptor/AbstractDescriptorTest.php b/src/Symfony/Component/Console/Tests/Descriptor/AbstractDescriptorTest.php index 320a4fb9f46b..5d9257fbedfc 100644 --- a/src/Symfony/Component/Console/Tests/Descriptor/AbstractDescriptorTest.php +++ b/src/Symfony/Component/Console/Tests/Descriptor/AbstractDescriptorTest.php @@ -102,6 +102,6 @@ protected function assertDescription($expectedDescription, $describedObject, arr { $output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, true); $this->getDescriptor()->describe($output, $describedObject, $options + ['raw_output' => true]); - $this->assertEquals(trim($expectedDescription), trim(str_replace(PHP_EOL, "\n", $output->fetch()))); + $this->assertEquals(trim($expectedDescription), trim(str_replace(\PHP_EOL, "\n", $output->fetch()))); } } diff --git a/src/Symfony/Component/Console/Tests/Descriptor/JsonDescriptorTest.php b/src/Symfony/Component/Console/Tests/Descriptor/JsonDescriptorTest.php index fb596b8d7ada..d3f962fea0f0 100644 --- a/src/Symfony/Component/Console/Tests/Descriptor/JsonDescriptorTest.php +++ b/src/Symfony/Component/Console/Tests/Descriptor/JsonDescriptorTest.php @@ -30,6 +30,6 @@ protected function assertDescription($expectedDescription, $describedObject, arr { $output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, true); $this->getDescriptor()->describe($output, $describedObject, $options + ['raw_output' => true]); - $this->assertEquals(json_decode(trim($expectedDescription), true), json_decode(trim(str_replace(PHP_EOL, "\n", $output->fetch())), true)); + $this->assertEquals(json_decode(trim($expectedDescription), true), json_decode(trim(str_replace(\PHP_EOL, "\n", $output->fetch())), true)); } } diff --git a/src/Symfony/Component/Console/Tests/Descriptor/ObjectsProvider.php b/src/Symfony/Component/Console/Tests/Descriptor/ObjectsProvider.php index d46d6f18baad..ccd4c3b07131 100644 --- a/src/Symfony/Component/Console/Tests/Descriptor/ObjectsProvider.php +++ b/src/Symfony/Component/Console/Tests/Descriptor/ObjectsProvider.php @@ -32,7 +32,7 @@ public static function getInputArguments() 'input_argument_3' => new InputArgument('argument_name', InputArgument::OPTIONAL, 'argument description', 'default_value'), 'input_argument_4' => new InputArgument('argument_name', InputArgument::REQUIRED, "multiline\nargument description"), 'input_argument_with_style' => new InputArgument('argument_name', InputArgument::OPTIONAL, 'argument description', 'style'), - 'input_argument_with_default_inf_value' => new InputArgument('argument_name', InputArgument::OPTIONAL, 'argument description', INF), + 'input_argument_with_default_inf_value' => new InputArgument('argument_name', InputArgument::OPTIONAL, 'argument description', \INF), ]; } @@ -47,7 +47,7 @@ public static function getInputOptions() 'input_option_6' => new InputOption('option_name', ['o', 'O'], InputOption::VALUE_REQUIRED, 'option with multiple shortcuts'), 'input_option_with_style' => new InputOption('option_name', 'o', InputOption::VALUE_REQUIRED, 'option description', 'style'), 'input_option_with_style_array' => new InputOption('option_name', 'o', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'option description', ['Hello', 'world']), - 'input_option_with_default_inf_value' => new InputOption('option_name', 'o', InputOption::VALUE_OPTIONAL, 'option description', INF), + 'input_option_with_default_inf_value' => new InputOption('option_name', 'o', InputOption::VALUE_OPTIONAL, 'option description', \INF), ]; } diff --git a/src/Symfony/Component/Console/Tests/Helper/ProcessHelperTest.php b/src/Symfony/Component/Console/Tests/Helper/ProcessHelperTest.php index 82c6b445175d..e2880f22f431 100644 --- a/src/Symfony/Component/Console/Tests/Helper/ProcessHelperTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/ProcessHelperTest.php @@ -109,9 +109,9 @@ public function provideCommandsAndOutput() ['', 'php -r "syntax error"', StreamOutput::VERBOSITY_VERBOSE, null], [$syntaxErrorOutputVerbose, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERY_VERBOSE, null], [$syntaxErrorOutputDebug, 'php -r "fwrite(STDERR, \'error message\');usleep(500000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_DEBUG, null], - [$errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERBOSE, $errorMessage], - [$syntaxErrorOutputVerbose.$errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERY_VERBOSE, $errorMessage], - [$syntaxErrorOutputDebug.$errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(500000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_DEBUG, $errorMessage], + [$errorMessage.\PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERBOSE, $errorMessage], + [$syntaxErrorOutputVerbose.$errorMessage.\PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERY_VERBOSE, $errorMessage], + [$syntaxErrorOutputDebug.$errorMessage.\PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(500000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_DEBUG, $errorMessage], [$successOutputProcessDebug, ['php', '-r', 'echo 42;'], StreamOutput::VERBOSITY_DEBUG, null], [$successOutputDebug, $fromShellCommandline('php -r "echo 42;"'), StreamOutput::VERBOSITY_DEBUG, null], [$successOutputProcessDebug, [new Process(['php', '-r', 'echo 42;'])], StreamOutput::VERBOSITY_DEBUG, null], diff --git a/src/Symfony/Component/Console/Tests/Helper/ProgressBarTest.php b/src/Symfony/Component/Console/Tests/Helper/ProgressBarTest.php index 099f6aedf700..b5d2b5f6e264 100644 --- a/src/Symfony/Component/Console/Tests/Helper/ProgressBarTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/ProgressBarTest.php @@ -336,9 +336,9 @@ public function testOverwriteWithSectionOutput() rewind($output->getStream()); $this->assertEquals( - ' 0/50 [>---------------------------] 0%'.PHP_EOL. - "\x1b[1A\x1b[0J".' 1/50 [>---------------------------] 2%'.PHP_EOL. - "\x1b[1A\x1b[0J".' 2/50 [=>--------------------------] 4%'.PHP_EOL, + ' 0/50 [>---------------------------] 0%'.\PHP_EOL. + "\x1b[1A\x1b[0J".' 1/50 [>---------------------------] 2%'.\PHP_EOL. + "\x1b[1A\x1b[0J".' 2/50 [=>--------------------------] 4%'.\PHP_EOL, stream_get_contents($output->getStream()) ); } @@ -362,12 +362,12 @@ public function testOverwriteMultipleProgressBarsWithSectionOutputs() rewind($stream->getStream()); $this->assertEquals( - ' 0/50 [>---------------------------] 0%'.PHP_EOL. - ' 0/50 [>---------------------------] 0%'.PHP_EOL. - "\x1b[1A\x1b[0J".' 1/50 [>---------------------------] 2%'.PHP_EOL. - "\x1b[2A\x1b[0J".' 1/50 [>---------------------------] 2%'.PHP_EOL. - "\x1b[1A\x1b[0J".' 1/50 [>---------------------------] 2%'.PHP_EOL. - ' 1/50 [>---------------------------] 2%'.PHP_EOL, + ' 0/50 [>---------------------------] 0%'.\PHP_EOL. + ' 0/50 [>---------------------------] 0%'.\PHP_EOL. + "\x1b[1A\x1b[0J".' 1/50 [>---------------------------] 2%'.\PHP_EOL. + "\x1b[2A\x1b[0J".' 1/50 [>---------------------------] 2%'.\PHP_EOL. + "\x1b[1A\x1b[0J".' 1/50 [>---------------------------] 2%'.\PHP_EOL. + ' 1/50 [>---------------------------] 2%'.\PHP_EOL, stream_get_contents($stream->getStream()) ); } @@ -393,12 +393,12 @@ public function testMultipleSectionsWithCustomFormat() rewind($stream->getStream()); - $this->assertEquals(' 0/50 [>---------------------------] 0%'.PHP_EOL. - ' 0/50 [>] 0% Fruitcake marzipan toffee. Cupcake gummi bears tart dessert ice cream chupa chups cupcake chocolate bar sesame snaps. Croissant halvah cookie jujubes powder macaroon. Fruitcake bear claw bonbon jelly beans oat cake pie muffin Fruitcake marzipan toffee.'.PHP_EOL. - "\x1b[4A\x1b[0J".' 0/50 [>] 0% Fruitcake marzipan toffee. Cupcake gummi bears tart dessert ice cream chupa chups cupcake chocolate bar sesame snaps. Croissant halvah cookie jujubes powder macaroon. Fruitcake bear claw bonbon jelly beans oat cake pie muffin Fruitcake marzipan toffee.'.PHP_EOL. - "\x1b[3A\x1b[0J".' 1/50 [>---------------------------] 2%'.PHP_EOL. - ' 0/50 [>] 0% Fruitcake marzipan toffee. Cupcake gummi bears tart dessert ice cream chupa chups cupcake chocolate bar sesame snaps. Croissant halvah cookie jujubes powder macaroon. Fruitcake bear claw bonbon jelly beans oat cake pie muffin Fruitcake marzipan toffee.'.PHP_EOL. - "\x1b[3A\x1b[0J".' 1/50 [>] 2% Fruitcake marzipan toffee. Cupcake gummi bears tart dessert ice cream chupa chups cupcake chocolate bar sesame snaps. Croissant halvah cookie jujubes powder macaroon. Fruitcake bear claw bonbon jelly beans oat cake pie muffin Fruitcake marzipan toffee.'.PHP_EOL, + $this->assertEquals(' 0/50 [>---------------------------] 0%'.\PHP_EOL. + ' 0/50 [>] 0% Fruitcake marzipan toffee. Cupcake gummi bears tart dessert ice cream chupa chups cupcake chocolate bar sesame snaps. Croissant halvah cookie jujubes powder macaroon. Fruitcake bear claw bonbon jelly beans oat cake pie muffin Fruitcake marzipan toffee.'.\PHP_EOL. + "\x1b[4A\x1b[0J".' 0/50 [>] 0% Fruitcake marzipan toffee. Cupcake gummi bears tart dessert ice cream chupa chups cupcake chocolate bar sesame snaps. Croissant halvah cookie jujubes powder macaroon. Fruitcake bear claw bonbon jelly beans oat cake pie muffin Fruitcake marzipan toffee.'.\PHP_EOL. + "\x1b[3A\x1b[0J".' 1/50 [>---------------------------] 2%'.\PHP_EOL. + ' 0/50 [>] 0% Fruitcake marzipan toffee. Cupcake gummi bears tart dessert ice cream chupa chups cupcake chocolate bar sesame snaps. Croissant halvah cookie jujubes powder macaroon. Fruitcake bear claw bonbon jelly beans oat cake pie muffin Fruitcake marzipan toffee.'.\PHP_EOL. + "\x1b[3A\x1b[0J".' 1/50 [>] 2% Fruitcake marzipan toffee. Cupcake gummi bears tart dessert ice cream chupa chups cupcake chocolate bar sesame snaps. Croissant halvah cookie jujubes powder macaroon. Fruitcake bear claw bonbon jelly beans oat cake pie muffin Fruitcake marzipan toffee.'.\PHP_EOL, stream_get_contents($stream->getStream()) ); } @@ -555,16 +555,16 @@ public function testNonDecoratedOutput() rewind($output->getStream()); $this->assertEquals( - ' 0/200 [>---------------------------] 0%'.PHP_EOL. - ' 20/200 [==>-------------------------] 10%'.PHP_EOL. - ' 40/200 [=====>----------------------] 20%'.PHP_EOL. - ' 60/200 [========>-------------------] 30%'.PHP_EOL. - ' 80/200 [===========>----------------] 40%'.PHP_EOL. - ' 100/200 [==============>-------------] 50%'.PHP_EOL. - ' 120/200 [================>-----------] 60%'.PHP_EOL. - ' 140/200 [===================>--------] 70%'.PHP_EOL. - ' 160/200 [======================>-----] 80%'.PHP_EOL. - ' 180/200 [=========================>--] 90%'.PHP_EOL. + ' 0/200 [>---------------------------] 0%'.\PHP_EOL. + ' 20/200 [==>-------------------------] 10%'.\PHP_EOL. + ' 40/200 [=====>----------------------] 20%'.\PHP_EOL. + ' 60/200 [========>-------------------] 30%'.\PHP_EOL. + ' 80/200 [===========>----------------] 40%'.\PHP_EOL. + ' 100/200 [==============>-------------] 50%'.\PHP_EOL. + ' 120/200 [================>-----------] 60%'.\PHP_EOL. + ' 140/200 [===================>--------] 70%'.\PHP_EOL. + ' 160/200 [======================>-----] 80%'.\PHP_EOL. + ' 180/200 [=========================>--] 90%'.\PHP_EOL. ' 200/200 [============================] 100%', stream_get_contents($output->getStream()) ); @@ -581,8 +581,8 @@ public function testNonDecoratedOutputWithClear() rewind($output->getStream()); $this->assertEquals( - ' 0/50 [>---------------------------] 0%'.PHP_EOL. - ' 25/50 [==============>-------------] 50%'.PHP_EOL. + ' 0/50 [>---------------------------] 0%'.\PHP_EOL. + ' 25/50 [==============>-------------] 50%'.\PHP_EOL. ' 50/50 [============================] 100%', stream_get_contents($output->getStream()) ); @@ -596,7 +596,7 @@ public function testNonDecoratedOutputWithoutMax() rewind($output->getStream()); $this->assertEquals( - ' 0 [>---------------------------]'.PHP_EOL. + ' 0 [>---------------------------]'.\PHP_EOL. ' 1 [->--------------------------]', stream_get_contents($output->getStream()) ); diff --git a/src/Symfony/Component/Console/Tests/Helper/ProgressIndicatorTest.php b/src/Symfony/Component/Console/Tests/Helper/ProgressIndicatorTest.php index 4abb9706aa5d..986646794b01 100644 --- a/src/Symfony/Component/Console/Tests/Helper/ProgressIndicatorTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/ProgressIndicatorTest.php @@ -46,11 +46,11 @@ public function testDefaultIndicator() $this->generateOutput(' \\ Advancing...'). $this->generateOutput(' | Advancing...'). $this->generateOutput(' | Done...'). - PHP_EOL. + \PHP_EOL. $this->generateOutput(' - Starting Again...'). $this->generateOutput(' \\ Starting Again...'). $this->generateOutput(' \\ Done Again...'). - PHP_EOL, + \PHP_EOL, stream_get_contents($output->getStream()) ); } @@ -70,9 +70,9 @@ public function testNonDecoratedOutput() rewind($output->getStream()); $this->assertEquals( - ' Starting...'.PHP_EOL. - ' Midway...'.PHP_EOL. - ' Done...'.PHP_EOL.PHP_EOL, + ' Starting...'.\PHP_EOL. + ' Midway...'.\PHP_EOL. + ' Done...'.\PHP_EOL.\PHP_EOL, stream_get_contents($output->getStream()) ); } diff --git a/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php b/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php index 467f38b6d45c..06f20e2b1b10 100644 --- a/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php @@ -206,7 +206,7 @@ private function assertOutputContains($expected, StreamOutput $output, $normaliz $stream = stream_get_contents($output->getStream()); if ($normalize) { - $stream = str_replace(PHP_EOL, "\n", $stream); + $stream = str_replace(\PHP_EOL, "\n", $stream); } $this->assertStringContainsString($expected, $stream); diff --git a/src/Symfony/Component/Console/Tests/Helper/TableTest.php b/src/Symfony/Component/Console/Tests/Helper/TableTest.php index 070b87b03531..3616333ecaa0 100644 --- a/src/Symfony/Component/Console/Tests/Helper/TableTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/TableTest.php @@ -787,7 +787,7 @@ public function testColumnStyle() ]); $style = new TableStyle(); - $style->setPadType(STR_PAD_LEFT); + $style->setPadType(\STR_PAD_LEFT); $table->setColumnStyle(3, $style); $table->render(); @@ -833,7 +833,7 @@ public function testColumnWidth() ->setColumnWidth(3, 10); $style = new TableStyle(); - $style->setPadType(STR_PAD_LEFT); + $style->setPadType(\STR_PAD_LEFT); $table->setColumnStyle(3, $style); $table->render(); @@ -864,7 +864,7 @@ public function testColumnWidths() ->setColumnWidths([15, 0, -1, 10]); $style = new TableStyle(); - $style->setPadType(STR_PAD_LEFT); + $style->setPadType(\STR_PAD_LEFT); $table->setColumnStyle(3, $style); $table->render(); @@ -1260,7 +1260,7 @@ protected function getOutputContent(StreamOutput $output) { rewind($output->getStream()); - return str_replace(PHP_EOL, "\n", stream_get_contents($output->getStream())); + return str_replace(\PHP_EOL, "\n", stream_get_contents($output->getStream())); } public function testWithColspanAndMaxWith(): void diff --git a/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php b/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php index 0f5884136b02..283eccaf2bf0 100644 --- a/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php +++ b/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php @@ -67,7 +67,7 @@ public function testOutputMapping($logLevel, $outputVerbosity, $isOutput, $addVe $logger = new ConsoleLogger($out, $addVerbosityLevelMap); $logger->log($logLevel, 'foo bar'); $logs = $out->fetch(); - $this->assertEquals($isOutput ? "[$logLevel] foo bar".PHP_EOL : '', $logs); + $this->assertEquals($isOutput ? "[$logLevel] foo bar".\PHP_EOL : '', $logs); } public function provideOutputMappingParams() diff --git a/src/Symfony/Component/Console/Tests/Output/ConsoleSectionOutputTest.php b/src/Symfony/Component/Console/Tests/Output/ConsoleSectionOutputTest.php index e8c65f9b2164..6abe040b4f2b 100644 --- a/src/Symfony/Component/Console/Tests/Output/ConsoleSectionOutputTest.php +++ b/src/Symfony/Component/Console/Tests/Output/ConsoleSectionOutputTest.php @@ -39,11 +39,11 @@ public function testClearAll() $sections = []; $output = new ConsoleSectionOutput($this->stream, $sections, OutputInterface::VERBOSITY_NORMAL, true, new OutputFormatter()); - $output->writeln('Foo'.PHP_EOL.'Bar'); + $output->writeln('Foo'.\PHP_EOL.'Bar'); $output->clear(); rewind($output->getStream()); - $this->assertEquals('Foo'.PHP_EOL.'Bar'.PHP_EOL.sprintf("\x1b[%dA", 2)."\x1b[0J", stream_get_contents($output->getStream())); + $this->assertEquals('Foo'.\PHP_EOL.'Bar'.\PHP_EOL.sprintf("\x1b[%dA", 2)."\x1b[0J", stream_get_contents($output->getStream())); } public function testClearNumberOfLines() @@ -55,7 +55,7 @@ public function testClearNumberOfLines() $output->clear(2); rewind($output->getStream()); - $this->assertEquals("Foo\nBar\nBaz\nFooBar".PHP_EOL.sprintf("\x1b[%dA", 2)."\x1b[0J", stream_get_contents($output->getStream())); + $this->assertEquals("Foo\nBar\nBaz\nFooBar".\PHP_EOL.sprintf("\x1b[%dA", 2)."\x1b[0J", stream_get_contents($output->getStream())); } public function testClearNumberOfLinesWithMultipleSections() @@ -72,7 +72,7 @@ public function testClearNumberOfLinesWithMultipleSections() rewind($output->getStream()); - $this->assertEquals('Foo'.PHP_EOL.'Bar'.PHP_EOL."\x1b[1A\x1b[0J\e[1A\e[0J".'Baz'.PHP_EOL.'Foo'.PHP_EOL, stream_get_contents($output->getStream())); + $this->assertEquals('Foo'.\PHP_EOL.'Bar'.\PHP_EOL."\x1b[1A\x1b[0J\e[1A\e[0J".'Baz'.\PHP_EOL.'Foo'.\PHP_EOL, stream_get_contents($output->getStream())); } public function testClearPreservingEmptyLines() @@ -82,13 +82,13 @@ public function testClearPreservingEmptyLines() $output1 = new ConsoleSectionOutput($output->getStream(), $sections, OutputInterface::VERBOSITY_NORMAL, true, new OutputFormatter()); $output2 = new ConsoleSectionOutput($output->getStream(), $sections, OutputInterface::VERBOSITY_NORMAL, true, new OutputFormatter()); - $output2->writeln(PHP_EOL.'foo'); + $output2->writeln(\PHP_EOL.'foo'); $output2->clear(1); $output1->writeln('bar'); rewind($output->getStream()); - $this->assertEquals(PHP_EOL.'foo'.PHP_EOL."\x1b[1A\x1b[0J\x1b[1A\x1b[0J".'bar'.PHP_EOL.PHP_EOL, stream_get_contents($output->getStream())); + $this->assertEquals(\PHP_EOL.'foo'.\PHP_EOL."\x1b[1A\x1b[0J\x1b[1A\x1b[0J".'bar'.\PHP_EOL.\PHP_EOL, stream_get_contents($output->getStream())); } public function testOverwrite() @@ -100,7 +100,7 @@ public function testOverwrite() $output->overwrite('Bar'); rewind($output->getStream()); - $this->assertEquals('Foo'.PHP_EOL."\x1b[1A\x1b[0JBar".PHP_EOL, stream_get_contents($output->getStream())); + $this->assertEquals('Foo'.\PHP_EOL."\x1b[1A\x1b[0JBar".\PHP_EOL, stream_get_contents($output->getStream())); } public function testOverwriteMultipleLines() @@ -108,11 +108,11 @@ public function testOverwriteMultipleLines() $sections = []; $output = new ConsoleSectionOutput($this->stream, $sections, OutputInterface::VERBOSITY_NORMAL, true, new OutputFormatter()); - $output->writeln('Foo'.PHP_EOL.'Bar'.PHP_EOL.'Baz'); + $output->writeln('Foo'.\PHP_EOL.'Bar'.\PHP_EOL.'Baz'); $output->overwrite('Bar'); rewind($output->getStream()); - $this->assertEquals('Foo'.PHP_EOL.'Bar'.PHP_EOL.'Baz'.PHP_EOL.sprintf("\x1b[%dA", 3)."\x1b[0J".'Bar'.PHP_EOL, stream_get_contents($output->getStream())); + $this->assertEquals('Foo'.\PHP_EOL.'Bar'.\PHP_EOL.'Baz'.\PHP_EOL.sprintf("\x1b[%dA", 3)."\x1b[0J".'Bar'.\PHP_EOL, stream_get_contents($output->getStream())); } public function testAddingMultipleSections() @@ -138,7 +138,7 @@ public function testMultipleSectionsOutput() $output2->overwrite('Foobar'); rewind($output->getStream()); - $this->assertEquals('Foo'.PHP_EOL.'Bar'.PHP_EOL."\x1b[2A\x1b[0JBar".PHP_EOL."\x1b[1A\x1b[0JBaz".PHP_EOL.'Bar'.PHP_EOL."\x1b[1A\x1b[0JFoobar".PHP_EOL, stream_get_contents($output->getStream())); + $this->assertEquals('Foo'.\PHP_EOL.'Bar'.\PHP_EOL."\x1b[2A\x1b[0JBar".\PHP_EOL."\x1b[1A\x1b[0JBaz".\PHP_EOL.'Bar'.\PHP_EOL."\x1b[1A\x1b[0JFoobar".\PHP_EOL, stream_get_contents($output->getStream())); } public function testClearSectionContainingQuestion() @@ -158,6 +158,6 @@ public function testClearSectionContainingQuestion() $output->clear(); rewind($output->getStream()); - $this->assertSame('What\'s your favorite super hero?'.PHP_EOL."\x1b[2A\x1b[0J", stream_get_contents($output->getStream())); + $this->assertSame('What\'s your favorite super hero?'.\PHP_EOL."\x1b[2A\x1b[0J", stream_get_contents($output->getStream())); } } diff --git a/src/Symfony/Component/Console/Tests/Output/StreamOutputTest.php b/src/Symfony/Component/Console/Tests/Output/StreamOutputTest.php index 8fa9dfd1047c..a434fead42b1 100644 --- a/src/Symfony/Component/Console/Tests/Output/StreamOutputTest.php +++ b/src/Symfony/Component/Console/Tests/Output/StreamOutputTest.php @@ -54,7 +54,7 @@ public function testDoWrite() $output = new StreamOutput($this->stream); $output->writeln('foo'); rewind($output->getStream()); - $this->assertEquals('foo'.PHP_EOL, stream_get_contents($output->getStream()), '->doWrite() writes to the stream'); + $this->assertEquals('foo'.\PHP_EOL, stream_get_contents($output->getStream()), '->doWrite() writes to the stream'); } public function testDoWriteOnFailure() diff --git a/src/Symfony/Component/Console/Tests/Tester/ApplicationTesterTest.php b/src/Symfony/Component/Console/Tests/Tester/ApplicationTesterTest.php index 8361602dd7e9..dabf0098872d 100644 --- a/src/Symfony/Component/Console/Tests/Tester/ApplicationTesterTest.php +++ b/src/Symfony/Component/Console/Tests/Tester/ApplicationTesterTest.php @@ -59,12 +59,12 @@ public function testGetInput() public function testGetOutput() { rewind($this->tester->getOutput()->getStream()); - $this->assertEquals('foo'.PHP_EOL, stream_get_contents($this->tester->getOutput()->getStream()), '->getOutput() returns the current output instance'); + $this->assertEquals('foo'.\PHP_EOL, stream_get_contents($this->tester->getOutput()->getStream()), '->getOutput() returns the current output instance'); } public function testGetDisplay() { - $this->assertEquals('foo'.PHP_EOL, $this->tester->getDisplay(), '->getDisplay() returns the display of the last execution'); + $this->assertEquals('foo'.\PHP_EOL, $this->tester->getDisplay(), '->getDisplay() returns the display of the last execution'); } public function testSetInputs() diff --git a/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php b/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php index d48126cbe95c..11a4bfaf4fee 100644 --- a/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php +++ b/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php @@ -59,12 +59,12 @@ public function testGetInput() public function testGetOutput() { rewind($this->tester->getOutput()->getStream()); - $this->assertEquals('foo'.PHP_EOL, stream_get_contents($this->tester->getOutput()->getStream()), '->getOutput() returns the current output instance'); + $this->assertEquals('foo'.\PHP_EOL, stream_get_contents($this->tester->getOutput()->getStream()), '->getOutput() returns the current output instance'); } public function testGetDisplay() { - $this->assertEquals('foo'.PHP_EOL, $this->tester->getDisplay(), '->getDisplay() returns the display of the last execution'); + $this->assertEquals('foo'.\PHP_EOL, $this->tester->getDisplay(), '->getDisplay() returns the display of the last execution'); } public function testGetStatusCode() diff --git a/src/Symfony/Component/DependencyInjection/Compiler/DecoratorServicePass.php b/src/Symfony/Component/DependencyInjection/Compiler/DecoratorServicePass.php index 55f87b04b9ae..c9931fb72619 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/DecoratorServicePass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/DecoratorServicePass.php @@ -36,7 +36,7 @@ public function __construct(?string $innerId = '.inner') public function process(ContainerBuilder $container) { $definitions = new \SplPriorityQueue(); - $order = PHP_INT_MAX; + $order = \PHP_INT_MAX; foreach ($container->getDefinitions() as $id => $definition) { if (!$decorated = $definition->getDecoratedService()) { diff --git a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php index 2153304485fd..ec82969d1bb4 100644 --- a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php +++ b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php @@ -1088,7 +1088,7 @@ private function createService(Definition $definition, array &$inlineServices, b } else { $r = new \ReflectionClass($parameterBag->resolveValue($definition->getClass())); - $service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs($arguments); + $service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs(array_values($arguments)); if (!$definition->isDeprecated() && 0 < strpos($r->getDocComment(), "\n * @deprecated ")) { trigger_deprecation('', '', 'The "%s" service relies on the deprecated "%s" class. It should either be deprecated or its implementation upgraded.', $id, $r->name); diff --git a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php index 2126eabf54f9..fd25b64f7a8a 100644 --- a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php +++ b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php @@ -326,7 +326,7 @@ class %s extends {$options['class']} $this->asFiles = false; if ($this->preload && null !== $autoloadFile = $this->getAutoloadFile()) { - $autoloadFile = substr($this->export($autoloadFile), 2, -1); + $autoloadFile = trim($this->export($autoloadFile), '()\\'); $preloadedFiles = array_reverse($preloadedFiles); $preloadedFiles = implode("';\nrequire __DIR__.'/", $preloadedFiles); @@ -2052,11 +2052,19 @@ private function isSingleUsePrivateNode(ServiceReferenceGraphNode $node): bool */ private function export($value) { - if (null !== $this->targetDirRegex && \is_string($value) && preg_match($this->targetDirRegex, $value, $matches, PREG_OFFSET_CAPTURE)) { + if (null !== $this->targetDirRegex && \is_string($value) && preg_match($this->targetDirRegex, $value, $matches, \PREG_OFFSET_CAPTURE)) { $suffix = $matches[0][1] + \strlen($matches[0][0]); $matches[0][1] += \strlen($matches[1][0]); $prefix = $matches[0][1] ? $this->doExport(substr($value, 0, $matches[0][1]), true).'.' : ''; - $suffix = isset($value[$suffix]) ? '.'.$this->doExport(substr($value, $suffix), true) : ''; + + if ('\\' === \DIRECTORY_SEPARATOR && isset($value[$suffix])) { + $cookie = '\\'.random_int(100000, \PHP_INT_MAX); + $suffix = '.'.$this->doExport(str_replace('\\', $cookie, substr($value, $suffix)), true); + $suffix = str_replace('\\'.$cookie, "'.\\DIRECTORY_SEPARATOR.'", $suffix); + } else { + $suffix = isset($value[$suffix]) ? '.'.$this->doExport(substr($value, $suffix), true) : ''; + } + $dirname = $this->asFiles ? '$this->containerDir' : '__DIR__'; $offset = 2 + $this->targetDirMaxMatches - \count($matches); @@ -2123,9 +2131,7 @@ private function doExport($value, bool $resolveEnv = false) private function getAutoloadFile(): ?string { - if (null === $this->targetDirRegex) { - return null; - } + $file = null; foreach (spl_autoload_functions() as $autoloader) { if (!\is_array($autoloader)) { @@ -2144,14 +2150,14 @@ private function getAutoloadFile(): ?string if (0 === strpos($class, 'ComposerAutoloaderInit') && $class::getLoader() === $autoloader[0]) { $file = \dirname((new \ReflectionClass($class))->getFileName(), 2).'/autoload.php'; - if (preg_match($this->targetDirRegex.'A', $file)) { + if (null !== $this->targetDirRegex && preg_match($this->targetDirRegex.'A', $file)) { return $file; } } } } - return null; + return $file; } private function getClasses(Definition $definition, string $id): array diff --git a/src/Symfony/Component/DependencyInjection/Dumper/Preloader.php b/src/Symfony/Component/DependencyInjection/Dumper/Preloader.php index ef5a1c3237ed..c64559c49d6d 100644 --- a/src/Symfony/Component/DependencyInjection/Dumper/Preloader.php +++ b/src/Symfony/Component/DependencyInjection/Dumper/Preloader.php @@ -27,14 +27,14 @@ public static function append(string $file, array $list): void foreach ($list as $item) { if (0 === strpos($item, $cacheDir)) { - file_put_contents($file, sprintf("require_once __DIR__.%s;\n", var_export(substr($item, \strlen($cacheDir)), true)), FILE_APPEND); + file_put_contents($file, sprintf("require_once __DIR__.%s;\n", var_export(strtr(substr($item, \strlen($cacheDir)), \DIRECTORY_SEPARATOR, '/'), true)), \FILE_APPEND); continue; } $classes[] = sprintf("\$classes[] = %s;\n", var_export($item, true)); } - file_put_contents($file, sprintf("\n\$classes = [];\n%sPreloader::preload(\$classes);\n", implode('', $classes)), FILE_APPEND); + file_put_contents($file, sprintf("\n\$classes = [];\n%sPreloader::preload(\$classes);\n", implode('', $classes)), \FILE_APPEND); } public static function preload(array $classes): void diff --git a/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php b/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php index b16bad18dff4..3aba21e6e605 100644 --- a/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php +++ b/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php @@ -192,11 +192,11 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv) } if ('bool' === $prefix) { - return (bool) (filter_var($env, FILTER_VALIDATE_BOOLEAN) ?: filter_var($env, FILTER_VALIDATE_INT) ?: filter_var($env, FILTER_VALIDATE_FLOAT)); + return (bool) (filter_var($env, \FILTER_VALIDATE_BOOLEAN) ?: filter_var($env, \FILTER_VALIDATE_INT) ?: filter_var($env, \FILTER_VALIDATE_FLOAT)); } if ('int' === $prefix) { - if (false === $env = filter_var($env, FILTER_VALIDATE_INT) ?: filter_var($env, FILTER_VALIDATE_FLOAT)) { + if (false === $env = filter_var($env, \FILTER_VALIDATE_INT) ?: filter_var($env, \FILTER_VALIDATE_FLOAT)) { throw new RuntimeException(sprintf('Non-numeric env var "%s" cannot be cast to int.', $name)); } @@ -204,7 +204,7 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv) } if ('float' === $prefix) { - if (false === $env = filter_var($env, FILTER_VALIDATE_FLOAT)) { + if (false === $env = filter_var($env, \FILTER_VALIDATE_FLOAT)) { throw new RuntimeException(sprintf('Non-numeric env var "%s" cannot be cast to float.', $name)); } @@ -226,7 +226,7 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv) if ('json' === $prefix) { $env = json_decode($env, true); - if (JSON_ERROR_NONE !== json_last_error()) { + if (\JSON_ERROR_NONE !== json_last_error()) { throw new RuntimeException(sprintf('Invalid JSON in env var "%s": ', $name).json_last_error_msg()); } @@ -262,7 +262,7 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv) } if ('query_string' === $prefix) { - $queryString = parse_url($env, PHP_URL_QUERY) ?: $env; + $queryString = parse_url($env, \PHP_URL_QUERY) ?: $env; parse_str($queryString, $result); return $result; diff --git a/src/Symfony/Component/DependencyInjection/Loader/IniFileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/IniFileLoader.php index e6384803c36e..f313cbcae4d2 100644 --- a/src/Symfony/Component/DependencyInjection/Loader/IniFileLoader.php +++ b/src/Symfony/Component/DependencyInjection/Loader/IniFileLoader.php @@ -37,7 +37,7 @@ public function load($resource, string $type = null) } // real raw parsing - $result = parse_ini_file($path, true, INI_SCANNER_RAW); + $result = parse_ini_file($path, true, \INI_SCANNER_RAW); if (isset($result['parameters']) && \is_array($result['parameters'])) { foreach ($result['parameters'] as $key => $value) { @@ -55,7 +55,7 @@ public function supports($resource, string $type = null) return false; } - if (null === $type && 'ini' === pathinfo($resource, PATHINFO_EXTENSION)) { + if (null === $type && 'ini' === pathinfo($resource, \PATHINFO_EXTENSION)) { return true; } diff --git a/src/Symfony/Component/DependencyInjection/Loader/PhpFileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/PhpFileLoader.php index 207fb83ec180..196baf622b75 100644 --- a/src/Symfony/Component/DependencyInjection/Loader/PhpFileLoader.php +++ b/src/Symfony/Component/DependencyInjection/Loader/PhpFileLoader.php @@ -64,7 +64,7 @@ public function supports($resource, string $type = null) return false; } - if (null === $type && 'php' === pathinfo($resource, PATHINFO_EXTENSION)) { + if (null === $type && 'php' === pathinfo($resource, \PATHINFO_EXTENSION)) { return true; } diff --git a/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php index 1294edba7175..33b5a009f7b4 100644 --- a/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php +++ b/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php @@ -82,7 +82,7 @@ public function supports($resource, string $type = null) return false; } - if (null === $type && 'xml' === pathinfo($resource, PATHINFO_EXTENSION)) { + if (null === $type && 'xml' === pathinfo($resource, \PATHINFO_EXTENSION)) { return true; } @@ -624,7 +624,7 @@ public function validateSchema(\DOMDocument $dom) EOF ; - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { $disableEntities = libxml_disable_entity_loader(false); $valid = @$dom->schemaValidateSource($source); libxml_disable_entity_loader($disableEntities); diff --git a/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php index 417e568ed0af..9df17b55535e 100644 --- a/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php +++ b/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php @@ -167,7 +167,7 @@ public function supports($resource, string $type = null) return false; } - if (null === $type && \in_array(pathinfo($resource, PATHINFO_EXTENSION), ['yaml', 'yml'], true)) { + if (null === $type && \in_array(pathinfo($resource, \PATHINFO_EXTENSION), ['yaml', 'yml'], true)) { return true; } diff --git a/src/Symfony/Component/DependencyInjection/ServiceLocator.php b/src/Symfony/Component/DependencyInjection/ServiceLocator.php index dd97e39d138d..41f6c97d44cb 100644 --- a/src/Symfony/Component/DependencyInjection/ServiceLocator.php +++ b/src/Symfony/Component/DependencyInjection/ServiceLocator.php @@ -84,7 +84,7 @@ private function createNotFoundException(string $id): NotFoundExceptionInterface return new ServiceNotFoundException($id, end($this->loading) ?: null, null, [], $msg); } - $class = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, 4); + $class = debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS, 4); $class = isset($class[3]['object']) ? \get_class($class[3]['object']) : null; $externalId = $this->externalId ?: $class; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php index e02de5e2fca6..f66959d0eb32 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php @@ -239,7 +239,7 @@ public function testDumpAsFiles() $dumper = new PhpDumper($container); $dump = print_r($dumper->dump(['as_files' => true, 'file' => __DIR__, 'hot_path_tag' => 'hot', 'inline_factories_parameter' => false, 'inline_class_loader_parameter' => false]), true); if ('\\' === \DIRECTORY_SEPARATOR) { - $dump = str_replace('\\\\Fixtures\\\\includes\\\\foo.php', '/Fixtures/includes/foo.php', $dump); + $dump = str_replace("'.\\DIRECTORY_SEPARATOR.'", '/', $dump); } $this->assertStringMatchesFormatFile(self::$fixturesPath.'/php/services9_as_files.txt', $dump); } @@ -266,7 +266,7 @@ public function testDumpAsFilesWithFactoriesInlined() $dump = print_r($dumper->dump(['as_files' => true, 'file' => __DIR__, 'hot_path_tag' => 'hot', 'build_time' => 1563381341]), true); if ('\\' === \DIRECTORY_SEPARATOR) { - $dump = str_replace('\\\\Fixtures\\\\includes\\\\', '/Fixtures/includes/', $dump); + $dump = str_replace("'.\\DIRECTORY_SEPARATOR.'", '/', $dump); } $this->assertStringMatchesFormatFile(self::$fixturesPath.'/php/services9_inlined_factories.txt', $dump); } @@ -292,7 +292,7 @@ public function testDumpAsFilesWithLazyFactoriesInlined() $dump = print_r($dumper->dump(['as_files' => true, 'file' => __DIR__, 'hot_path_tag' => 'hot', 'build_time' => 1563381341]), true); if ('\\' === \DIRECTORY_SEPARATOR) { - $dump = str_replace('\\\\Fixtures\\\\includes\\\\', '/Fixtures/includes/', $dump); + $dump = str_replace("'.\\DIRECTORY_SEPARATOR.'", '/', $dump); } $this->assertStringMatchesFormatFile(self::$fixturesPath.'/php/services9_lazy_inlined_factories.txt', $dump); } @@ -310,7 +310,7 @@ public function testNonSharedLazyDumpAsFiles() $dump = print_r($dumper->dump(['as_files' => true, 'file' => __DIR__, 'inline_factories_parameter' => false, 'inline_class_loader_parameter' => false]), true); if ('\\' === \DIRECTORY_SEPARATOR) { - $dump = str_replace('\\\\Fixtures\\\\includes\\\\foo_lazy.php', '/Fixtures/includes/foo_lazy.php', $dump); + $dump = str_replace("'.\\DIRECTORY_SEPARATOR.'", '/', $dump); } $this->assertStringMatchesFormatFile(self::$fixturesPath.'/php/services_non_shared_lazy_as_files.txt', $dump); } @@ -986,7 +986,7 @@ public function testArrayParameters() $dumper = new PhpDumper($container); - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_array_params.php', str_replace('\\\\Dumper', '/Dumper', $dumper->dump(['file' => self::$fixturesPath.'/php/services_array_params.php', 'inline_factories_parameter' => false, 'inline_class_loader_parameter' => false]))); + $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_array_params.php', str_replace("'.\\DIRECTORY_SEPARATOR.'", '/', $dumper->dump(['file' => self::$fixturesPath.'/php/services_array_params.php', 'inline_factories_parameter' => false, 'inline_class_loader_parameter' => false]))); } public function testExpressionReferencingPrivateService() @@ -1149,7 +1149,7 @@ public function testHotPathOptimizations() $dump = $dumper->dump(['hot_path_tag' => 'container.hot_path', 'inline_class_loader_parameter' => 'inline_requires', 'file' => self::$fixturesPath.'/php/services_inline_requires.php']); if ('\\' === \DIRECTORY_SEPARATOR) { - $dump = str_replace("'\\\\includes\\\\HotPath\\\\", "'/includes/HotPath/", $dump); + $dump = str_replace("'.\\DIRECTORY_SEPARATOR.'", '/', $dump); } $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_inline_requires.php', $dump); diff --git a/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php b/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php index 313bce597366..116f571770c1 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php @@ -196,7 +196,7 @@ public function validConsts() { return [ ['Symfony\Component\DependencyInjection\Tests\EnvVarProcessorTest::TEST_CONST', self::TEST_CONST], - ['E_ERROR', E_ERROR], + ['E_ERROR', \E_ERROR], ]; } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php index 24b4f94bebda..87706820bcd5 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php @@ -75,7 +75,7 @@ public function testImportWithGlobPattern() ['foo', 'bar'], ], 'mixedcase' => ['MixedCaseKey' => 'value'], - 'constant' => PHP_EOL, + 'constant' => \PHP_EOL, 'bar' => '%foo%', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar'), diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.php index 4b08d059b320..52c3129fbd28 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.php @@ -53,7 +53,7 @@ public function testTypeConversionsWithNativePhp($key, $value, $supported) $this->markTestSkipped(sprintf('Converting the value "%s" to "%s" is not supported by the IniFileLoader.', $key, $value)); } - $expected = parse_ini_file(__DIR__.'/../Fixtures/ini/types.ini', true, INI_SCANNER_TYPED); + $expected = parse_ini_file(__DIR__.'/../Fixtures/ini/types.ini', true, \INI_SCANNER_TYPED); $this->assertSame($value, $expected['parameters'][$key], '->load() converts values to PHP types'); } @@ -69,7 +69,7 @@ public function getTypeConversions() ['no', false, true], ['none', false, true], ['null', null, true], - ['constant', PHP_VERSION, true], + ['constant', \PHP_VERSION, true], ['12', 12, true], ['12_string', '12', true], ['12_quoted_number', 12, false], // INI_SCANNER_RAW removes the double quotes diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php index 89d721cb3a73..09f13addbb9d 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php @@ -104,7 +104,7 @@ public function testParseFile() public function testLoadWithExternalEntitiesDisabled() { - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { $disableEntities = libxml_disable_entity_loader(true); } @@ -112,7 +112,7 @@ public function testLoadWithExternalEntitiesDisabled() $loader = new XmlFileLoader($containerBuilder, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services2.xml'); - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { libxml_disable_entity_loader($disableEntities); } @@ -144,7 +144,7 @@ public function testLoadParameters() ['foo', 'bar'], ], 'mixedcase' => ['MixedCaseKey' => 'value'], - 'constant' => PHP_EOL, + 'constant' => \PHP_EOL, ]; $this->assertEquals($expected, $actual, '->load() converts XML values to PHP ones'); @@ -180,7 +180,7 @@ public function testLoadImports() ['foo', 'bar'], ], 'mixedcase' => ['MixedCaseKey' => 'value'], - 'constant' => PHP_EOL, + 'constant' => \PHP_EOL, 'bar' => '%foo%', 'imported_from_ini' => true, 'imported_from_yaml' => true, @@ -716,7 +716,7 @@ public function testPrototype() sort($ids); $this->assertSame([Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'], $ids); - $resources = $container->getResources(); + $resources = array_map('strval', $container->getResources()); $fixturesDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR; $this->assertContains((string) new FileResource($fixturesDir.'xml'.\DIRECTORY_SEPARATOR.'services_prototype.xml'), $resources); @@ -734,7 +734,6 @@ public function testPrototype() ] ); $this->assertContains((string) $globResource, $resources); - $resources = array_map('strval', $resources); $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Foo', $resources); $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar', $resources); } @@ -749,7 +748,7 @@ public function testPrototypeExcludeWithArray() sort($ids); $this->assertSame([Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'], $ids); - $resources = $container->getResources(); + $resources = array_map('strval', $container->getResources()); $fixturesDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR; $this->assertContains((string) new FileResource($fixturesDir.'xml'.\DIRECTORY_SEPARATOR.'services_prototype_array.xml'), $resources); @@ -767,7 +766,6 @@ public function testPrototypeExcludeWithArray() ] ); $this->assertContains((string) $globResource, $resources); - $resources = array_map('strval', $resources); $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Foo', $resources); $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar', $resources); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php index 26aadbaee22c..271f591d8d94 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php @@ -106,7 +106,7 @@ public function testLoadParameters() $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services2.yml'); - $this->assertEquals(['foo' => 'bar', 'mixedcase' => ['MixedCaseKey' => 'value'], 'values' => [true, false, 0, 1000.3, PHP_INT_MAX], 'bar' => 'foo', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar')], $container->getParameterBag()->all(), '->load() converts YAML keys to lowercase'); + $this->assertEquals(['foo' => 'bar', 'mixedcase' => ['MixedCaseKey' => 'value'], 'values' => [true, false, 0, 1000.3, \PHP_INT_MAX], 'bar' => 'foo', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar')], $container->getParameterBag()->all(), '->load() converts YAML keys to lowercase'); } public function testLoadImports() @@ -124,7 +124,7 @@ public function testLoadImports() $actual = $container->getParameterBag()->all(); $expected = [ 'foo' => 'bar', - 'values' => [true, false, PHP_INT_MAX], + 'values' => [true, false, \PHP_INT_MAX], 'bar' => '%foo%', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar'), @@ -445,7 +445,7 @@ public function testPrototype() sort($ids); $this->assertSame([Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'], $ids); - $resources = $container->getResources(); + $resources = array_map('strval', $container->getResources()); $fixturesDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR; $this->assertContains((string) new FileResource($fixturesDir.'yaml'.\DIRECTORY_SEPARATOR.'services_prototype.yml'), $resources); @@ -462,7 +462,6 @@ public function testPrototype() ] ); $this->assertContains((string) $globResource, $resources); - $resources = array_map('strval', $resources); $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Foo', $resources); $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar', $resources); } diff --git a/src/Symfony/Component/DomCrawler/AbstractUriElement.php b/src/Symfony/Component/DomCrawler/AbstractUriElement.php index ac77724a6095..773e9f650f16 100644 --- a/src/Symfony/Component/DomCrawler/AbstractUriElement.php +++ b/src/Symfony/Component/DomCrawler/AbstractUriElement.php @@ -46,7 +46,7 @@ public function __construct(\DOMElement $node, string $currentUri = null, ?strin $this->method = $method ? strtoupper($method) : null; $this->currentUri = $currentUri; - $elementUriIsRelative = null === parse_url(trim($this->getRawUri()), PHP_URL_SCHEME); + $elementUriIsRelative = null === parse_url(trim($this->getRawUri()), \PHP_URL_SCHEME); $baseUriIsAbsolute = \in_array(strtolower(substr($this->currentUri, 0, 4)), ['http', 'file']); if ($elementUriIsRelative && !$baseUriIsAbsolute) { throw new \InvalidArgumentException(sprintf('The URL of the element is relative, so you must define its base URI passing an absolute URL to the constructor of the "%s" class ("%s" was passed).', __CLASS__, $this->currentUri)); diff --git a/src/Symfony/Component/DomCrawler/Crawler.php b/src/Symfony/Component/DomCrawler/Crawler.php index 0f80578a82e0..3627aad5a10c 100644 --- a/src/Symfony/Component/DomCrawler/Crawler.php +++ b/src/Symfony/Component/DomCrawler/Crawler.php @@ -214,7 +214,7 @@ public function addHtmlContent(string $content, string $charset = 'UTF-8') * LIBXML_PARSEHUGE is dangerous, see * http://symfony.com/blog/security-release-symfony-2-0-17-released */ - public function addXmlContent(string $content, string $charset = 'UTF-8', int $options = LIBXML_NONET) + public function addXmlContent(string $content, string $charset = 'UTF-8', int $options = \LIBXML_NONET) { // remove the default namespace if it's the only namespace to make XPath expressions simpler if (!preg_match('/xmlns:/', $content)) { @@ -222,7 +222,7 @@ public function addXmlContent(string $content, string $charset = 'UTF-8', int $o } $internalErrors = libxml_use_internal_errors(true); - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { $disableEntities = libxml_disable_entity_loader(true); } @@ -234,7 +234,7 @@ public function addXmlContent(string $content, string $charset = 'UTF-8', int $o } libxml_use_internal_errors($internalErrors); - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { libxml_disable_entity_loader($disableEntities); } @@ -442,7 +442,7 @@ public function closest(string $selector): ?self $domNode = $this->getNode(0); - while (XML_ELEMENT_NODE === $domNode->nodeType) { + while (\XML_ELEMENT_NODE === $domNode->nodeType) { $node = $this->createSubCrawler($domNode); if ($node->matches($selector)) { return $node; @@ -503,7 +503,7 @@ public function parents() $nodes = []; while ($node = $node->parentNode) { - if (XML_ELEMENT_NODE === $node->nodeType) { + if (\XML_ELEMENT_NODE === $node->nodeType) { $nodes[] = $node; } } @@ -1104,7 +1104,7 @@ protected function sibling($node, string $siblingDir = 'nextSibling') $currentNode = $this->getNode(0); do { - if ($node !== $currentNode && XML_ELEMENT_NODE === $node->nodeType) { + if ($node !== $currentNode && \XML_ELEMENT_NODE === $node->nodeType) { $nodes[] = $node; } } while ($node = $node->$siblingDir); @@ -1122,7 +1122,7 @@ private function parseXhtml(string $htmlContent, string $charset = 'UTF-8'): \DO $htmlContent = $this->convertToHtmlEntities($htmlContent, $charset); $internalErrors = libxml_use_internal_errors(true); - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { $disableEntities = libxml_disable_entity_loader(true); } @@ -1134,7 +1134,7 @@ private function parseXhtml(string $htmlContent, string $charset = 'UTF-8'): \DO } libxml_use_internal_errors($internalErrors); - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { libxml_disable_entity_loader($disableEntities); } diff --git a/src/Symfony/Component/DomCrawler/Field/FileFormField.php b/src/Symfony/Component/DomCrawler/Field/FileFormField.php index d4d60be22732..bd97e7688ea1 100644 --- a/src/Symfony/Component/DomCrawler/Field/FileFormField.php +++ b/src/Symfony/Component/DomCrawler/Field/FileFormField.php @@ -27,7 +27,7 @@ class FileFormField extends FormField */ public function setErrorCode(int $error) { - $codes = [UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_PARTIAL, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_EXTENSION]; + $codes = [\UPLOAD_ERR_INI_SIZE, \UPLOAD_ERR_FORM_SIZE, \UPLOAD_ERR_PARTIAL, \UPLOAD_ERR_NO_FILE, \UPLOAD_ERR_NO_TMP_DIR, \UPLOAD_ERR_CANT_WRITE, \UPLOAD_ERR_EXTENSION]; if (!\in_array($error, $codes)) { throw new \InvalidArgumentException(sprintf('The error code "%s" is not valid.', $error)); } @@ -49,7 +49,7 @@ public function upload(?string $value) public function setValue(?string $value) { if (null !== $value && is_readable($value)) { - $error = UPLOAD_ERR_OK; + $error = \UPLOAD_ERR_OK; $size = filesize($value); $info = pathinfo($value); $name = $info['basename']; @@ -65,7 +65,7 @@ public function setValue(?string $value) copy($value, $tmp); $value = $tmp; } else { - $error = UPLOAD_ERR_NO_FILE; + $error = \UPLOAD_ERR_NO_FILE; $size = 0; $name = ''; $value = ''; diff --git a/src/Symfony/Component/DomCrawler/Form.php b/src/Symfony/Component/DomCrawler/Form.php index adafc0a07ce1..9b5c2892d093 100644 --- a/src/Symfony/Component/DomCrawler/Form.php +++ b/src/Symfony/Component/DomCrawler/Form.php @@ -203,7 +203,7 @@ public function getUri() $uri = parent::getUri(); if (!\in_array($this->getMethod(), ['POST', 'PUT', 'DELETE', 'PATCH'])) { - $query = parse_url($uri, PHP_URL_QUERY); + $query = parse_url($uri, \PHP_URL_QUERY); $currentParameters = []; if ($query) { parse_str($query, $currentParameters); diff --git a/src/Symfony/Component/DomCrawler/Tests/Field/FileFormFieldTest.php b/src/Symfony/Component/DomCrawler/Tests/Field/FileFormFieldTest.php index 381386cd813e..dc665f1546f9 100644 --- a/src/Symfony/Component/DomCrawler/Tests/Field/FileFormFieldTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/Field/FileFormFieldTest.php @@ -20,7 +20,7 @@ public function testInitialize() $node = $this->createNode('input', '', ['type' => 'file']); $field = new FileFormField($node); - $this->assertEquals(['name' => '', 'type' => '', 'tmp_name' => '', 'error' => UPLOAD_ERR_NO_FILE, 'size' => 0], $field->getValue(), '->initialize() sets the value of the field to no file uploaded'); + $this->assertEquals(['name' => '', 'type' => '', 'tmp_name' => '', 'error' => \UPLOAD_ERR_NO_FILE, 'size' => 0], $field->getValue(), '->initialize() sets the value of the field to no file uploaded'); $node = $this->createNode('textarea', ''); try { @@ -48,7 +48,7 @@ public function testSetValue($method) $field = new FileFormField($node); $field->$method(null); - $this->assertEquals(['name' => '', 'type' => '', 'tmp_name' => '', 'error' => UPLOAD_ERR_NO_FILE, 'size' => 0], $field->getValue(), "->$method() clears the uploaded file if the value is null"); + $this->assertEquals(['name' => '', 'type' => '', 'tmp_name' => '', 'error' => \UPLOAD_ERR_NO_FILE, 'size' => 0], $field->getValue(), "->$method() clears the uploaded file if the value is null"); $field->$method(__FILE__); $value = $field->getValue(); @@ -91,9 +91,9 @@ public function testSetErrorCode() $node = $this->createNode('input', '', ['type' => 'file']); $field = new FileFormField($node); - $field->setErrorCode(UPLOAD_ERR_FORM_SIZE); + $field->setErrorCode(\UPLOAD_ERR_FORM_SIZE); $value = $field->getValue(); - $this->assertEquals(UPLOAD_ERR_FORM_SIZE, $value['error'], '->setErrorCode() sets the file input field error code'); + $this->assertEquals(\UPLOAD_ERR_FORM_SIZE, $value['error'], '->setErrorCode() sets the file input field error code'); try { $field->setErrorCode(12345); diff --git a/src/Symfony/Component/DomCrawler/UriResolver.php b/src/Symfony/Component/DomCrawler/UriResolver.php index 5a57fcc51739..be64f5257018 100644 --- a/src/Symfony/Component/DomCrawler/UriResolver.php +++ b/src/Symfony/Component/DomCrawler/UriResolver.php @@ -33,7 +33,7 @@ public static function resolve(string $uri, ?string $baseUri): string $uri = trim($uri); // absolute URL? - if (null !== parse_url($uri, PHP_URL_SCHEME)) { + if (null !== parse_url($uri, \PHP_URL_SCHEME)) { return $uri; } @@ -70,7 +70,7 @@ public static function resolve(string $uri, ?string $baseUri): string } // relative path - $path = parse_url(substr($baseUri, \strlen($baseUriCleaned)), PHP_URL_PATH); + $path = parse_url(substr($baseUri, \strlen($baseUriCleaned)), \PHP_URL_PATH); $path = self::canonicalizePath(substr($path, 0, strrpos($path, '/')).'/'.$uri); return $baseUriCleaned.('' === $path || '/' !== $path[0] ? '/' : '').$path; diff --git a/src/Symfony/Component/Dotenv/Dotenv.php b/src/Symfony/Component/Dotenv/Dotenv.php index c33caa43f321..8cb2ba82c278 100644 --- a/src/Symfony/Component/Dotenv/Dotenv.php +++ b/src/Symfony/Component/Dotenv/Dotenv.php @@ -161,7 +161,7 @@ public function bootEnv(string $path, string $defaultEnv = 'dev', array $testEnv $k = $this->debugKey; $debug = $_SERVER[$k] ?? !\in_array($_SERVER[$this->envKey], $this->prodEnvs, true); - $_SERVER[$k] = $_ENV[$k] = (int) $debug || (!\is_bool($debug) && filter_var($debug, FILTER_VALIDATE_BOOLEAN)) ? '1' : '0'; + $_SERVER[$k] = $_ENV[$k] = (int) $debug || (!\is_bool($debug) && filter_var($debug, \FILTER_VALIDATE_BOOLEAN)) ? '1' : '0'; } /** diff --git a/src/Symfony/Component/ErrorHandler/Debug.php b/src/Symfony/Component/ErrorHandler/Debug.php index 9cc8ec17a827..4a828121821d 100644 --- a/src/Symfony/Component/ErrorHandler/Debug.php +++ b/src/Symfony/Component/ErrorHandler/Debug.php @@ -24,7 +24,7 @@ public static function enable(): ErrorHandler if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) { ini_set('display_errors', 0); - } elseif (!filter_var(ini_get('log_errors'), FILTER_VALIDATE_BOOLEAN) || ini_get('error_log')) { + } elseif (!filter_var(ini_get('log_errors'), \FILTER_VALIDATE_BOOLEAN) || ini_get('error_log')) { // CLI - display errors only if they're not already logged to STDERR ini_set('display_errors', 1); } diff --git a/src/Symfony/Component/ErrorHandler/DebugClassLoader.php b/src/Symfony/Component/ErrorHandler/DebugClassLoader.php index a0c8954c5f93..42aba12a2d49 100644 --- a/src/Symfony/Component/ErrorHandler/DebugClassLoader.php +++ b/src/Symfony/Component/ErrorHandler/DebugClassLoader.php @@ -204,7 +204,7 @@ public function __construct(callable $classLoader) } elseif (substr($test, -\strlen($file)) === $file) { // filesystem is case insensitive and realpath() normalizes the case of characters self::$caseCheck = 1; - } elseif (false !== stripos(PHP_OS, 'darwin')) { + } elseif (false !== stripos(\PHP_OS, 'darwin')) { // on MacOSX, HFS+ is case insensitive but realpath() doesn't normalize the case of characters self::$caseCheck = 2; } else { @@ -329,7 +329,7 @@ public function findFile(string $class): ?string */ public function loadClass(string $class): void { - $e = error_reporting(error_reporting() | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR); + $e = error_reporting(error_reporting() | \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR); try { if ($this->isFinder && !isset($this->loaded[$class])) { @@ -381,7 +381,7 @@ private function checkClass(string $class, string $file = null): void $deprecations = $this->checkAnnotations($refl, $name); foreach ($deprecations as $message) { - @trigger_error($message, E_USER_DEPRECATED); + @trigger_error($message, \E_USER_DEPRECATED); } } @@ -433,7 +433,7 @@ public function checkAnnotations(\ReflectionClass $refl, string $class): array } } - if ($refl->isInterface() && false !== strpos($doc, 'method') && preg_match_all('#\n \* @method\s+(static\s+)?+([\w\|&\[\]\\\]+\s+)?(\w+(?:\s*\([^\)]*\))?)+(.+?([[:punct:]]\s*)?)?(?=\r?\n \*(?: @|/$|\r?\n))#', $doc, $notice, PREG_SET_ORDER)) { + if ($refl->isInterface() && false !== strpos($doc, 'method') && preg_match_all('#\n \* @method\s+(static\s+)?+([\w\|&\[\]\\\]+\s+)?(\w+(?:\s*\([^\)]*\))?)+(.+?([[:punct:]]\s*)?)?(?=\r?\n \*(?: @|/$|\r?\n))#', $doc, $notice, \PREG_SET_ORDER)) { foreach ($notice as $method) { $static = '' !== $method[1] && !empty($method[2]); $name = $method[3]; @@ -657,7 +657,7 @@ public function checkAnnotations(\ReflectionClass $refl, string $class): array if ($finalOrInternal || $method->isConstructor() || false === strpos($doc, '@param') || StatelessInvocation::class === $class) { continue; } - if (!preg_match_all('#\n\s+\* @param +((?(?!callable *\().*?|callable *\(.*\).*?))(?<= )\$([a-zA-Z0-9_\x7f-\xff]++)#', $doc, $matches, PREG_SET_ORDER)) { + if (!preg_match_all('#\n\s+\* @param +((?(?!callable *\().*?|callable *\(.*\).*?))(?<= )\$([a-zA-Z0-9_\x7f-\xff]++)#', $doc, $matches, \PREG_SET_ORDER)) { continue; } if (!isset(self::$annotatedParameters[$class][$method->name])) { diff --git a/src/Symfony/Component/ErrorHandler/ErrorEnhancer/ClassNotFoundErrorEnhancer.php b/src/Symfony/Component/ErrorHandler/ErrorEnhancer/ClassNotFoundErrorEnhancer.php index 7cd2b382f163..3d9e8b092bbd 100644 --- a/src/Symfony/Component/ErrorHandler/ErrorEnhancer/ClassNotFoundErrorEnhancer.php +++ b/src/Symfony/Component/ErrorHandler/ErrorEnhancer/ClassNotFoundErrorEnhancer.php @@ -28,50 +28,34 @@ public function enhance(\Throwable $error): ?\Throwable { // Some specific versions of PHP produce a fatal error when extending a not found class. $message = !$error instanceof FatalError ? $error->getMessage() : $error->getError()['message']; - $messageLen = \strlen($message); - $notFoundSuffix = '\' not found'; - $notFoundSuffixLen = \strlen($notFoundSuffix); - if ($notFoundSuffixLen > $messageLen) { + if (!preg_match('/^(Class|Interface|Trait) [\'"]([^\'"]+)[\'"] not found$/', $message, $matches)) { return null; } - - if (0 !== substr_compare($message, $notFoundSuffix, -$notFoundSuffixLen)) { - return null; + $typeName = strtolower($matches[1]); + $fullyQualifiedClassName = $matches[2]; + + if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedClassName, '\\')) { + $className = substr($fullyQualifiedClassName, $namespaceSeparatorIndex + 1); + $namespacePrefix = substr($fullyQualifiedClassName, 0, $namespaceSeparatorIndex); + $message = sprintf('Attempted to load %s "%s" from namespace "%s".', $typeName, $className, $namespacePrefix); + $tail = ' for another namespace?'; + } else { + $className = $fullyQualifiedClassName; + $message = sprintf('Attempted to load %s "%s" from the global namespace.', $typeName, $className); + $tail = '?'; } - foreach (['class', 'interface', 'trait'] as $typeName) { - $prefix = ucfirst($typeName).' \''; - $prefixLen = \strlen($prefix); - if (0 !== strpos($message, $prefix)) { - continue; - } - - $fullyQualifiedClassName = substr($message, $prefixLen, -$notFoundSuffixLen); - if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedClassName, '\\')) { - $className = substr($fullyQualifiedClassName, $namespaceSeparatorIndex + 1); - $namespacePrefix = substr($fullyQualifiedClassName, 0, $namespaceSeparatorIndex); - $message = sprintf('Attempted to load %s "%s" from namespace "%s".', $typeName, $className, $namespacePrefix); - $tail = ' for another namespace?'; + if ($candidates = $this->getClassCandidates($className)) { + $tail = array_pop($candidates).'"?'; + if ($candidates) { + $tail = ' for e.g. "'.implode('", "', $candidates).'" or "'.$tail; } else { - $className = $fullyQualifiedClassName; - $message = sprintf('Attempted to load %s "%s" from the global namespace.', $typeName, $className); - $tail = '?'; + $tail = ' for "'.$tail; } - - if ($candidates = $this->getClassCandidates($className)) { - $tail = array_pop($candidates).'"?'; - if ($candidates) { - $tail = ' for e.g. "'.implode('", "', $candidates).'" or "'.$tail; - } else { - $tail = ' for "'.$tail; - } - } - $message .= "\nDid you forget a \"use\" statement".$tail; - - return new ClassNotFoundError($message, $error); } + $message .= "\nDid you forget a \"use\" statement".$tail; - return null; + return new ClassNotFoundError($message, $error); } /** diff --git a/src/Symfony/Component/ErrorHandler/ErrorHandler.php b/src/Symfony/Component/ErrorHandler/ErrorHandler.php index 55164d650955..51283746251e 100644 --- a/src/Symfony/Component/ErrorHandler/ErrorHandler.php +++ b/src/Symfony/Component/ErrorHandler/ErrorHandler.php @@ -51,39 +51,39 @@ class ErrorHandler { private $levels = [ - E_DEPRECATED => 'Deprecated', - E_USER_DEPRECATED => 'User Deprecated', - E_NOTICE => 'Notice', - E_USER_NOTICE => 'User Notice', - E_STRICT => 'Runtime Notice', - E_WARNING => 'Warning', - E_USER_WARNING => 'User Warning', - E_COMPILE_WARNING => 'Compile Warning', - E_CORE_WARNING => 'Core Warning', - E_USER_ERROR => 'User Error', - E_RECOVERABLE_ERROR => 'Catchable Fatal Error', - E_COMPILE_ERROR => 'Compile Error', - E_PARSE => 'Parse Error', - E_ERROR => 'Error', - E_CORE_ERROR => 'Core Error', + \E_DEPRECATED => 'Deprecated', + \E_USER_DEPRECATED => 'User Deprecated', + \E_NOTICE => 'Notice', + \E_USER_NOTICE => 'User Notice', + \E_STRICT => 'Runtime Notice', + \E_WARNING => 'Warning', + \E_USER_WARNING => 'User Warning', + \E_COMPILE_WARNING => 'Compile Warning', + \E_CORE_WARNING => 'Core Warning', + \E_USER_ERROR => 'User Error', + \E_RECOVERABLE_ERROR => 'Catchable Fatal Error', + \E_COMPILE_ERROR => 'Compile Error', + \E_PARSE => 'Parse Error', + \E_ERROR => 'Error', + \E_CORE_ERROR => 'Core Error', ]; private $loggers = [ - E_DEPRECATED => [null, LogLevel::INFO], - E_USER_DEPRECATED => [null, LogLevel::INFO], - E_NOTICE => [null, LogLevel::WARNING], - E_USER_NOTICE => [null, LogLevel::WARNING], - E_STRICT => [null, LogLevel::WARNING], - E_WARNING => [null, LogLevel::WARNING], - E_USER_WARNING => [null, LogLevel::WARNING], - E_COMPILE_WARNING => [null, LogLevel::WARNING], - E_CORE_WARNING => [null, LogLevel::WARNING], - E_USER_ERROR => [null, LogLevel::CRITICAL], - E_RECOVERABLE_ERROR => [null, LogLevel::CRITICAL], - E_COMPILE_ERROR => [null, LogLevel::CRITICAL], - E_PARSE => [null, LogLevel::CRITICAL], - E_ERROR => [null, LogLevel::CRITICAL], - E_CORE_ERROR => [null, LogLevel::CRITICAL], + \E_DEPRECATED => [null, LogLevel::INFO], + \E_USER_DEPRECATED => [null, LogLevel::INFO], + \E_NOTICE => [null, LogLevel::WARNING], + \E_USER_NOTICE => [null, LogLevel::WARNING], + \E_STRICT => [null, LogLevel::WARNING], + \E_WARNING => [null, LogLevel::WARNING], + \E_USER_WARNING => [null, LogLevel::WARNING], + \E_COMPILE_WARNING => [null, LogLevel::WARNING], + \E_CORE_WARNING => [null, LogLevel::WARNING], + \E_USER_ERROR => [null, LogLevel::CRITICAL], + \E_RECOVERABLE_ERROR => [null, LogLevel::CRITICAL], + \E_COMPILE_ERROR => [null, LogLevel::CRITICAL], + \E_PARSE => [null, LogLevel::CRITICAL], + \E_ERROR => [null, LogLevel::CRITICAL], + \E_CORE_ERROR => [null, LogLevel::CRITICAL], ]; private $thrownErrors = 0x1FFF; // E_ALL - E_DEPRECATED - E_USER_DEPRECATED @@ -150,7 +150,7 @@ public static function register(self $handler = null, bool $replace = true): sel $handler->setExceptionHandler($prev ?? [$handler, 'renderException']); } - $handler->throwAt(E_ALL & $handler->thrownErrors, true); + $handler->throwAt(\E_ALL & $handler->thrownErrors, true); return $handler; } @@ -166,7 +166,7 @@ public static function call(callable $function, ...$arguments) { set_error_handler(static function (int $type, string $message, string $file, int $line) { if (__FILE__ === $file) { - $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3); + $trace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 3); $file = $trace[2]['file'] ?? $file; $line = $trace[2]['line'] ?? $line; } @@ -205,7 +205,7 @@ public function __construct(BufferingLogger $bootstrappingLogger = null, bool $d * @param array|int $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants * @param bool $replace Whether to replace or not any existing logger */ - public function setDefaultLogger(LoggerInterface $logger, $levels = E_ALL, bool $replace = false): void + public function setDefaultLogger(LoggerInterface $logger, $levels = \E_ALL, bool $replace = false): void { $loggers = []; @@ -217,7 +217,7 @@ public function setDefaultLogger(LoggerInterface $logger, $levels = E_ALL, bool } } else { if (null === $levels) { - $levels = E_ALL; + $levels = \E_ALL; } foreach ($this->loggers as $type => $log) { if (($type & $levels) && (empty($log[0]) || $replace || $log[0] === $this->bootstrappingLogger)) { @@ -309,7 +309,7 @@ public function setExceptionHandler(?callable $handler): ?callable public function throwAt(int $levels, bool $replace = false): int { $prev = $this->thrownErrors; - $this->thrownErrors = ($levels | E_RECOVERABLE_ERROR | E_USER_ERROR) & ~E_USER_DEPRECATED & ~E_DEPRECATED; + $this->thrownErrors = ($levels | \E_RECOVERABLE_ERROR | \E_USER_ERROR) & ~\E_USER_DEPRECATED & ~\E_DEPRECATED; if (!$replace) { $this->thrownErrors |= $prev; } @@ -406,28 +406,27 @@ private function reRegister(int $prev): void */ public function handleError(int $type, string $message, string $file, int $line): bool { - if (\PHP_VERSION_ID >= 70300 && E_WARNING === $type && '"' === $message[0] && false !== strpos($message, '" targeting switch is equivalent to "break')) { - $type = E_DEPRECATED; + if (\PHP_VERSION_ID >= 70300 && \E_WARNING === $type && '"' === $message[0] && false !== strpos($message, '" targeting switch is equivalent to "break')) { + $type = \E_DEPRECATED; } // Level is the current error reporting level to manage silent error. $level = error_reporting(); $silenced = 0 === ($level & $type); // Strong errors are not authorized to be silenced. - $level |= E_RECOVERABLE_ERROR | E_USER_ERROR | E_DEPRECATED | E_USER_DEPRECATED; + $level |= \E_RECOVERABLE_ERROR | \E_USER_ERROR | \E_DEPRECATED | \E_USER_DEPRECATED; $log = $this->loggedErrors & $type; $throw = $this->thrownErrors & $type & $level; $type &= $level | $this->screamedErrors; // Never throw on warnings triggered by assert() - if (E_WARNING === $type && 'a' === $message[0] && 0 === strncmp($message, 'assert(): ', 10)) { + if (\E_WARNING === $type && 'a' === $message[0] && 0 === strncmp($message, 'assert(): ', 10)) { $throw = 0; } if (!$type || (!$log && !$throw)) { - return !$silenced && $type && $log; + return false; } - $scope = $this->scopedErrors & $type; if (false !== strpos($message, "@anonymous\0")) { $logMessage = $this->parseAnonymousClass($message); @@ -440,7 +439,7 @@ public function handleError(int $type, string $message, string $file, int $line) self::$toStringException = null; } elseif (!$throw && !($type & $level)) { if (!isset(self::$silencedErrorCache[$id = $file.':'.$line])) { - $lightTrace = $this->tracedErrors & $type ? $this->cleanTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5), $type, $file, $line, false) : []; + $lightTrace = $this->tracedErrors & $type ? $this->cleanTrace(debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 5), $type, $file, $line, false) : []; $errorAsException = new SilencedErrorContext($type, $file, $line, isset($lightTrace[1]) ? [$lightTrace[0]] : $lightTrace); } elseif (isset(self::$silencedErrorCache[$id][$message])) { $lightTrace = null; @@ -475,7 +474,7 @@ public function handleError(int $type, string $message, string $file, int $line) } if ($throw) { - if (\PHP_VERSION_ID < 70400 && E_USER_ERROR & $type) { + if (\PHP_VERSION_ID < 70400 && \E_USER_ERROR & $type) { for ($i = 1; isset($backtrace[$i]); ++$i) { if (isset($backtrace[$i]['function'], $backtrace[$i]['type'], $backtrace[$i - 1]['function']) && '__toString' === $backtrace[$i]['function'] @@ -663,7 +662,7 @@ public static function handleFatalError(array $error = null): void $error = error_get_last(); } - if ($error && $error['type'] &= E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR) { + if ($error && $error['type'] &= \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR) { // Let's not throw anymore but keep logging $handler->throwAt(0, true); $trace = isset($error['backtrace']) ? $error['backtrace'] : null; @@ -742,7 +741,7 @@ private function cleanTrace(array $backtrace, int $type, string &$file, int &$li break; } } - if (E_USER_DEPRECATED === $type) { + if (\E_USER_DEPRECATED === $type) { for ($i = 0; isset($lightTrace[$i]); ++$i) { if (!isset($lightTrace[$i]['file'], $lightTrace[$i]['line'], $lightTrace[$i]['function'])) { continue; diff --git a/src/Symfony/Component/ErrorHandler/ErrorRenderer/HtmlErrorRenderer.php b/src/Symfony/Component/ErrorHandler/ErrorRenderer/HtmlErrorRenderer.php index 11f3a606f126..08c7dfa5af9b 100644 --- a/src/Symfony/Component/ErrorHandler/ErrorRenderer/HtmlErrorRenderer.php +++ b/src/Symfony/Component/ErrorHandler/ErrorRenderer/HtmlErrorRenderer.php @@ -186,7 +186,7 @@ private function formatArgsAsText(array $args) private function escape(string $string): string { - return htmlspecialchars($string, ENT_COMPAT | ENT_SUBSTITUTE, $this->charset); + return htmlspecialchars($string, \ENT_COMPAT | \ENT_SUBSTITUTE, $this->charset); } private function abbrClass(string $class): string @@ -345,7 +345,7 @@ private function addElementToGhost(): string private function include(string $name, array $context = []): string { - extract($context, EXTR_SKIP); + extract($context, \EXTR_SKIP); ob_start(); include __DIR__.'/../Resources/'.$name; diff --git a/src/Symfony/Component/ErrorHandler/Resources/views/logs.html.php b/src/Symfony/Component/ErrorHandler/Resources/views/logs.html.php index c866e06978f7..f886200fb3b5 100644 --- a/src/Symfony/Component/ErrorHandler/Resources/views/logs.html.php +++ b/src/Symfony/Component/ErrorHandler/Resources/views/logs.html.php @@ -20,7 +20,7 @@ if (($exception = $log['context']['exception'] ?? null) instanceof \ErrorException) { $severity = $exception->getSeverity(); } - $status = E_DEPRECATED === $severity || E_USER_DEPRECATED === $severity ? 'warning' : 'normal'; + $status = \E_DEPRECATED === $severity || \E_USER_DEPRECATED === $severity ? 'warning' : 'normal'; } ?> data-filter-channel="escape($log['channel']); ?>"> @@ -35,7 +35,7 @@ formatLogMessage($log['message'], $log['context']); ?> -
+
escape(json_encode($log['context'], \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES)); ?>
diff --git a/src/Symfony/Component/ErrorHandler/Resources/views/trace.html.php b/src/Symfony/Component/ErrorHandler/Resources/views/trace.html.php index 153f7d6f8e65..6b4261f3f4e1 100644 --- a/src/Symfony/Component/ErrorHandler/Resources/views/trace.html.php +++ b/src/Symfony/Component/ErrorHandler/Resources/views/trace.html.php @@ -13,7 +13,7 @@ $lineNumber = $trace['line'] ?: 1; $fileLink = $this->getFileLink($trace['file'], $lineNumber); $filePath = strtr(strip_tags($this->formatFile($trace['file'], $lineNumber)), [' at line '.$lineNumber => '']); - $filePathParts = explode(DIRECTORY_SEPARATOR, $filePath); + $filePathParts = explode(\DIRECTORY_SEPARATOR, $filePath); ?> in diff --git a/src/Symfony/Component/ErrorHandler/Tests/ErrorEnhancer/ClassNotFoundErrorEnhancerTest.php b/src/Symfony/Component/ErrorHandler/Tests/ErrorEnhancer/ClassNotFoundErrorEnhancerTest.php index 1e09afbb9f32..1ca2f162b9eb 100644 --- a/src/Symfony/Component/ErrorHandler/Tests/ErrorEnhancer/ClassNotFoundErrorEnhancerTest.php +++ b/src/Symfony/Component/ErrorHandler/Tests/ErrorEnhancer/ClassNotFoundErrorEnhancerTest.php @@ -81,14 +81,30 @@ public function provideClassNotFoundData() $debugClassLoader = new DebugClassLoader([$autoloader, 'loadClass']); return [ + [ + 'Class "WhizBangFactory" not found', + "Attempted to load class \"WhizBangFactory\" from the global namespace.\nDid you forget a \"use\" statement?", + ], [ 'Class \'WhizBangFactory\' not found', "Attempted to load class \"WhizBangFactory\" from the global namespace.\nDid you forget a \"use\" statement?", ], + [ + 'Class "Foo\\Bar\\WhizBangFactory" not found', + "Attempted to load class \"WhizBangFactory\" from namespace \"Foo\\Bar\".\nDid you forget a \"use\" statement for another namespace?", + ], [ 'Class \'Foo\\Bar\\WhizBangFactory\' not found', "Attempted to load class \"WhizBangFactory\" from namespace \"Foo\\Bar\".\nDid you forget a \"use\" statement for another namespace?", ], + [ + 'Interface "Foo\\Bar\\WhizBangInterface" not found', + "Attempted to load interface \"WhizBangInterface\" from namespace \"Foo\\Bar\".\nDid you forget a \"use\" statement for another namespace?", + ], + [ + 'Trait "Foo\\Bar\\WhizBangTrait" not found', + "Attempted to load trait \"WhizBangTrait\" from namespace \"Foo\\Bar\".\nDid you forget a \"use\" statement for another namespace?", + ], [ 'Class \'UndefinedFunctionError\' not found', "Attempted to load class \"UndefinedFunctionError\" from the global namespace.\nDid you forget a \"use\" statement for \"Symfony\Component\ErrorHandler\Error\UndefinedFunctionError\"?", @@ -125,7 +141,7 @@ function ($className) { /* do nothing here */ }, public function testEnhanceWithFatalError() { $error = (new ClassNotFoundErrorEnhancer())->enhance(new FatalError('foo', 0, [ - 'type' => E_ERROR, + 'type' => \E_ERROR, 'message' => "Class 'FooBarCcc' not found", 'file' => $expectedFile = realpath(__FILE__), 'line' => $expectedLine = __LINE__, diff --git a/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php b/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php index b31b728e9495..4239be1ed3d2 100644 --- a/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php +++ b/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php @@ -65,12 +65,12 @@ public function testErrorGetLast() $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock(); $handler = ErrorHandler::register(); $handler->setDefaultLogger($logger); - $handler->screamAt(E_ALL); + $handler->screamAt(\E_ALL); try { - @trigger_error('Hello', E_USER_WARNING); + @trigger_error('Hello', \E_USER_WARNING); $expected = [ - 'type' => E_USER_WARNING, + 'type' => \E_USER_WARNING, 'message' => 'Hello', 'file' => __FILE__, 'line' => __LINE__ - 5, @@ -92,10 +92,10 @@ public function testNotice() } catch (\ErrorException $exception) { // if an exception is thrown, the test passed if (\PHP_VERSION_ID < 80000) { - $this->assertEquals(E_NOTICE, $exception->getSeverity()); + $this->assertEquals(\E_NOTICE, $exception->getSeverity()); $this->assertMatchesRegularExpression('/^Notice: Undefined variable: (foo|bar)/', $exception->getMessage()); } else { - $this->assertEquals(E_WARNING, $exception->getSeverity()); + $this->assertEquals(\E_WARNING, $exception->getSeverity()); $this->assertMatchesRegularExpression('/^Warning: Undefined variable \$(foo|bar)/', $exception->getMessage()); } $this->assertEquals(__FILE__, $exception->getFile()); @@ -155,10 +155,10 @@ public function testCallErrorExceptionInfo() } catch (\ErrorException $e) { $trace = $e->getTrace(); if (\PHP_VERSION_ID < 80000) { - $this->assertEquals(E_NOTICE, $e->getSeverity()); + $this->assertEquals(\E_NOTICE, $e->getSeverity()); $this->assertSame('Undefined variable: foo', $e->getMessage()); } else { - $this->assertEquals(E_WARNING, $e->getSeverity()); + $this->assertEquals(\E_WARNING, $e->getSeverity()); $this->assertSame('Undefined variable $foo', $e->getMessage()); } $this->assertSame(__FILE__, $e->getFile()); @@ -184,7 +184,7 @@ public function testConstruct() try { $handler = ErrorHandler::register(); $handler->throwAt(3, true); - $this->assertEquals(3 | E_RECOVERABLE_ERROR | E_USER_ERROR, $handler->throwAt(0)); + $this->assertEquals(3 | \E_RECOVERABLE_ERROR | \E_USER_ERROR, $handler->throwAt(0)); } finally { restore_error_handler(); restore_exception_handler(); @@ -197,25 +197,25 @@ public function testDefaultLogger() $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock(); $handler = ErrorHandler::register(); - $handler->setDefaultLogger($logger, E_NOTICE); - $handler->setDefaultLogger($logger, [E_USER_NOTICE => LogLevel::CRITICAL]); + $handler->setDefaultLogger($logger, \E_NOTICE); + $handler->setDefaultLogger($logger, [\E_USER_NOTICE => LogLevel::CRITICAL]); $loggers = [ - E_DEPRECATED => [null, LogLevel::INFO], - E_USER_DEPRECATED => [null, LogLevel::INFO], - E_NOTICE => [$logger, LogLevel::WARNING], - E_USER_NOTICE => [$logger, LogLevel::CRITICAL], - E_STRICT => [null, LogLevel::WARNING], - E_WARNING => [null, LogLevel::WARNING], - E_USER_WARNING => [null, LogLevel::WARNING], - E_COMPILE_WARNING => [null, LogLevel::WARNING], - E_CORE_WARNING => [null, LogLevel::WARNING], - E_USER_ERROR => [null, LogLevel::CRITICAL], - E_RECOVERABLE_ERROR => [null, LogLevel::CRITICAL], - E_COMPILE_ERROR => [null, LogLevel::CRITICAL], - E_PARSE => [null, LogLevel::CRITICAL], - E_ERROR => [null, LogLevel::CRITICAL], - E_CORE_ERROR => [null, LogLevel::CRITICAL], + \E_DEPRECATED => [null, LogLevel::INFO], + \E_USER_DEPRECATED => [null, LogLevel::INFO], + \E_NOTICE => [$logger, LogLevel::WARNING], + \E_USER_NOTICE => [$logger, LogLevel::CRITICAL], + \E_STRICT => [null, LogLevel::WARNING], + \E_WARNING => [null, LogLevel::WARNING], + \E_USER_WARNING => [null, LogLevel::WARNING], + \E_COMPILE_WARNING => [null, LogLevel::WARNING], + \E_CORE_WARNING => [null, LogLevel::WARNING], + \E_USER_ERROR => [null, LogLevel::CRITICAL], + \E_RECOVERABLE_ERROR => [null, LogLevel::CRITICAL], + \E_COMPILE_ERROR => [null, LogLevel::CRITICAL], + \E_PARSE => [null, LogLevel::CRITICAL], + \E_ERROR => [null, LogLevel::CRITICAL], + \E_CORE_ERROR => [null, LogLevel::CRITICAL], ]; $this->assertSame($loggers, $handler->setLoggers([])); } finally { @@ -256,15 +256,15 @@ public function testHandleError() restore_exception_handler(); $handler = ErrorHandler::register(); - $handler->throwAt(E_USER_DEPRECATED, true); - $this->assertFalse($handler->handleError(E_USER_DEPRECATED, 'foo', 'foo.php', 12, [])); + $handler->throwAt(\E_USER_DEPRECATED, true); + $this->assertFalse($handler->handleError(\E_USER_DEPRECATED, 'foo', 'foo.php', 12, [])); restore_error_handler(); restore_exception_handler(); $handler = ErrorHandler::register(); - $handler->throwAt(E_DEPRECATED, true); - $this->assertFalse($handler->handleError(E_DEPRECATED, 'foo', 'foo.php', 12, [])); + $handler->throwAt(\E_DEPRECATED, true); + $this->assertFalse($handler->handleError(\E_DEPRECATED, 'foo', 'foo.php', 12, [])); restore_error_handler(); restore_exception_handler(); @@ -278,7 +278,7 @@ public function testHandleError() $exception = $context['exception']; $this->assertInstanceOf(\ErrorException::class, $exception); $this->assertSame('User Deprecated: foo', $exception->getMessage()); - $this->assertSame(E_USER_DEPRECATED, $exception->getSeverity()); + $this->assertSame(\E_USER_DEPRECATED, $exception->getSeverity()); }; $logger @@ -288,8 +288,8 @@ public function testHandleError() ; $handler = ErrorHandler::register(); - $handler->setDefaultLogger($logger, E_USER_DEPRECATED); - $this->assertTrue($handler->handleError(E_USER_DEPRECATED, 'foo', 'foo.php', 12, [])); + $handler->setDefaultLogger($logger, \E_USER_DEPRECATED); + $this->assertTrue($handler->handleError(\E_USER_DEPRECATED, 'foo', 'foo.php', 12, [])); restore_error_handler(); restore_exception_handler(); @@ -303,10 +303,10 @@ public function testHandleError() if (\PHP_VERSION_ID < 80000) { $this->assertEquals('Notice: Undefined variable: undefVar', $message); - $this->assertSame(E_NOTICE, $exception->getSeverity()); + $this->assertSame(\E_NOTICE, $exception->getSeverity()); } else { $this->assertEquals('Warning: Undefined variable $undefVar', $message); - $this->assertSame(E_WARNING, $exception->getSeverity()); + $this->assertSame(\E_WARNING, $exception->getSeverity()); } $this->assertInstanceOf(SilencedErrorContext::class, $exception); @@ -324,11 +324,11 @@ public function testHandleError() $handler = ErrorHandler::register(); if (\PHP_VERSION_ID < 80000) { - $handler->setDefaultLogger($logger, E_NOTICE); - $handler->screamAt(E_NOTICE); + $handler->setDefaultLogger($logger, \E_NOTICE); + $handler->screamAt(\E_NOTICE); } else { - $handler->setDefaultLogger($logger, E_WARNING); - $handler->screamAt(E_WARNING); + $handler->setDefaultLogger($logger, \E_WARNING); + $handler->screamAt(\E_WARNING); } unset($undefVar); $line = __LINE__ + 1; @@ -404,7 +404,7 @@ public function testHandleDeprecation() $handler = new ErrorHandler(); $handler->setDefaultLogger($logger); - @$handler->handleError(E_USER_DEPRECATED, 'Foo deprecation', __FILE__, __LINE__, []); + @$handler->handleError(\E_USER_DEPRECATED, 'Foo deprecation', __FILE__, __LINE__, []); } /** @@ -428,7 +428,7 @@ public function testHandleException(string $expectedMessage, \Throwable $excepti ->willReturnCallback($logArgCheck) ; - $handler->setDefaultLogger($logger, E_ERROR); + $handler->setDefaultLogger($logger, \E_ERROR); $handler->setExceptionHandler(null); try { @@ -468,26 +468,26 @@ public function testBootstrappingLogger() $handler = new ErrorHandler($bootLogger); $loggers = [ - E_DEPRECATED => [$bootLogger, LogLevel::INFO], - E_USER_DEPRECATED => [$bootLogger, LogLevel::INFO], - E_NOTICE => [$bootLogger, LogLevel::WARNING], - E_USER_NOTICE => [$bootLogger, LogLevel::WARNING], - E_STRICT => [$bootLogger, LogLevel::WARNING], - E_WARNING => [$bootLogger, LogLevel::WARNING], - E_USER_WARNING => [$bootLogger, LogLevel::WARNING], - E_COMPILE_WARNING => [$bootLogger, LogLevel::WARNING], - E_CORE_WARNING => [$bootLogger, LogLevel::WARNING], - E_USER_ERROR => [$bootLogger, LogLevel::CRITICAL], - E_RECOVERABLE_ERROR => [$bootLogger, LogLevel::CRITICAL], - E_COMPILE_ERROR => [$bootLogger, LogLevel::CRITICAL], - E_PARSE => [$bootLogger, LogLevel::CRITICAL], - E_ERROR => [$bootLogger, LogLevel::CRITICAL], - E_CORE_ERROR => [$bootLogger, LogLevel::CRITICAL], + \E_DEPRECATED => [$bootLogger, LogLevel::INFO], + \E_USER_DEPRECATED => [$bootLogger, LogLevel::INFO], + \E_NOTICE => [$bootLogger, LogLevel::WARNING], + \E_USER_NOTICE => [$bootLogger, LogLevel::WARNING], + \E_STRICT => [$bootLogger, LogLevel::WARNING], + \E_WARNING => [$bootLogger, LogLevel::WARNING], + \E_USER_WARNING => [$bootLogger, LogLevel::WARNING], + \E_COMPILE_WARNING => [$bootLogger, LogLevel::WARNING], + \E_CORE_WARNING => [$bootLogger, LogLevel::WARNING], + \E_USER_ERROR => [$bootLogger, LogLevel::CRITICAL], + \E_RECOVERABLE_ERROR => [$bootLogger, LogLevel::CRITICAL], + \E_COMPILE_ERROR => [$bootLogger, LogLevel::CRITICAL], + \E_PARSE => [$bootLogger, LogLevel::CRITICAL], + \E_ERROR => [$bootLogger, LogLevel::CRITICAL], + \E_CORE_ERROR => [$bootLogger, LogLevel::CRITICAL], ]; $this->assertSame($loggers, $handler->setLoggers([])); - $handler->handleError(E_DEPRECATED, 'Foo message', __FILE__, 123, []); + $handler->handleError(\E_DEPRECATED, 'Foo message', __FILE__, 123, []); $logs = $bootLogger->cleanLogs(); @@ -501,7 +501,7 @@ public function testBootstrappingLogger() $this->assertSame('Deprecated: Foo message', $exception->getMessage()); $this->assertSame(__FILE__, $exception->getFile()); $this->assertSame(123, $exception->getLine()); - $this->assertSame(E_DEPRECATED, $exception->getSeverity()); + $this->assertSame(\E_DEPRECATED, $exception->getSeverity()); $bootLogger->log(LogLevel::WARNING, 'Foo message', ['exception' => $exception]); @@ -510,7 +510,7 @@ public function testBootstrappingLogger() ->method('log') ->with(LogLevel::WARNING, 'Foo message', ['exception' => $exception]); - $handler->setLoggers([E_DEPRECATED => [$mockLogger, LogLevel::WARNING]]); + $handler->setLoggers([\E_DEPRECATED => [$mockLogger, LogLevel::WARNING]]); } public function testSettingLoggerWhenExceptionIsBuffered() @@ -539,7 +539,7 @@ public function testHandleFatalError() $handler = ErrorHandler::register(); $error = [ - 'type' => E_PARSE, + 'type' => \E_PARSE, 'message' => 'foo', 'file' => 'bar', 'line' => 123, @@ -557,7 +557,7 @@ public function testHandleFatalError() ->willReturnCallback($logArgCheck) ; - $handler->setDefaultLogger($logger, E_PARSE); + $handler->setDefaultLogger($logger, \E_PARSE); $handler->setExceptionHandler(null); $handler->handleFatalError($error); @@ -625,8 +625,8 @@ public function testErrorHandlerWhenLogging(bool $previousHandlerWasDefined, boo $handler = ErrorHandlerThatUsesThePreviousOne::register(); } - @trigger_error('foo', E_USER_DEPRECATED); - @trigger_error('bar', E_USER_DEPRECATED); + @trigger_error('foo', \E_USER_DEPRECATED); + @trigger_error('bar', \E_USER_DEPRECATED); $this->assertSame([$handler, 'handleError'], set_error_handler('var_dump')); diff --git a/src/Symfony/Component/ErrorHandler/Tests/Exception/FlattenExceptionTest.php b/src/Symfony/Component/ErrorHandler/Tests/Exception/FlattenExceptionTest.php index 35b33d2800ac..30c5234669ad 100644 --- a/src/Symfony/Component/ErrorHandler/Tests/Exception/FlattenExceptionTest.php +++ b/src/Symfony/Component/ErrorHandler/Tests/Exception/FlattenExceptionTest.php @@ -269,8 +269,8 @@ function () {}, 0.0, '0', '', - INF, - NAN, + \INF, + \NAN, ]); $flattened = FlattenException::createFromThrowable($exception); @@ -301,7 +301,7 @@ function () {}, $this->assertSame(['float', 0.0], $array[$i++]); $this->assertSame(['string', '0'], $array[$i++]); $this->assertSame(['string', ''], $array[$i++]); - $this->assertSame(['float', INF], $array[$i++]); + $this->assertSame(['float', \INF], $array[$i++]); // assertEquals() does not like NAN values. $this->assertEquals('float', $array[$i][0]); diff --git a/src/Symfony/Component/ErrorHandler/ThrowableUtils.php b/src/Symfony/Component/ErrorHandler/ThrowableUtils.php index 5cbe87f49343..d6efcbefa0cc 100644 --- a/src/Symfony/Component/ErrorHandler/ThrowableUtils.php +++ b/src/Symfony/Component/ErrorHandler/ThrowableUtils.php @@ -23,13 +23,13 @@ public static function getSeverity(\Throwable $throwable): int } if ($throwable instanceof \ParseError) { - return E_PARSE; + return \E_PARSE; } if ($throwable instanceof \TypeError) { - return E_RECOVERABLE_ERROR; + return \E_RECOVERABLE_ERROR; } - return E_ERROR; + return \E_ERROR; } } diff --git a/src/Symfony/Component/EventDispatcher/Tests/Debug/TraceableEventDispatcherTest.php b/src/Symfony/Component/EventDispatcher/Tests/Debug/TraceableEventDispatcherTest.php index 99627a71a9db..bcb14d34a6e8 100644 --- a/src/Symfony/Component/EventDispatcher/Tests/Debug/TraceableEventDispatcherTest.php +++ b/src/Symfony/Component/EventDispatcher/Tests/Debug/TraceableEventDispatcherTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\EventDispatcher\Tests\Debug; use PHPUnit\Framework\TestCase; +use Symfony\Component\ErrorHandler\BufferingLogger; use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -192,41 +193,57 @@ public function testItDoesNotReturnHandledEvents() public function testLogger() { - $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock(); + $logger = new BufferingLogger(); $dispatcher = new EventDispatcher(); $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger); $tdispatcher->addListener('foo', $listener1 = function () {}); $tdispatcher->addListener('foo', $listener2 = function () {}); - $logger->expects($this->exactly(2)) - ->method('debug') - ->withConsecutive( - ['Notified event "{event}" to listener "{listener}".', ['event' => 'foo', 'listener' => 'closure']], - ['Notified event "{event}" to listener "{listener}".', ['event' => 'foo', 'listener' => 'closure']] - ); - $tdispatcher->dispatch(new Event(), 'foo'); + + $this->assertSame([ + [ + 'debug', + 'Notified event "{event}" to listener "{listener}".', + ['event' => 'foo', 'listener' => 'closure'], + ], + [ + 'debug', + 'Notified event "{event}" to listener "{listener}".', + ['event' => 'foo', 'listener' => 'closure'], + ], + ], $logger->cleanLogs()); } public function testLoggerWithStoppedEvent() { - $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock(); + $logger = new BufferingLogger(); $dispatcher = new EventDispatcher(); $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger); $tdispatcher->addListener('foo', $listener1 = function (Event $event) { $event->stopPropagation(); }); $tdispatcher->addListener('foo', $listener2 = function () {}); - $logger->expects($this->exactly(3)) - ->method('debug') - ->withConsecutive( - ['Notified event "{event}" to listener "{listener}".', ['event' => 'foo', 'listener' => 'closure']], - ['Listener "{listener}" stopped propagation of the event "{event}".', ['event' => 'foo', 'listener' => 'closure']], - ['Listener "{listener}" was not called for event "{event}".', ['event' => 'foo', 'listener' => 'closure']] - ); - $tdispatcher->dispatch(new Event(), 'foo'); + + $this->assertSame([ + [ + 'debug', + 'Notified event "{event}" to listener "{listener}".', + ['event' => 'foo', 'listener' => 'closure'], + ], + [ + 'debug', + 'Listener "{listener}" stopped propagation of the event "{event}".', + ['event' => 'foo', 'listener' => 'closure'], + ], + [ + 'debug', + 'Listener "{listener}" was not called for event "{event}".', + ['event' => 'foo', 'listener' => 'closure'], + ], + ], $logger->cleanLogs()); } public function testDispatchCallListeners() diff --git a/src/Symfony/Component/EventDispatcher/composer.json b/src/Symfony/Component/EventDispatcher/composer.json index a67f66a42aa7..7fb244fa6af6 100644 --- a/src/Symfony/Component/EventDispatcher/composer.json +++ b/src/Symfony/Component/EventDispatcher/composer.json @@ -25,6 +25,7 @@ "symfony/dependency-injection": "^4.4|^5.0", "symfony/expression-language": "^4.4|^5.0", "symfony/config": "^4.4|^5.0", + "symfony/error-handler": "^4.4|^5.0", "symfony/http-foundation": "^4.4|^5.0", "symfony/service-contracts": "^1.1|^2", "symfony/stopwatch": "^4.4|^5.0", diff --git a/src/Symfony/Component/ExpressionLanguage/Compiler.php b/src/Symfony/Component/ExpressionLanguage/Compiler.php index e040e8c4bf26..6fcdac445912 100644 --- a/src/Symfony/Component/ExpressionLanguage/Compiler.php +++ b/src/Symfony/Component/ExpressionLanguage/Compiler.php @@ -109,14 +109,14 @@ public function string(string $value) public function repr($value) { if (\is_int($value) || \is_float($value)) { - if (false !== $locale = setlocale(LC_NUMERIC, 0)) { - setlocale(LC_NUMERIC, 'C'); + if (false !== $locale = setlocale(\LC_NUMERIC, 0)) { + setlocale(\LC_NUMERIC, 'C'); } $this->raw($value); if (false !== $locale) { - setlocale(LC_NUMERIC, $locale); + setlocale(\LC_NUMERIC, $locale); } } elseif (null === $value) { $this->raw('null'); diff --git a/src/Symfony/Component/ExpressionLanguage/Lexer.php b/src/Symfony/Component/ExpressionLanguage/Lexer.php index b5648d2f67f5..5a3fb0a0efc1 100644 --- a/src/Symfony/Component/ExpressionLanguage/Lexer.php +++ b/src/Symfony/Component/ExpressionLanguage/Lexer.php @@ -43,7 +43,7 @@ public function tokenize(string $expression) if (preg_match('/[0-9]+(?:\.[0-9]+)?([Ee][\+\-][0-9]+)?/A', $expression, $match, 0, $cursor)) { // numbers $number = (float) $match[0]; // floats - if (preg_match('/^[0-9]+$/', $match[0]) && $number <= PHP_INT_MAX) { + if (preg_match('/^[0-9]+$/', $match[0]) && $number <= \PHP_INT_MAX) { $number = (int) $match[0]; // integers lower than the maximum } $tokens[] = new Token(Token::NUMBER_TYPE, $number, $cursor + 1); diff --git a/src/Symfony/Component/ExpressionLanguage/SyntaxError.php b/src/Symfony/Component/ExpressionLanguage/SyntaxError.php index b67fdd12e614..0bfd7e997772 100644 --- a/src/Symfony/Component/ExpressionLanguage/SyntaxError.php +++ b/src/Symfony/Component/ExpressionLanguage/SyntaxError.php @@ -22,7 +22,7 @@ public function __construct(string $message, int $cursor = 0, string $expression $message .= '.'; if (null !== $subject && null !== $proposals) { - $minScore = INF; + $minScore = \INF; foreach ($proposals as $proposal) { $distance = levenshtein($subject, $proposal); if ($distance < $minScore) { diff --git a/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php b/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php index ed8b6852a5db..bd044621fe16 100644 --- a/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php +++ b/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php @@ -66,7 +66,7 @@ public function testCachedParse() public function testConstantFunction() { $expressionLanguage = new ExpressionLanguage(); - $this->assertEquals(PHP_VERSION, $expressionLanguage->evaluate('constant("PHP_VERSION")')); + $this->assertEquals(\PHP_VERSION, $expressionLanguage->evaluate('constant("PHP_VERSION")')); $expressionLanguage = new ExpressionLanguage(); $this->assertEquals('\constant("PHP_VERSION")', $expressionLanguage->compile('constant("PHP_VERSION")')); diff --git a/src/Symfony/Component/Filesystem/Filesystem.php b/src/Symfony/Component/Filesystem/Filesystem.php index d2131c9b9dcd..eb14fee9e995 100644 --- a/src/Symfony/Component/Filesystem/Filesystem.php +++ b/src/Symfony/Component/Filesystem/Filesystem.php @@ -44,7 +44,7 @@ public function copy(string $originFile, string $targetFile, bool $overwriteNewe $this->mkdir(\dirname($targetFile)); $doCopy = true; - if (!$overwriteNewerFiles && null === parse_url($originFile, PHP_URL_HOST) && is_file($targetFile)) { + if (!$overwriteNewerFiles && null === parse_url($originFile, \PHP_URL_HOST) && is_file($targetFile)) { $doCopy = filemtime($originFile) > filemtime($targetFile); } @@ -114,7 +114,7 @@ public function mkdir($dirs, int $mode = 0777) */ public function exists($files) { - $maxPathLength = PHP_MAXPATHLEN - 2; + $maxPathLength = \PHP_MAXPATHLEN - 2; foreach ($this->toIterable($files) as $file) { if (\strlen($file) > $maxPathLength) { @@ -289,7 +289,7 @@ public function rename(string $origin, string $target, bool $overwrite = false) */ private function isReadable(string $filename): bool { - $maxPathLength = PHP_MAXPATHLEN - 2; + $maxPathLength = \PHP_MAXPATHLEN - 2; if (\strlen($filename) > $maxPathLength) { throw new IOException(sprintf('Could not check if file is readable because path length exceeds %d characters.', $maxPathLength), 0, null, $filename); @@ -574,7 +574,7 @@ public function isAbsolutePath(string $file) && ':' === $file[1] && strspn($file, '/\\', 2, 1) ) - || null !== parse_url($file, PHP_URL_SCHEME) + || null !== parse_url($file, \PHP_URL_SCHEME) ; } @@ -690,7 +690,7 @@ public function appendToFile(string $filename, $content) throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir); } - if (false === @file_put_contents($filename, $content, FILE_APPEND)) { + if (false === @file_put_contents($filename, $content, \FILE_APPEND)) { throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename); } } diff --git a/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php b/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php index c6e63fbc5676..dcd6a393a984 100644 --- a/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php +++ b/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php @@ -377,7 +377,7 @@ public function testFilesExistsFails() $this->markTestSkipped('Long file names are an issue on Windows'); } $basePath = $this->workspace.'\\directory\\'; - $maxPathLength = PHP_MAXPATHLEN - 2; + $maxPathLength = \PHP_MAXPATHLEN - 2; $oldPath = getcwd(); mkdir($basePath); diff --git a/src/Symfony/Component/Filesystem/Tests/FilesystemTestCase.php b/src/Symfony/Component/Filesystem/Tests/FilesystemTestCase.php index 396a3ab2e863..76cfb9f9ff8c 100644 --- a/src/Symfony/Component/Filesystem/Tests/FilesystemTestCase.php +++ b/src/Symfony/Component/Filesystem/Tests/FilesystemTestCase.php @@ -159,7 +159,7 @@ protected function markAsSkippedIfSymlinkIsMissing($relative = false) } // https://bugs.php.net/69473 - if ($relative && '\\' === \DIRECTORY_SEPARATOR && 1 === PHP_ZTS) { + if ($relative && '\\' === \DIRECTORY_SEPARATOR && 1 === \PHP_ZTS) { $this->markTestSkipped('symlink does not support relative paths on thread safe Windows PHP versions'); } } diff --git a/src/Symfony/Component/Finder/Finder.php b/src/Symfony/Component/Finder/Finder.php index e1bcea35d265..2b13a73ceb42 100644 --- a/src/Symfony/Component/Finder/Finder.php +++ b/src/Symfony/Component/Finder/Finder.php @@ -582,7 +582,7 @@ public function in($dirs) foreach ((array) $dirs as $dir) { if (is_dir($dir)) { $resolvedDirs[] = $this->normalizeDir($dir); - } elseif ($glob = glob($dir, (\defined('GLOB_BRACE') ? GLOB_BRACE : 0) | GLOB_ONLYDIR | GLOB_NOSORT)) { + } elseif ($glob = glob($dir, (\defined('GLOB_BRACE') ? \GLOB_BRACE : 0) | \GLOB_ONLYDIR | \GLOB_NOSORT)) { sort($glob); $resolvedDirs = array_merge($resolvedDirs, array_map([$this, 'normalizeDir'], $glob)); } else { @@ -700,7 +700,7 @@ private function searchInDirectory(string $dir): \Iterator } $minDepth = 0; - $maxDepth = PHP_INT_MAX; + $maxDepth = \PHP_INT_MAX; foreach ($this->depths as $comparator) { switch ($comparator->getOperator()) { @@ -735,7 +735,7 @@ private function searchInDirectory(string $dir): \Iterator $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST); - if ($minDepth > 0 || $maxDepth < PHP_INT_MAX) { + if ($minDepth > 0 || $maxDepth < \PHP_INT_MAX) { $iterator = new Iterator\DepthRangeFilterIterator($iterator, $minDepth, $maxDepth); } diff --git a/src/Symfony/Component/Finder/Iterator/DepthRangeFilterIterator.php b/src/Symfony/Component/Finder/Iterator/DepthRangeFilterIterator.php index 436a66d84b99..18e751d77b92 100644 --- a/src/Symfony/Component/Finder/Iterator/DepthRangeFilterIterator.php +++ b/src/Symfony/Component/Finder/Iterator/DepthRangeFilterIterator.php @@ -25,10 +25,10 @@ class DepthRangeFilterIterator extends \FilterIterator * @param int $minDepth The min depth * @param int $maxDepth The max depth */ - public function __construct(\RecursiveIteratorIterator $iterator, int $minDepth = 0, int $maxDepth = PHP_INT_MAX) + public function __construct(\RecursiveIteratorIterator $iterator, int $minDepth = 0, int $maxDepth = \PHP_INT_MAX) { $this->minDepth = $minDepth; - $iterator->setMaxDepth(PHP_INT_MAX === $maxDepth ? -1 : $maxDepth); + $iterator->setMaxDepth(\PHP_INT_MAX === $maxDepth ? -1 : $maxDepth); parent::__construct($iterator); } diff --git a/src/Symfony/Component/Finder/SplFileInfo.php b/src/Symfony/Component/Finder/SplFileInfo.php index 65d7423e0da3..62c9faa6e914 100644 --- a/src/Symfony/Component/Finder/SplFileInfo.php +++ b/src/Symfony/Component/Finder/SplFileInfo.php @@ -61,7 +61,7 @@ public function getFilenameWithoutExtension(): string { $filename = $this->getFilename(); - return pathinfo($filename, PATHINFO_FILENAME); + return pathinfo($filename, \PATHINFO_FILENAME); } /** diff --git a/src/Symfony/Component/Finder/Tests/Iterator/DepthRangeFilterIteratorTest.php b/src/Symfony/Component/Finder/Tests/Iterator/DepthRangeFilterIteratorTest.php index 7c2572d21047..150a9d819efb 100644 --- a/src/Symfony/Component/Finder/Tests/Iterator/DepthRangeFilterIteratorTest.php +++ b/src/Symfony/Component/Finder/Tests/Iterator/DepthRangeFilterIteratorTest.php @@ -97,8 +97,8 @@ public function getAcceptData() return [ [0, 0, $this->toAbsolute($lessThan1)], [0, 1, $this->toAbsolute($lessThanOrEqualTo1)], - [2, PHP_INT_MAX, []], - [1, PHP_INT_MAX, $this->toAbsolute($graterThanOrEqualTo1)], + [2, \PHP_INT_MAX, []], + [1, \PHP_INT_MAX, $this->toAbsolute($graterThanOrEqualTo1)], [1, 1, $this->toAbsolute($equalTo1)], ]; } diff --git a/src/Symfony/Component/Form/Command/DebugCommand.php b/src/Symfony/Component/Form/Command/DebugCommand.php index 160b30d77b0c..4150feaf8ce8 100644 --- a/src/Symfony/Component/Form/Command/DebugCommand.php +++ b/src/Symfony/Component/Form/Command/DebugCommand.php @@ -237,7 +237,7 @@ private function findAlternatives(string $name, array $collection): array $threshold = 1e3; $alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; }); - ksort($alternatives, SORT_NATURAL | SORT_FLAG_CASE); + ksort($alternatives, \SORT_NATURAL | \SORT_FLAG_CASE); return array_keys($alternatives); } diff --git a/src/Symfony/Component/Form/Console/Descriptor/JsonDescriptor.php b/src/Symfony/Component/Form/Console/Descriptor/JsonDescriptor.php index 20f827bed319..59a6fdc6e908 100644 --- a/src/Symfony/Component/Form/Console/Descriptor/JsonDescriptor.php +++ b/src/Symfony/Component/Form/Console/Descriptor/JsonDescriptor.php @@ -97,7 +97,7 @@ private function writeData(array $data, array $options) { $flags = isset($options['json_encoding']) ? $options['json_encoding'] : 0; - $this->output->write(json_encode($data, $flags | JSON_PRETTY_PRINT)."\n"); + $this->output->write(json_encode($data, $flags | \JSON_PRETTY_PRINT)."\n"); } private function sortOptions(array &$options) diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php index 85cba6a69151..6ed37e71a3e7 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php @@ -165,7 +165,7 @@ public function reverseTransform($value) throw new TransformationFailedException($formatter->getErrorMessage()); } - if ($result >= PHP_INT_MAX || $result <= -PHP_INT_MAX) { + if ($result >= \PHP_INT_MAX || $result <= -\PHP_INT_MAX) { throw new TransformationFailedException('I don\'t have a clear idea what infinity looks like.'); } @@ -237,7 +237,7 @@ private function round($number) { if (null !== $this->scale && null !== $this->roundingMode) { // shift number to maintain the correct scale during rounding - $roundingCoef = pow(10, $this->scale); + $roundingCoef = 10 ** $this->scale; // string representation to avoid rounding errors, similar to bcmul() $number = (string) ($number * $roundingCoef); @@ -255,13 +255,13 @@ private function round($number) $number = $number > 0 ? floor($number) : ceil($number); break; case \NumberFormatter::ROUND_HALFEVEN: - $number = round($number, 0, PHP_ROUND_HALF_EVEN); + $number = round($number, 0, \PHP_ROUND_HALF_EVEN); break; case \NumberFormatter::ROUND_HALFUP: - $number = round($number, 0, PHP_ROUND_HALF_UP); + $number = round($number, 0, \PHP_ROUND_HALF_UP); break; case \NumberFormatter::ROUND_HALFDOWN: - $number = round($number, 0, PHP_ROUND_HALF_DOWN); + $number = round($number, 0, \PHP_ROUND_HALF_DOWN); break; } diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index a08b14151764..fd3d57c81656 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -227,13 +227,13 @@ private function round($number) $number = $number > 0 ? floor($number) : ceil($number); break; case \NumberFormatter::ROUND_HALFEVEN: - $number = round($number, 0, PHP_ROUND_HALF_EVEN); + $number = round($number, 0, \PHP_ROUND_HALF_EVEN); break; case \NumberFormatter::ROUND_HALFUP: - $number = round($number, 0, PHP_ROUND_HALF_UP); + $number = round($number, 0, \PHP_ROUND_HALF_UP); break; case \NumberFormatter::ROUND_HALFDOWN: - $number = round($number, 0, PHP_ROUND_HALF_DOWN); + $number = round($number, 0, \PHP_ROUND_HALF_DOWN); break; } diff --git a/src/Symfony/Component/Form/Extension/Core/Type/BaseType.php b/src/Symfony/Component/Form/Extension/Core/Type/BaseType.php index ac371c61c56b..3b5a3a01b560 100644 --- a/src/Symfony/Component/Form/Extension/Core/Type/BaseType.php +++ b/src/Symfony/Component/Form/Extension/Core/Type/BaseType.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Extension\Core\Type; +use Symfony\Component\Form\AbstractRendererEngine; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormInterface; @@ -112,7 +113,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) // collection form have different types (dynamically), they should // be rendered differently. // https://github.com/symfony/symfony/issues/5038 - 'cache_key' => $uniqueBlockPrefix.'_'.$form->getConfig()->getType()->getBlockPrefix(), + AbstractRendererEngine::CACHE_KEY_VAR => $uniqueBlockPrefix.'_'.$form->getConfig()->getType()->getBlockPrefix(), ]); } diff --git a/src/Symfony/Component/Form/Extension/Core/Type/FileType.php b/src/Symfony/Component/Form/Extension/Core/Type/FileType.php index ce535394d993..57b37ca21c63 100644 --- a/src/Symfony/Component/Form/Extension/Core/Type/FileType.php +++ b/src/Symfony/Component/Form/Extension/Core/Type/FileType.php @@ -145,14 +145,14 @@ private function getFileUploadError(int $errorCode) { $messageParameters = []; - if (UPLOAD_ERR_INI_SIZE === $errorCode) { + if (\UPLOAD_ERR_INI_SIZE === $errorCode) { list($limitAsString, $suffix) = $this->factorizeSizes(0, self::getMaxFilesize()); $messageTemplate = 'The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.'; $messageParameters = [ '{{ limit }}' => $limitAsString, '{{ suffix }}' => $suffix, ]; - } elseif (UPLOAD_ERR_FORM_SIZE === $errorCode) { + } elseif (\UPLOAD_ERR_FORM_SIZE === $errorCode) { $messageTemplate = 'The file is too large.'; } else { $messageTemplate = 'The file could not be uploaded.'; @@ -177,7 +177,7 @@ private static function getMaxFilesize(): int $iniMax = strtolower(ini_get('upload_max_filesize')); if ('' === $iniMax) { - return PHP_INT_MAX; + return \PHP_INT_MAX; } $max = ltrim($iniMax, '+'); diff --git a/src/Symfony/Component/Form/Extension/Core/Type/TimeType.php b/src/Symfony/Component/Form/Extension/Core/Type/TimeType.php index b3d0d5ef653b..c79cbe65b9c9 100644 --- a/src/Symfony/Component/Form/Extension/Core/Type/TimeType.php +++ b/src/Symfony/Component/Form/Extension/Core/Type/TimeType.php @@ -126,7 +126,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) $hours = $minutes = []; foreach ($options['hours'] as $hour) { - $hours[str_pad($hour, 2, '0', STR_PAD_LEFT)] = $hour; + $hours[str_pad($hour, 2, '0', \STR_PAD_LEFT)] = $hour; } // Only pass a subset of the options to children @@ -136,7 +136,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) if ($options['with_minutes']) { foreach ($options['minutes'] as $minute) { - $minutes[str_pad($minute, 2, '0', STR_PAD_LEFT)] = $minute; + $minutes[str_pad($minute, 2, '0', \STR_PAD_LEFT)] = $minute; } $minuteOptions['choices'] = $minutes; @@ -148,7 +148,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) $seconds = []; foreach ($options['seconds'] as $second) { - $seconds[str_pad($second, 2, '0', STR_PAD_LEFT)] = $second; + $seconds[str_pad($second, 2, '0', \STR_PAD_LEFT)] = $second; } $secondOptions['choices'] = $seconds; diff --git a/src/Symfony/Component/Form/FormRenderer.php b/src/Symfony/Component/Form/FormRenderer.php index 2ac3b57ee558..ed63d9499cdf 100644 --- a/src/Symfony/Component/Form/FormRenderer.php +++ b/src/Symfony/Component/Form/FormRenderer.php @@ -291,9 +291,9 @@ public function humanize(string $text) public function encodeCurrency(Environment $environment, string $text, string $widget = ''): string { if ('UTF-8' === $charset = $environment->getCharset()) { - $text = htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); + $text = htmlspecialchars($text, \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8'); } else { - $text = htmlentities($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); + $text = htmlentities($text, \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8'); $text = iconv('UTF-8', $charset, $text); $widget = iconv('UTF-8', $charset, $widget); } diff --git a/src/Symfony/Component/Form/NativeRequestHandler.php b/src/Symfony/Component/Form/NativeRequestHandler.php index f7db42e0f727..2532256f2b8c 100644 --- a/src/Symfony/Component/Form/NativeRequestHandler.php +++ b/src/Symfony/Component/Form/NativeRequestHandler.php @@ -152,7 +152,7 @@ public function getUploadFileError($data) return null; } - if (UPLOAD_ERR_OK === $data['error']) { + if (\UPLOAD_ERR_OK === $data['error']) { return null; } @@ -238,7 +238,7 @@ private static function stripEmptyFiles($data) sort($keys); if (self::$fileKeys === $keys) { - if (UPLOAD_ERR_NO_FILE === $data['error']) { + if (\UPLOAD_ERR_NO_FILE === $data['error']) { return null; } diff --git a/src/Symfony/Component/Form/Tests/AbstractRequestHandlerTest.php b/src/Symfony/Component/Form/Tests/AbstractRequestHandlerTest.php index 61455a51330d..5e8facd4cf95 100644 --- a/src/Symfony/Component/Form/Tests/AbstractRequestHandlerTest.php +++ b/src/Symfony/Component/Form/Tests/AbstractRequestHandlerTest.php @@ -338,10 +338,10 @@ public function testAddFormErrorIfPostMaxSizeExceeded($contentLength, $iniMax, $ public function getPostMaxSizeFixtures() { return [ - [pow(1024, 3) + 1, '1G', true, ['{{ max }}' => '1G']], - [pow(1024, 3), '1G', false], - [pow(1024, 2) + 1, '1M', true, ['{{ max }}' => '1M']], - [pow(1024, 2), '1M', false], + [1024 ** 3 + 1, '1G', true, ['{{ max }}' => '1G']], + [1024 ** 3, '1G', false], + [1024 ** 2 + 1, '1M', true, ['{{ max }}' => '1M']], + [1024 ** 2, '1M', false], [1024 + 1, '1K', true, ['{{ max }}' => '1K']], [1024, '1K', false], [null, '1K', false], @@ -371,14 +371,14 @@ public function testFailedFileUploadIsTurnedIntoFormError($errorCode, $expectedE public function uploadFileErrorCodes() { return [ - 'no error' => [UPLOAD_ERR_OK, null], - 'upload_max_filesize ini directive' => [UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_INI_SIZE], - 'MAX_FILE_SIZE from form' => [UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_FORM_SIZE], - 'partially uploaded' => [UPLOAD_ERR_PARTIAL, UPLOAD_ERR_PARTIAL], - 'no file upload' => [UPLOAD_ERR_NO_FILE, UPLOAD_ERR_NO_FILE], - 'missing temporary directory' => [UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_NO_TMP_DIR], - 'write failure' => [UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_CANT_WRITE], - 'stopped by extension' => [UPLOAD_ERR_EXTENSION, UPLOAD_ERR_EXTENSION], + 'no error' => [\UPLOAD_ERR_OK, null], + 'upload_max_filesize ini directive' => [\UPLOAD_ERR_INI_SIZE, \UPLOAD_ERR_INI_SIZE], + 'MAX_FILE_SIZE from form' => [\UPLOAD_ERR_FORM_SIZE, \UPLOAD_ERR_FORM_SIZE], + 'partially uploaded' => [\UPLOAD_ERR_PARTIAL, \UPLOAD_ERR_PARTIAL], + 'no file upload' => [\UPLOAD_ERR_NO_FILE, \UPLOAD_ERR_NO_FILE], + 'missing temporary directory' => [\UPLOAD_ERR_NO_TMP_DIR, \UPLOAD_ERR_NO_TMP_DIR], + 'write failure' => [\UPLOAD_ERR_CANT_WRITE, \UPLOAD_ERR_CANT_WRITE], + 'stopped by extension' => [\UPLOAD_ERR_EXTENSION, \UPLOAD_ERR_EXTENSION], ]; } diff --git a/src/Symfony/Component/Form/Tests/CompoundFormTest.php b/src/Symfony/Component/Form/Tests/CompoundFormTest.php index 0a97f6408c3a..a5196a3b68f1 100644 --- a/src/Symfony/Component/Form/Tests/CompoundFormTest.php +++ b/src/Symfony/Component/Form/Tests/CompoundFormTest.php @@ -623,7 +623,7 @@ public function testSubmitPostOrPutRequest($method) $files = [ 'author' => [ - 'error' => ['image' => UPLOAD_ERR_OK], + 'error' => ['image' => \UPLOAD_ERR_OK], 'name' => ['image' => 'upload.png'], 'size' => ['image' => null], 'tmp_name' => ['image' => $path], @@ -646,7 +646,7 @@ public function testSubmitPostOrPutRequest($method) $form->handleRequest($request); - $file = new UploadedFile($path, 'upload.png', 'image/png', UPLOAD_ERR_OK); + $file = new UploadedFile($path, 'upload.png', 'image/png', \UPLOAD_ERR_OK); $this->assertEquals('Bernhard', $form['name']->getData()); $this->assertEquals($file, $form['image']->getData()); @@ -670,7 +670,7 @@ public function testSubmitPostOrPutRequestWithEmptyRootFormName($method) $files = [ 'image' => [ - 'error' => UPLOAD_ERR_OK, + 'error' => \UPLOAD_ERR_OK, 'name' => 'upload.png', 'size' => null, 'tmp_name' => $path, @@ -693,7 +693,7 @@ public function testSubmitPostOrPutRequestWithEmptyRootFormName($method) $form->handleRequest($request); - $file = new UploadedFile($path, 'upload.png', 'image/png', UPLOAD_ERR_OK); + $file = new UploadedFile($path, 'upload.png', 'image/png', \UPLOAD_ERR_OK); $this->assertEquals('Bernhard', $form['name']->getData()); $this->assertEquals($file, $form['image']->getData()); @@ -713,7 +713,7 @@ public function testSubmitPostOrPutRequestWithSingleChildForm($method) $files = [ 'image' => [ - 'error' => UPLOAD_ERR_OK, + 'error' => \UPLOAD_ERR_OK, 'name' => 'upload.png', 'size' => null, 'tmp_name' => $path, @@ -732,7 +732,7 @@ public function testSubmitPostOrPutRequestWithSingleChildForm($method) $form->handleRequest($request); - $file = new UploadedFile($path, 'upload.png', 'image/png', UPLOAD_ERR_OK); + $file = new UploadedFile($path, 'upload.png', 'image/png', \UPLOAD_ERR_OK); $this->assertEquals($file, $form->getData()); @@ -1117,7 +1117,7 @@ public function testFileUpload() $this->form->submit([ 'foo' => 'Foo', - 'bar' => new UploadedFile(__FILE__, 'upload.png', 'image/png', UPLOAD_ERR_OK), + 'bar' => new UploadedFile(__FILE__, 'upload.png', 'image/png', \UPLOAD_ERR_OK), ]); $this->assertSame('Submitted data was expected to be text or number, file upload given.', $this->form->get('bar')->getTransformationFailure()->getMessage()); diff --git a/src/Symfony/Component/Form/Tests/Console/Descriptor/AbstractDescriptorTest.php b/src/Symfony/Component/Form/Tests/Console/Descriptor/AbstractDescriptorTest.php index e535fe5c03d2..e5f5d1228b5d 100644 --- a/src/Symfony/Component/Form/Tests/Console/Descriptor/AbstractDescriptorTest.php +++ b/src/Symfony/Component/Form/Tests/Console/Descriptor/AbstractDescriptorTest.php @@ -35,9 +35,9 @@ public function testDescribeDefaults($object, array $options, $fixtureName) $expectedDescription = $this->getExpectedDescription($fixtureName); if ('json' === $this->getFormat()) { - $this->assertEquals(json_encode(json_decode($expectedDescription), JSON_PRETTY_PRINT), json_encode(json_decode($describedObject), JSON_PRETTY_PRINT)); + $this->assertEquals(json_encode(json_decode($expectedDescription), \JSON_PRETTY_PRINT), json_encode(json_decode($describedObject), \JSON_PRETTY_PRINT)); } else { - $this->assertEquals(trim($expectedDescription), trim(str_replace(PHP_EOL, "\n", $describedObject))); + $this->assertEquals(trim($expectedDescription), trim(str_replace(\PHP_EOL, "\n", $describedObject))); } } @@ -48,9 +48,9 @@ public function testDescribeResolvedFormType(ResolvedFormTypeInterface $type, ar $expectedDescription = $this->getExpectedDescription($fixtureName); if ('json' === $this->getFormat()) { - $this->assertEquals(json_encode(json_decode($expectedDescription), JSON_PRETTY_PRINT), json_encode(json_decode($describedObject), JSON_PRETTY_PRINT)); + $this->assertEquals(json_encode(json_decode($expectedDescription), \JSON_PRETTY_PRINT), json_encode(json_decode($describedObject), \JSON_PRETTY_PRINT)); } else { - $this->assertEquals(trim($expectedDescription), trim(str_replace(PHP_EOL, "\n", $describedObject))); + $this->assertEquals(trim($expectedDescription), trim(str_replace(\PHP_EOL, "\n", $describedObject))); } } @@ -61,9 +61,9 @@ public function testDescribeOption(OptionsResolver $optionsResolver, array $opti $expectedDescription = $this->getExpectedDescription($fixtureName); if ('json' === $this->getFormat()) { - $this->assertEquals(json_encode(json_decode($expectedDescription), JSON_PRETTY_PRINT), json_encode(json_decode($describedObject), JSON_PRETTY_PRINT)); + $this->assertEquals(json_encode(json_decode($expectedDescription), \JSON_PRETTY_PRINT), json_encode(json_decode($describedObject), \JSON_PRETTY_PRINT)); } else { - $this->assertStringMatchesFormat(trim($expectedDescription), trim(str_replace(PHP_EOL, "\n", $describedObject))); + $this->assertStringMatchesFormat(trim($expectedDescription), trim(str_replace(\PHP_EOL, "\n", $describedObject))); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php index c9821bfe7475..ae23428a43a3 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php @@ -335,7 +335,7 @@ public function testReverseTransformWrapsIntlErrorsWithErrorLevel() $this->markTestSkipped('intl extension is not loaded'); } - $this->iniSet('intl.error_level', E_WARNING); + $this->iniSet('intl.error_level', \E_WARNING); $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToLocalizedStringTransformer(); @@ -362,7 +362,7 @@ public function testReverseTransformWrapsIntlErrorsWithExceptionsAndErrorLevel() } $this->iniSet('intl.use_exceptions', 1); - $this->iniSet('intl.error_level', E_WARNING); + $this->iniSet('intl.error_level', \E_WARNING); $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToLocalizedStringTransformer(); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php index 69d9e8526767..cb94ca785d53 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php @@ -21,12 +21,12 @@ class MoneyToLocalizedStringTransformerTest extends TestCase protected function setUp(): void { - $this->previousLocale = setlocale(LC_ALL, '0'); + $this->previousLocale = setlocale(\LC_ALL, '0'); } protected function tearDown(): void { - setlocale(LC_ALL, $this->previousLocale); + setlocale(\LC_ALL, $this->previousLocale); } public function testTransform() @@ -106,7 +106,7 @@ public function testFloatToIntConversionMismatchOnTransform() public function testValidNumericValuesWithNonDotDecimalPointCharacter() { // calling setlocale() here is important as it changes the representation of floats when being cast to strings - setlocale(LC_ALL, 'de_AT.UTF-8'); + setlocale(\LC_ALL, 'de_AT.UTF-8'); $transformer = new MoneyToLocalizedStringTransformer(4, null, null, 100); IntlTestHelper::requireFullIntl($this, false); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php index 66e955a1dc4d..41b927d04ac0 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php @@ -622,7 +622,7 @@ public function testReverseTransformBigInt() { $transformer = new NumberToLocalizedStringTransformer(null, true); - $this->assertEquals(PHP_INT_MAX - 1, (int) $transformer->reverseTransform((string) (PHP_INT_MAX - 1))); + $this->assertEquals(\PHP_INT_MAX - 1, (int) $transformer->reverseTransform((string) (\PHP_INT_MAX - 1))); } public function testReverseTransformSmallInt() diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/StringToFloatTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/StringToFloatTransformerTest.php index d2c800be672b..b5a2008fa0b5 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/StringToFloatTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/StringToFloatTransformerTest.php @@ -16,18 +16,6 @@ class StringToFloatTransformerTest extends TestCase { - private $transformer; - - protected function setUp(): void - { - $this->transformer = new StringToFloatTransformer(); - } - - protected function tearDown(): void - { - $this->transformer = null; - } - public function provideTransformations(): array { return [ diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/DateTimeTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/DateTimeTypeTest.php index 4c047b67c2a2..306460a9d76f 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/DateTimeTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/DateTimeTypeTest.php @@ -520,6 +520,7 @@ public function testSingleTextWidgetWithCustomNonHtml5Format() 'widget' => 'single_text', 'date_format' => \IntlDateFormatter::SHORT, 'format' => null, + 'html5' => false, ]); $view = $form->createView(); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/FileTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/FileTypeTest.php index 0731942c8960..7c6e63935473 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/FileTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/FileTypeTest.php @@ -206,7 +206,7 @@ public function testFailedFileUploadIsTurnedIntoFormErrorUsingHttpFoundationRequ ->getForm(); $form->submit($this->createUploadedFile($requestHandler, __DIR__.'/../../../Fixtures/foo', 'foo', $errorCode)); - if (UPLOAD_ERR_OK === $errorCode) { + if (\UPLOAD_ERR_OK === $errorCode) { $this->assertTrue($form->isValid()); } else { $this->assertFalse($form->isValid()); @@ -231,7 +231,7 @@ public function testFailedFileUploadIsTurnedIntoFormErrorUsingNativeRequestHandl 'size' => 100, ]); - if (UPLOAD_ERR_OK === $errorCode) { + if (\UPLOAD_ERR_OK === $errorCode) { $this->assertTrue($form->isValid()); } else { $this->assertFalse($form->isValid()); @@ -256,7 +256,7 @@ public function testMultipleSubmittedFailedFileUploadsAreTurnedIntoFormErrorUsin $this->createUploadedFile($requestHandler, __DIR__.'/../../../Fixtures/foo', 'bar', $errorCode), ]); - if (UPLOAD_ERR_OK === $errorCode) { + if (\UPLOAD_ERR_OK === $errorCode) { $this->assertTrue($form->isValid()); } else { $this->assertFalse($form->isValid()); @@ -294,7 +294,7 @@ public function testMultipleSubmittedFailedFileUploadsAreTurnedIntoFormErrorUsin ], ]); - if (UPLOAD_ERR_OK === $errorCode) { + if (\UPLOAD_ERR_OK === $errorCode) { $this->assertTrue($form->isValid()); } else { $this->assertFalse($form->isValid()); @@ -307,14 +307,14 @@ public function testMultipleSubmittedFailedFileUploadsAreTurnedIntoFormErrorUsin public function uploadFileErrorCodes() { return [ - 'no error' => [UPLOAD_ERR_OK, null], - 'upload_max_filesize ini directive' => [UPLOAD_ERR_INI_SIZE, 'The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.'], - 'MAX_FILE_SIZE from form' => [UPLOAD_ERR_FORM_SIZE, 'The file is too large.'], - 'partially uploaded' => [UPLOAD_ERR_PARTIAL, 'The file could not be uploaded.'], - 'no file upload' => [UPLOAD_ERR_NO_FILE, 'The file could not be uploaded.'], - 'missing temporary directory' => [UPLOAD_ERR_NO_TMP_DIR, 'The file could not be uploaded.'], - 'write failure' => [UPLOAD_ERR_CANT_WRITE, 'The file could not be uploaded.'], - 'stopped by extension' => [UPLOAD_ERR_EXTENSION, 'The file could not be uploaded.'], + 'no error' => [\UPLOAD_ERR_OK, null], + 'upload_max_filesize ini directive' => [\UPLOAD_ERR_INI_SIZE, 'The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.'], + 'MAX_FILE_SIZE from form' => [\UPLOAD_ERR_FORM_SIZE, 'The file is too large.'], + 'partially uploaded' => [\UPLOAD_ERR_PARTIAL, 'The file could not be uploaded.'], + 'no file upload' => [\UPLOAD_ERR_NO_FILE, 'The file could not be uploaded.'], + 'missing temporary directory' => [\UPLOAD_ERR_NO_TMP_DIR, 'The file could not be uploaded.'], + 'write failure' => [\UPLOAD_ERR_CANT_WRITE, 'The file could not be uploaded.'], + 'stopped by extension' => [\UPLOAD_ERR_EXTENSION, 'The file could not be uploaded.'], ]; } diff --git a/src/Symfony/Component/Form/Tests/NativeRequestHandlerTest.php b/src/Symfony/Component/Form/Tests/NativeRequestHandlerTest.php index bff9852bbbd8..ad1ea18e4a1c 100644 --- a/src/Symfony/Component/Form/Tests/NativeRequestHandlerTest.php +++ b/src/Symfony/Component/Form/Tests/NativeRequestHandlerTest.php @@ -78,7 +78,7 @@ public function testConvertEmptyUploadedFilesToNull() 'name' => '', 'type' => '', 'tmp_name' => '', - 'error' => UPLOAD_ERR_NO_FILE, + 'error' => \UPLOAD_ERR_NO_FILE, 'size' => 0, ]]); @@ -105,7 +105,7 @@ public function testFixBuggyFilesArray() 'field' => 'owfdskjasdfsa', ], 'error' => [ - 'field' => UPLOAD_ERR_OK, + 'field' => \UPLOAD_ERR_OK, ], 'size' => [ 'field' => 100, @@ -119,7 +119,7 @@ public function testFixBuggyFilesArray() 'name' => 'upload.txt', 'type' => 'text/plain', 'tmp_name' => 'owfdskjasdfsa', - 'error' => UPLOAD_ERR_OK, + 'error' => \UPLOAD_ERR_OK, 'size' => 100, ], $fieldForm->getData()); } @@ -143,7 +143,7 @@ public function testFixBuggyNestedFilesArray() 'field' => ['subfield' => 'owfdskjasdfsa'], ], 'error' => [ - 'field' => ['subfield' => UPLOAD_ERR_OK], + 'field' => ['subfield' => \UPLOAD_ERR_OK], ], 'size' => [ 'field' => ['subfield' => 100], @@ -157,7 +157,7 @@ public function testFixBuggyNestedFilesArray() 'name' => 'upload.txt', 'type' => 'text/plain', 'tmp_name' => 'owfdskjasdfsa', - 'error' => UPLOAD_ERR_OK, + 'error' => \UPLOAD_ERR_OK, 'size' => 100, ], $subfieldForm->getData()); } @@ -258,7 +258,7 @@ protected function getUploadedFile($suffix = '') 'name' => 'upload'.$suffix.'.txt', 'type' => 'text/plain', 'tmp_name' => 'owfdskjasdfsa'.$suffix, - 'error' => UPLOAD_ERR_OK, + 'error' => \UPLOAD_ERR_OK, 'size' => 100, ]; } diff --git a/src/Symfony/Component/Form/composer.json b/src/Symfony/Component/Form/composer.json index 0c69794b4e71..03ba22716a02 100644 --- a/src/Symfony/Component/Form/composer.json +++ b/src/Symfony/Component/Form/composer.json @@ -29,7 +29,7 @@ }, "require-dev": { "doctrine/collections": "~1.0", - "symfony/validator": "^4.4|^5.0", + "symfony/validator": "^4.4.12|^5.1.6", "symfony/dependency-injection": "^4.4|^5.0", "symfony/expression-language": "^4.4|^5.0", "symfony/config": "^4.4|^5.0", diff --git a/src/Symfony/Component/HttpClient/CurlHttpClient.php b/src/Symfony/Component/HttpClient/CurlHttpClient.php index fc10683a5ff4..5174ad053a2e 100644 --- a/src/Symfony/Component/HttpClient/CurlHttpClient.php +++ b/src/Symfony/Component/HttpClient/CurlHttpClient.php @@ -75,13 +75,13 @@ public function __construct(array $defaultOptions = [], int $maxHostConnections // Don't enable HTTP/1.1 pipelining: it forces responses to be sent in order if (\defined('CURLPIPE_MULTIPLEX')) { - curl_multi_setopt($this->multi->handle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX); + curl_multi_setopt($this->multi->handle, \CURLMOPT_PIPELINING, \CURLPIPE_MULTIPLEX); } if (\defined('CURLMOPT_MAX_HOST_CONNECTIONS')) { - $maxHostConnections = curl_multi_setopt($this->multi->handle, CURLMOPT_MAX_HOST_CONNECTIONS, 0 < $maxHostConnections ? $maxHostConnections : PHP_INT_MAX) ? 0 : $maxHostConnections; + $maxHostConnections = curl_multi_setopt($this->multi->handle, \CURLMOPT_MAX_HOST_CONNECTIONS, 0 < $maxHostConnections ? $maxHostConnections : \PHP_INT_MAX) ? 0 : $maxHostConnections; } if (\defined('CURLMOPT_MAXCONNECTS') && 0 < $maxHostConnections) { - curl_multi_setopt($this->multi->handle, CURLMOPT_MAXCONNECTS, $maxHostConnections); + curl_multi_setopt($this->multi->handle, \CURLMOPT_MAXCONNECTS, $maxHostConnections); } // Skip configuring HTTP/2 push when it's unsupported or buggy, see https://bugs.php.net/77535 @@ -90,11 +90,11 @@ public function __construct(array $defaultOptions = [], int $maxHostConnections } // HTTP/2 push crashes before curl 7.61 - if (!\defined('CURLMOPT_PUSHFUNCTION') || 0x073d00 > self::$curlVersion['version_number'] || !(CURL_VERSION_HTTP2 & self::$curlVersion['features'])) { + if (!\defined('CURLMOPT_PUSHFUNCTION') || 0x073d00 > self::$curlVersion['version_number'] || !(\CURL_VERSION_HTTP2 & self::$curlVersion['features'])) { return; } - curl_multi_setopt($this->multi->handle, CURLMOPT_PUSHFUNCTION, function ($parent, $pushed, array $requestHeaders) use ($maxPendingPushes) { + curl_multi_setopt($this->multi->handle, \CURLMOPT_PUSHFUNCTION, function ($parent, $pushed, array $requestHeaders) use ($maxPendingPushes) { return $this->handlePush($parent, $pushed, $requestHeaders, $maxPendingPushes); }); } @@ -109,7 +109,7 @@ public function request(string $method, string $url, array $options = []): Respo [$url, $options] = self::prepareRequest($method, $url, $options, $this->defaultOptions); $scheme = $url['scheme']; $authority = $url['authority']; - $host = parse_url($authority, PHP_URL_HOST); + $host = parse_url($authority, \PHP_URL_HOST); $url = implode('', $url); if (!isset($options['normalized_headers']['user-agent'])) { @@ -117,38 +117,38 @@ public function request(string $method, string $url, array $options = []): Respo } $curlopts = [ - CURLOPT_URL => $url, - CURLOPT_TCP_NODELAY => true, - CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, - CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_MAXREDIRS => 0 < $options['max_redirects'] ? $options['max_redirects'] : 0, - CURLOPT_COOKIEFILE => '', // Keep track of cookies during redirects - CURLOPT_TIMEOUT => 0, - CURLOPT_PROXY => $options['proxy'], - CURLOPT_NOPROXY => $options['no_proxy'] ?? $_SERVER['no_proxy'] ?? $_SERVER['NO_PROXY'] ?? '', - CURLOPT_SSL_VERIFYPEER => $options['verify_peer'], - CURLOPT_SSL_VERIFYHOST => $options['verify_host'] ? 2 : 0, - CURLOPT_CAINFO => $options['cafile'], - CURLOPT_CAPATH => $options['capath'], - CURLOPT_SSL_CIPHER_LIST => $options['ciphers'], - CURLOPT_SSLCERT => $options['local_cert'], - CURLOPT_SSLKEY => $options['local_pk'], - CURLOPT_KEYPASSWD => $options['passphrase'], - CURLOPT_CERTINFO => $options['capture_peer_cert_chain'], + \CURLOPT_URL => $url, + \CURLOPT_TCP_NODELAY => true, + \CURLOPT_PROTOCOLS => \CURLPROTO_HTTP | \CURLPROTO_HTTPS, + \CURLOPT_REDIR_PROTOCOLS => \CURLPROTO_HTTP | \CURLPROTO_HTTPS, + \CURLOPT_FOLLOWLOCATION => true, + \CURLOPT_MAXREDIRS => 0 < $options['max_redirects'] ? $options['max_redirects'] : 0, + \CURLOPT_COOKIEFILE => '', // Keep track of cookies during redirects + \CURLOPT_TIMEOUT => 0, + \CURLOPT_PROXY => $options['proxy'], + \CURLOPT_NOPROXY => $options['no_proxy'] ?? $_SERVER['no_proxy'] ?? $_SERVER['NO_PROXY'] ?? '', + \CURLOPT_SSL_VERIFYPEER => $options['verify_peer'], + \CURLOPT_SSL_VERIFYHOST => $options['verify_host'] ? 2 : 0, + \CURLOPT_CAINFO => $options['cafile'], + \CURLOPT_CAPATH => $options['capath'], + \CURLOPT_SSL_CIPHER_LIST => $options['ciphers'], + \CURLOPT_SSLCERT => $options['local_cert'], + \CURLOPT_SSLKEY => $options['local_pk'], + \CURLOPT_KEYPASSWD => $options['passphrase'], + \CURLOPT_CERTINFO => $options['capture_peer_cert_chain'], ]; if (1.0 === (float) $options['http_version']) { - $curlopts[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0; + $curlopts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0; } elseif (1.1 === (float) $options['http_version']) { - $curlopts[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; - } elseif (\defined('CURL_VERSION_HTTP2') && (CURL_VERSION_HTTP2 & self::$curlVersion['features']) && ('https:' === $scheme || 2.0 === (float) $options['http_version'])) { - $curlopts[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2_0; + $curlopts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1; + } elseif (\defined('CURL_VERSION_HTTP2') && (\CURL_VERSION_HTTP2 & self::$curlVersion['features']) && ('https:' === $scheme || 2.0 === (float) $options['http_version'])) { + $curlopts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0; } if (isset($options['auth_ntlm'])) { - $curlopts[CURLOPT_HTTPAUTH] = CURLAUTH_NTLM; - $curlopts[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; + $curlopts[\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM; + $curlopts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1; if (\is_array($options['auth_ntlm'])) { $count = \count($options['auth_ntlm']); @@ -163,15 +163,15 @@ public function request(string $method, string $url, array $options = []): Respo throw new InvalidArgumentException(sprintf('Option "auth_ntlm" must be a string or an array, "%s" given.', get_debug_type($options['auth_ntlm']))); } - $curlopts[CURLOPT_USERPWD] = $options['auth_ntlm']; + $curlopts[\CURLOPT_USERPWD] = $options['auth_ntlm']; } - if (!ZEND_THREAD_SAFE) { - $curlopts[CURLOPT_DNS_USE_GLOBAL_CACHE] = false; + if (!\ZEND_THREAD_SAFE) { + $curlopts[\CURLOPT_DNS_USE_GLOBAL_CACHE] = false; } if (\defined('CURLOPT_HEADEROPT')) { - $curlopts[CURLOPT_HEADEROPT] = CURLHEADER_SEPARATE; + $curlopts[\CURLOPT_HEADEROPT] = \CURLHEADER_SEPARATE; } // curl's resolve feature varies by host:port but ours varies by host only, let's handle this with our own DNS map @@ -183,7 +183,7 @@ public function request(string $method, string $url, array $options = []): Respo // First reset any old DNS cache entries then add the new ones $resolve = $this->multi->dnsCache->evictions; $this->multi->dnsCache->evictions = []; - $port = parse_url($authority, PHP_URL_PORT) ?: ('http:' === $scheme ? 80 : 443); + $port = parse_url($authority, \PHP_URL_PORT) ?: ('http:' === $scheme ? 80 : 443); if ($resolve && 0x072a00 > self::$curlVersion['version_number']) { // DNS cache removals require curl 7.42 or higher @@ -198,20 +198,20 @@ public function request(string $method, string $url, array $options = []): Respo $this->multi->dnsCache->removals["-$host:$port"] = "-$host:$port"; } - $curlopts[CURLOPT_RESOLVE] = $resolve; + $curlopts[\CURLOPT_RESOLVE] = $resolve; } if ('POST' === $method) { // Use CURLOPT_POST to have browser-like POST-to-GET redirects for 301, 302 and 303 - $curlopts[CURLOPT_POST] = true; + $curlopts[\CURLOPT_POST] = true; } elseif ('HEAD' === $method) { - $curlopts[CURLOPT_NOBODY] = true; + $curlopts[\CURLOPT_NOBODY] = true; } else { - $curlopts[CURLOPT_CUSTOMREQUEST] = $method; + $curlopts[\CURLOPT_CUSTOMREQUEST] = $method; } if ('\\' !== \DIRECTORY_SEPARATOR && $options['timeout'] < 1) { - $curlopts[CURLOPT_NOSIGNAL] = true; + $curlopts[\CURLOPT_NOSIGNAL] = true; } if (\extension_loaded('zlib') && !isset($options['normalized_headers']['accept-encoding'])) { @@ -221,41 +221,41 @@ public function request(string $method, string $url, array $options = []): Respo foreach ($options['headers'] as $header) { if (':' === $header[-2] && \strlen($header) - 2 === strpos($header, ': ')) { // curl requires a special syntax to send empty headers - $curlopts[CURLOPT_HTTPHEADER][] = substr_replace($header, ';', -2); + $curlopts[\CURLOPT_HTTPHEADER][] = substr_replace($header, ';', -2); } else { - $curlopts[CURLOPT_HTTPHEADER][] = $header; + $curlopts[\CURLOPT_HTTPHEADER][] = $header; } } // Prevent curl from sending its default Accept and Expect headers foreach (['accept', 'expect'] as $header) { if (!isset($options['normalized_headers'][$header][0])) { - $curlopts[CURLOPT_HTTPHEADER][] = $header.':'; + $curlopts[\CURLOPT_HTTPHEADER][] = $header.':'; } } if (!\is_string($body = $options['body'])) { if (\is_resource($body)) { - $curlopts[CURLOPT_INFILE] = $body; + $curlopts[\CURLOPT_INFILE] = $body; } else { $eof = false; $buffer = ''; - $curlopts[CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body, &$buffer, &$eof) { + $curlopts[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body, &$buffer, &$eof) { return self::readRequestBody($length, $body, $buffer, $eof); }; } if (isset($options['normalized_headers']['content-length'][0])) { - $curlopts[CURLOPT_INFILESIZE] = substr($options['normalized_headers']['content-length'][0], \strlen('Content-Length: ')); + $curlopts[\CURLOPT_INFILESIZE] = substr($options['normalized_headers']['content-length'][0], \strlen('Content-Length: ')); } elseif (!isset($options['normalized_headers']['transfer-encoding'])) { - $curlopts[CURLOPT_HTTPHEADER][] = 'Transfer-Encoding: chunked'; // Enable chunked request bodies + $curlopts[\CURLOPT_HTTPHEADER][] = 'Transfer-Encoding: chunked'; // Enable chunked request bodies } if ('POST' !== $method) { - $curlopts[CURLOPT_UPLOAD] = true; + $curlopts[\CURLOPT_UPLOAD] = true; } } elseif ('' !== $body || 'POST' === $method) { - $curlopts[CURLOPT_POSTFIELDS] = $body; + $curlopts[\CURLOPT_POSTFIELDS] = $body; } if ($options['peer_fingerprint']) { @@ -263,15 +263,22 @@ public function request(string $method, string $url, array $options = []): Respo throw new TransportException(__CLASS__.' supports only "pin-sha256" fingerprints.'); } - $curlopts[CURLOPT_PINNEDPUBLICKEY] = 'sha256//'.implode(';sha256//', $options['peer_fingerprint']['pin-sha256']); + $curlopts[\CURLOPT_PINNEDPUBLICKEY] = 'sha256//'.implode(';sha256//', $options['peer_fingerprint']['pin-sha256']); } if ($options['bindto']) { - $curlopts[file_exists($options['bindto']) ? CURLOPT_UNIX_SOCKET_PATH : CURLOPT_INTERFACE] = $options['bindto']; + if (file_exists($options['bindto'])) { + $curlopts[\CURLOPT_UNIX_SOCKET_PATH] = $options['bindto']; + } elseif (preg_match('/^(.*):(\d+)$/', $options['bindto'], $matches)) { + $curlopts[\CURLOPT_INTERFACE] = $matches[1]; + $curlopts[\CURLOPT_LOCALPORT] = $matches[2]; + } else { + $curlopts[\CURLOPT_INTERFACE] = $options['bindto']; + } } if (0 < $options['max_duration']) { - $curlopts[CURLOPT_TIMEOUT_MS] = 1000 * $options['max_duration']; + $curlopts[\CURLOPT_TIMEOUT_MS] = 1000 * $options['max_duration']; } if ($pushedResponse = $this->multi->pushedResponses[$url] ?? null) { @@ -296,10 +303,10 @@ public function request(string $method, string $url, array $options = []): Respo } foreach ($curlopts as $opt => $value) { - if (null !== $value && !curl_setopt($ch, $opt, $value) && CURLOPT_CERTINFO !== $opt) { + if (null !== $value && !curl_setopt($ch, $opt, $value) && \CURLOPT_CERTINFO !== $opt) { $constants = array_filter(get_defined_constants(), static function ($v, $k) use ($opt) { return $v === $opt && 'C' === $k[0] && (0 === strpos($k, 'CURLOPT_') || 0 === strpos($k, 'CURLINFO_')); - }, ARRAY_FILTER_USE_BOTH); + }, \ARRAY_FILTER_USE_BOTH); throw new TransportException(sprintf('Curl option "%s" is not supported.', key($constants) ?? $opt)); } @@ -320,7 +327,7 @@ public function stream($responses, float $timeout = null): ResponseStreamInterfa } $active = 0; - while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($this->multi->handle, $active)); + while (\CURLM_CALL_MULTI_PERFORM === curl_multi_exec($this->multi->handle, $active)); return new ResponseStream(CurlResponse::stream($responses, $timeout)); } @@ -339,16 +346,16 @@ public function reset() if (\is_resource($this->multi->handle) || $this->multi->handle instanceof \CurlMultiHandle) { if (\defined('CURLMOPT_PUSHFUNCTION')) { - curl_multi_setopt($this->multi->handle, CURLMOPT_PUSHFUNCTION, null); + curl_multi_setopt($this->multi->handle, \CURLMOPT_PUSHFUNCTION, null); } $active = 0; - while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($this->multi->handle, $active)); + while (\CURLM_CALL_MULTI_PERFORM === curl_multi_exec($this->multi->handle, $active)); } foreach ($this->multi->openHandles as [$ch]) { if (\is_resource($ch) || $ch instanceof \CurlHandle) { - curl_setopt($ch, CURLOPT_VERBOSE, false); + curl_setopt($ch, \CURLOPT_VERBOSE, false); } } } @@ -361,7 +368,7 @@ public function __destruct() private function handlePush($parent, $pushed, array $requestHeaders, int $maxPendingPushes): int { $headers = []; - $origin = curl_getinfo($parent, CURLINFO_EFFECTIVE_URL); + $origin = curl_getinfo($parent, \CURLINFO_EFFECTIVE_URL); foreach ($requestHeaders as $h) { if (false !== $i = strpos($h, ':', 1)) { @@ -372,7 +379,7 @@ private function handlePush($parent, $pushed, array $requestHeaders, int $maxPen if (!isset($headers[':method']) || !isset($headers[':scheme']) || !isset($headers[':authority']) || !isset($headers[':path'])) { $this->logger && $this->logger->debug(sprintf('Rejecting pushed response from "%s": pushed headers are invalid', $origin)); - return CURL_PUSH_DENY; + return \CURL_PUSH_DENY; } $url = $headers[':scheme'][0].'://'.$headers[':authority'][0]; @@ -383,7 +390,7 @@ private function handlePush($parent, $pushed, array $requestHeaders, int $maxPen if (0 !== strpos($origin, $url.'/')) { $this->logger && $this->logger->debug(sprintf('Rejecting pushed response from "%s": server is not authoritative for "%s"', $origin, $url)); - return CURL_PUSH_DENY; + return \CURL_PUSH_DENY; } if ($maxPendingPushes <= \count($this->multi->pushedResponses)) { @@ -397,7 +404,7 @@ private function handlePush($parent, $pushed, array $requestHeaders, int $maxPen $this->multi->pushedResponses[$url] = new PushedResponse(new CurlResponse($this->multi, $pushed), $headers, $this->multi->openHandles[(int) $parent][1] ?? [], $pushed); - return CURL_PUSH_OK; + return \CURL_PUSH_OK; } /** @@ -477,12 +484,12 @@ private static function createRedirectResolver(array $options, string $host): \C return null; } - if ($redirectHeaders && $host = parse_url('http:'.$location['authority'], PHP_URL_HOST)) { + if ($redirectHeaders && $host = parse_url('http:'.$location['authority'], \PHP_URL_HOST)) { $requestHeaders = $redirectHeaders['host'] === $host ? $redirectHeaders['with_auth'] : $redirectHeaders['no_auth']; - curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders); + curl_setopt($ch, \CURLOPT_HTTPHEADER, $requestHeaders); } - $url = self::parseUrl(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL)); + $url = self::parseUrl(curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL)); return implode('', self::resolveUrl($location, $url)); }; diff --git a/src/Symfony/Component/HttpClient/Exception/HttpExceptionTrait.php b/src/Symfony/Component/HttpClient/Exception/HttpExceptionTrait.php index 76e650934b13..5b7b44830722 100644 --- a/src/Symfony/Component/HttpClient/Exception/HttpExceptionTrait.php +++ b/src/Symfony/Component/HttpClient/Exception/HttpExceptionTrait.php @@ -60,7 +60,8 @@ public function __construct(ResponseInterface $response) // see http://www.hydra-cg.com/spec/latest/core/#description-of-http-status-codes-and-errors $separator = isset($body['hydra:title'], $body['hydra:description']) ? "\n\n" : ''; $message = ($body['hydra:title'] ?? '').$separator.($body['hydra:description'] ?? ''); - } elseif (isset($body['title']) || isset($body['detail'])) { + } elseif ((isset($body['title']) || isset($body['detail'])) + && (is_scalar($body['title'] ?? '') && is_scalar($body['detail'] ?? ''))) { // see RFC 7807 and https://jsonapi.org/format/#error-objects $separator = isset($body['title'], $body['detail']) ? "\n\n" : ''; $message = ($body['title'] ?? '').$separator.($body['detail'] ?? ''); diff --git a/src/Symfony/Component/HttpClient/HttpClient.php b/src/Symfony/Component/HttpClient/HttpClient.php index 76031d729824..606d043298be 100644 --- a/src/Symfony/Component/HttpClient/HttpClient.php +++ b/src/Symfony/Component/HttpClient/HttpClient.php @@ -44,7 +44,7 @@ public static function create(array $defaultOptions = [], int $maxHostConnection $curlVersion = $curlVersion ?? curl_version(); // HTTP/2 push crashes before curl 7.61 - if (0x073d00 > $curlVersion['version_number'] || !(CURL_VERSION_HTTP2 & $curlVersion['features'])) { + if (0x073d00 > $curlVersion['version_number'] || !(\CURL_VERSION_HTTP2 & $curlVersion['features'])) { return new AmpHttpClient($defaultOptions, null, $maxHostConnections, $maxPendingPushes); } } @@ -54,14 +54,14 @@ public static function create(array $defaultOptions = [], int $maxHostConnection return new CurlHttpClient($defaultOptions, $maxHostConnections, $maxPendingPushes); } - @trigger_error('Configure the "curl.cainfo", "openssl.cafile" or "openssl.capath" php.ini setting to enable the CurlHttpClient', E_USER_WARNING); + @trigger_error('Configure the "curl.cainfo", "openssl.cafile" or "openssl.capath" php.ini setting to enable the CurlHttpClient', \E_USER_WARNING); } if ($amp) { return new AmpHttpClient($defaultOptions, null, $maxHostConnections, $maxPendingPushes); } - @trigger_error((\extension_loaded('curl') ? 'Upgrade' : 'Install').' the curl extension or run "composer require amphp/http-client" to perform async HTTP operations, including full HTTP/2 support', E_USER_NOTICE); + @trigger_error((\extension_loaded('curl') ? 'Upgrade' : 'Install').' the curl extension or run "composer require amphp/http-client" to perform async HTTP operations, including full HTTP/2 support', \E_USER_NOTICE); return new NativeHttpClient($defaultOptions, $maxHostConnections); } diff --git a/src/Symfony/Component/HttpClient/HttpClientTrait.php b/src/Symfony/Component/HttpClient/HttpClientTrait.php index f447ce104963..cf2f1cc6e989 100644 --- a/src/Symfony/Component/HttpClient/HttpClientTrait.php +++ b/src/Symfony/Component/HttpClient/HttpClientTrait.php @@ -111,7 +111,7 @@ private static function prepareRequest(?string $method, ?string $url, array $opt throw new InvalidArgumentException(sprintf('Option "auth_basic" must be string or an array, "%s" given.', get_debug_type($options['auth_basic']))); } - if (isset($options['auth_bearer']) && (!\is_string($options['auth_bearer']) || !preg_match('{^[-._=~+/0-9a-zA-Z]++$}', $options['auth_bearer']))) { + if (isset($options['auth_bearer']) && (!\is_string($options['auth_bearer']) || !preg_match('{^[-._=:~+/0-9a-zA-Z]++$}', $options['auth_bearer']))) { throw new InvalidArgumentException(sprintf('Option "auth_bearer" must be a string containing only characters from the base 64 alphabet, %s given.', \is_string($options['auth_bearer']) ? 'invalid string' : '"'.get_debug_type($options['auth_bearer']).'"')); } @@ -198,6 +198,16 @@ private static function mergeDefaultOptions(array $options, array $defaultOption continue; } + if ('auth_ntlm' === $name) { + if (!\extension_loaded('curl')) { + $msg = 'try installing the "curl" extension to use "%s" instead.'; + } else { + $msg = 'try using "%s" instead.'; + } + + throw new InvalidArgumentException(sprintf('Option "auth_ntlm" is not supported by "%s", '.$msg, __CLASS__, CurlHttpClient::class)); + } + $alternatives = []; foreach ($defaultOptions as $key => $v) { @@ -206,10 +216,6 @@ private static function mergeDefaultOptions(array $options, array $defaultOption } } - if ('auth_ntlm' === $name) { - throw new InvalidArgumentException(sprintf('Option "auth_ntlm" is not supported by "%s", try using CurlHttpClient instead.', __CLASS__)); - } - throw new InvalidArgumentException(sprintf('Unsupported option "%s" passed to "%s", did you mean "%s"?', $name, __CLASS__, implode('", "', $alternatives ?: array_keys($defaultOptions)))); } @@ -269,7 +275,7 @@ private static function normalizeHeaders(array $headers): array private static function normalizeBody($body) { if (\is_array($body)) { - return http_build_query($body, '', '&', PHP_QUERY_RFC1738); + return http_build_query($body, '', '&', \PHP_QUERY_RFC1738); } if (\is_string($body)) { @@ -352,15 +358,15 @@ private static function normalizePeerFingerprint($fingerprint): array */ private static function jsonEncode($value, int $flags = null, int $maxDepth = 512): string { - $flags = $flags ?? (JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_PRESERVE_ZERO_FRACTION); + $flags = $flags ?? (\JSON_HEX_TAG | \JSON_HEX_APOS | \JSON_HEX_AMP | \JSON_HEX_QUOT | \JSON_PRESERVE_ZERO_FRACTION); try { - $value = json_encode($value, $flags | (\PHP_VERSION_ID >= 70300 ? JSON_THROW_ON_ERROR : 0), $maxDepth); + $value = json_encode($value, $flags | (\PHP_VERSION_ID >= 70300 ? \JSON_THROW_ON_ERROR : 0), $maxDepth); } catch (\JsonException $e) { throw new InvalidArgumentException('Invalid value for "json" option: '.$e->getMessage()); } - if (\PHP_VERSION_ID < 70300 && JSON_ERROR_NONE !== json_last_error() && (false === $value || !($flags & JSON_PARTIAL_OUTPUT_ON_ERROR))) { + if (\PHP_VERSION_ID < 70300 && \JSON_ERROR_NONE !== json_last_error() && (false === $value || !($flags & \JSON_PARTIAL_OUTPUT_ON_ERROR))) { throw new InvalidArgumentException('Invalid value for "json" option: '.json_last_error_msg()); } @@ -455,7 +461,7 @@ private static function parseUrl(string $url, array $query = [], array $allowedS throw new InvalidArgumentException(sprintf('Unsupported IDN "%s", try enabling the "intl" PHP extension or running "composer require symfony/polyfill-intl-idn".', $host)); } - $host = \defined('INTL_IDNA_VARIANT_UTS46') ? idn_to_ascii($host, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46) ?: strtolower($host) : strtolower($host); + $host = \defined('INTL_IDNA_VARIANT_UTS46') ? idn_to_ascii($host, \IDNA_DEFAULT, \INTL_IDNA_VARIANT_UTS46) ?: strtolower($host) : strtolower($host); $host .= $port ? ':'.$port : ''; } @@ -540,7 +546,7 @@ private static function mergeQueryString(?string $queryString, array $queryArray } } - $queryString = http_build_query($queryArray, '', '&', PHP_QUERY_RFC3986); + $queryString = http_build_query($queryArray, '', '&', \PHP_QUERY_RFC3986); $queryArray = []; if ($queryString) { diff --git a/src/Symfony/Component/HttpClient/Internal/AmpClientState.php b/src/Symfony/Component/HttpClient/Internal/AmpClientState.php index afd4c88fb8b4..61a0c004acfb 100644 --- a/src/Symfony/Component/HttpClient/Internal/AmpClientState.php +++ b/src/Symfony/Component/HttpClient/Internal/AmpClientState.php @@ -185,7 +185,7 @@ public function connect(string $uri, ?ConnectContext $context = null, ?Cancellat } } - $maxHostConnections = 0 < $this->maxHostConnections ? $this->maxHostConnections : PHP_INT_MAX; + $maxHostConnections = 0 < $this->maxHostConnections ? $this->maxHostConnections : \PHP_INT_MAX; $pool = new DefaultConnectionFactory($connector, $context); $pool = ConnectionLimitingPool::byAuthority($maxHostConnections, $pool); diff --git a/src/Symfony/Component/HttpClient/Internal/NativeClientState.php b/src/Symfony/Component/HttpClient/Internal/NativeClientState.php index 2a47dbcca0ec..0d765b74e68e 100644 --- a/src/Symfony/Component/HttpClient/Internal/NativeClientState.php +++ b/src/Symfony/Component/HttpClient/Internal/NativeClientState.php @@ -23,7 +23,7 @@ final class NativeClientState extends ClientState /** @var int */ public $id; /** @var int */ - public $maxHostConnections = PHP_INT_MAX; + public $maxHostConnections = \PHP_INT_MAX; /** @var int */ public $responseCount = 0; /** @var string[] */ @@ -33,6 +33,6 @@ final class NativeClientState extends ClientState public function __construct() { - $this->id = random_int(PHP_INT_MIN, PHP_INT_MAX); + $this->id = random_int(\PHP_INT_MIN, \PHP_INT_MAX); } } diff --git a/src/Symfony/Component/HttpClient/NativeHttpClient.php b/src/Symfony/Component/HttpClient/NativeHttpClient.php index fe3de8bf2343..f74e621bb8ba 100644 --- a/src/Symfony/Component/HttpClient/NativeHttpClient.php +++ b/src/Symfony/Component/HttpClient/NativeHttpClient.php @@ -55,7 +55,7 @@ public function __construct(array $defaultOptions = [], int $maxHostConnections } $this->multi = new NativeClientState(); - $this->multi->maxHostConnections = 0 < $maxHostConnections ? $maxHostConnections : PHP_INT_MAX; + $this->multi->maxHostConnections = 0 < $maxHostConnections ? $maxHostConnections : \PHP_INT_MAX; } /** @@ -116,7 +116,7 @@ public function request(string $method, string $url, array $options = []): Respo if ($onProgress = $options['on_progress']) { // Memoize the last progress to ease calling the callback periodically when no network transfer happens $lastProgress = [0, 0]; - $maxDuration = 0 < $options['max_duration'] ? $options['max_duration'] : INF; + $maxDuration = 0 < $options['max_duration'] ? $options['max_duration'] : \INF; $onProgress = static function (...$progress) use ($onProgress, &$lastProgress, &$info, $maxDuration) { if ($info['total_time'] >= $maxDuration) { throw new TransportException(sprintf('Max duration was reached for "%s".', implode('', $info['url']))); @@ -148,11 +148,11 @@ public function request(string $method, string $url, array $options = []): Respo $notification = static function (int $code, int $severity, ?string $msg, int $msgCode, int $dlNow, int $dlSize) use ($onProgress, &$info) { $info['total_time'] = microtime(true) - $info['start_time']; - if (STREAM_NOTIFY_PROGRESS === $code) { + if (\STREAM_NOTIFY_PROGRESS === $code) { $info['starttransfer_time'] = $info['starttransfer_time'] ?: $info['total_time']; $info['size_upload'] += $dlNow ? 0 : $info['size_body']; $info['size_download'] = $dlNow; - } elseif (STREAM_NOTIFY_CONNECT === $code) { + } elseif (\STREAM_NOTIFY_CONNECT === $code) { $info['connect_time'] = $info['total_time']; $info['debug'] .= $info['request_header']; unset($info['request_header']); @@ -214,7 +214,7 @@ public function request(string $method, string $url, array $options = []): Respo 'disable_compression' => true, ], static function ($v) { return null !== $v; }), 'socket' => [ - 'bindto' => $options['bindto'], + 'bindto' => $options['bindto'] ?: '0:0', 'tcp_nodelay' => true, ], ]; @@ -269,14 +269,14 @@ private static function getBodyAsString($body): string */ private static function dnsResolve(array $url, NativeClientState $multi, array &$info, ?\Closure $onProgress): array { - if ($port = parse_url($url['authority'], PHP_URL_PORT) ?: '') { + if ($port = parse_url($url['authority'], \PHP_URL_PORT) ?: '') { $info['primary_port'] = $port; $port = ':'.$port; } else { $info['primary_port'] = 'http:' === $url['scheme'] ? 80 : 443; } - $host = parse_url($url['authority'], PHP_URL_HOST); + $host = parse_url($url['authority'], \PHP_URL_HOST); if (null === $ip = $multi->dnsCache[$host] ?? null) { $info['debug'] .= "* Hostname was NOT found in DNS cache\n"; @@ -366,7 +366,7 @@ private static function createRedirectResolver(array $options, string $host, ?ar [$host, $port, $url['authority']] = self::dnsResolve($url, $multi, $info, $onProgress); stream_context_set_option($context, 'ssl', 'peer_name', $host); - if (false !== (parse_url($location, PHP_URL_HOST) ?? false)) { + if (false !== (parse_url($location, \PHP_URL_HOST) ?? false)) { // Authorization and Cookie headers MUST NOT follow except for the initial host name $requestHeaders = $redirectHeaders['host'] === $host ? $redirectHeaders['with_auth'] : $redirectHeaders['no_auth']; $requestHeaders[] = 'Host: '.$host.$port; diff --git a/src/Symfony/Component/HttpClient/Response/CurlResponse.php b/src/Symfony/Component/HttpClient/Response/CurlResponse.php index 82b0e2c1ebe3..29f82ac9b7ce 100644 --- a/src/Symfony/Component/HttpClient/Response/CurlResponse.php +++ b/src/Symfony/Component/HttpClient/Response/CurlResponse.php @@ -50,8 +50,8 @@ public function __construct(CurlClientState $multi, $ch, array $options = null, if (0x074000 === $curlVersion) { fwrite($this->debugBuffer, 'Due to a bug in curl 7.64.0, the debug log is disabled; use another version to work around the issue.'); } else { - curl_setopt($ch, CURLOPT_VERBOSE, true); - curl_setopt($ch, CURLOPT_STDERR, $this->debugBuffer); + curl_setopt($ch, \CURLOPT_VERBOSE, true); + curl_setopt($ch, \CURLOPT_STDERR, $this->debugBuffer); } } else { $this->info['url'] = $ch; @@ -71,10 +71,10 @@ public function __construct(CurlClientState $multi, $ch, array $options = null, if (!$info['response_headers']) { // Used to keep track of what we're waiting for - curl_setopt($ch, CURLOPT_PRIVATE, \in_array($method, ['GET', 'HEAD', 'OPTIONS', 'TRACE'], true) && 1.0 < (float) ($options['http_version'] ?? 1.1) ? 'H2' : 'H0'); // H = headers + retry counter + curl_setopt($ch, \CURLOPT_PRIVATE, \in_array($method, ['GET', 'HEAD', 'OPTIONS', 'TRACE'], true) && 1.0 < (float) ($options['http_version'] ?? 1.1) ? 'H2' : 'H0'); // H = headers + retry counter } - curl_setopt($ch, CURLOPT_HEADERFUNCTION, static function ($ch, string $data) use (&$info, &$headers, $options, $multi, $id, &$location, $resolveRedirect, $logger): int { + curl_setopt($ch, \CURLOPT_HEADERFUNCTION, static function ($ch, string $data) use (&$info, &$headers, $options, $multi, $id, &$location, $resolveRedirect, $logger): int { if (0 !== substr_compare($data, "\r\n", -2)) { return 0; } @@ -90,9 +90,9 @@ public function __construct(CurlClientState $multi, $ch, array $options = null, if (null === $options) { // Pushed response: buffer until requested - curl_setopt($ch, CURLOPT_WRITEFUNCTION, static function ($ch, string $data) use ($multi, $id): int { + curl_setopt($ch, \CURLOPT_WRITEFUNCTION, static function ($ch, string $data) use ($multi, $id): int { $multi->handlesActivity[$id][] = $data; - curl_pause($ch, CURLPAUSE_RECV); + curl_pause($ch, \CURLPAUSE_RECV); return \strlen($data); }); @@ -101,12 +101,12 @@ public function __construct(CurlClientState $multi, $ch, array $options = null, } $this->inflate = !isset($options['normalized_headers']['accept-encoding']); - curl_pause($ch, CURLPAUSE_CONT); + curl_pause($ch, \CURLPAUSE_CONT); if ($onProgress = $options['on_progress']) { $url = isset($info['url']) ? ['url' => $info['url']] : []; - curl_setopt($ch, CURLOPT_NOPROGRESS, false); - curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, static function ($ch, $dlSize, $dlNow) use ($onProgress, &$info, $url, $multi, $debugBuffer) { + curl_setopt($ch, \CURLOPT_NOPROGRESS, false); + curl_setopt($ch, \CURLOPT_PROGRESSFUNCTION, static function ($ch, $dlSize, $dlNow) use ($onProgress, &$info, $url, $multi, $debugBuffer) { try { rewind($debugBuffer); $debug = ['debug' => stream_get_contents($debugBuffer)]; @@ -122,14 +122,27 @@ public function __construct(CurlClientState $multi, $ch, array $options = null, }); } - curl_setopt($ch, CURLOPT_WRITEFUNCTION, static function ($ch, string $data) use ($multi, $id): int { + curl_setopt($ch, \CURLOPT_WRITEFUNCTION, static function ($ch, string $data) use ($multi, $id): int { + if ('H' === (curl_getinfo($ch, \CURLINFO_PRIVATE)[0] ?? null)) { + $multi->handlesActivity[$id][] = null; + $multi->handlesActivity[$id][] = new TransportException(sprintf('Unsupported protocol for "%s"', curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL))); + + return 0; + } + + curl_setopt($ch, \CURLOPT_WRITEFUNCTION, static function ($ch, string $data) use ($multi, $id): int { + $multi->handlesActivity[$id][] = $data; + + return \strlen($data); + }); + $multi->handlesActivity[$id][] = $data; return \strlen($data); }); $this->initializer = static function (self $response) { - $waitFor = curl_getinfo($ch = $response->handle, CURLINFO_PRIVATE); + $waitFor = curl_getinfo($ch = $response->handle, \CURLINFO_PRIVATE); return 'H' === $waitFor[0]; }; @@ -157,10 +170,10 @@ public function getInfo(string $type = null) rewind($this->debugBuffer); $info['debug'] = stream_get_contents($this->debugBuffer); - $waitFor = curl_getinfo($this->handle, CURLINFO_PRIVATE); + $waitFor = curl_getinfo($this->handle, \CURLINFO_PRIVATE); if ('H' !== $waitFor[0] && 'C' !== $waitFor[0]) { - curl_setopt($this->handle, CURLOPT_VERBOSE, false); + curl_setopt($this->handle, \CURLOPT_VERBOSE, false); rewind($this->debugBuffer); ftruncate($this->debugBuffer, 0); $this->finalInfo = $info; @@ -176,7 +189,7 @@ public function getInfo(string $type = null) public function getContent(bool $throw = true): string { $performing = self::$performing; - self::$performing = $performing || '_0' === curl_getinfo($this->handle, CURLINFO_PRIVATE); + self::$performing = $performing || '_0' === curl_getinfo($this->handle, \CURLINFO_PRIVATE); try { return $this->doGetContent($throw); @@ -218,7 +231,7 @@ private function close(): void { $this->inflate = null; unset($this->multi->openHandles[$this->id], $this->multi->handlesActivity[$this->id]); - curl_setopt($this->handle, CURLOPT_PRIVATE, '_0'); + curl_setopt($this->handle, \CURLOPT_PRIVATE, '_0'); if (self::$performing) { return; @@ -226,12 +239,12 @@ private function close(): void curl_multi_remove_handle($this->multi->handle, $this->handle); curl_setopt_array($this->handle, [ - CURLOPT_NOPROGRESS => true, - CURLOPT_PROGRESSFUNCTION => null, - CURLOPT_HEADERFUNCTION => null, - CURLOPT_WRITEFUNCTION => null, - CURLOPT_READFUNCTION => null, - CURLOPT_INFILE => null, + \CURLOPT_NOPROGRESS => true, + \CURLOPT_PROGRESSFUNCTION => null, + \CURLOPT_HEADERFUNCTION => null, + \CURLOPT_WRITEFUNCTION => null, + \CURLOPT_READFUNCTION => null, + \CURLOPT_INFILE => null, ]); } @@ -246,7 +259,7 @@ private static function schedule(self $response, array &$runningResponses): void $runningResponses[$i] = [$response->multi, [$response->id => $response]]; } - if ('_0' === curl_getinfo($ch = $response->handle, CURLINFO_PRIVATE)) { + if ('_0' === curl_getinfo($ch = $response->handle, \CURLINFO_PRIVATE)) { // Response already completed $response->multi->handlesActivity[$response->id][] = null; $response->multi->handlesActivity[$response->id][] = null !== $response->info['error'] ? new TransportException($response->info['error']) : null; @@ -264,7 +277,7 @@ private static function perform(ClientState $multi, array &$responses = null): v if ($responses) { $response = current($responses); $multi->handlesActivity[(int) $response->handle][] = null; - $multi->handlesActivity[(int) $response->handle][] = new TransportException(sprintf('Userland callback cannot use the client nor the response while processing "%s".', curl_getinfo($response->handle, CURLINFO_EFFECTIVE_URL))); + $multi->handlesActivity[(int) $response->handle][] = new TransportException(sprintf('Userland callback cannot use the client nor the response while processing "%s".', curl_getinfo($response->handle, \CURLINFO_EFFECTIVE_URL))); } return; @@ -273,20 +286,20 @@ private static function perform(ClientState $multi, array &$responses = null): v try { self::$performing = true; $active = 0; - while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($multi->handle, $active)); + while (\CURLM_CALL_MULTI_PERFORM === curl_multi_exec($multi->handle, $active)); while ($info = curl_multi_info_read($multi->handle)) { $result = $info['result']; $id = (int) $ch = $info['handle']; - $waitFor = @curl_getinfo($ch, CURLINFO_PRIVATE) ?: '_0'; + $waitFor = @curl_getinfo($ch, \CURLINFO_PRIVATE) ?: '_0'; - if (\in_array($result, [CURLE_SEND_ERROR, CURLE_RECV_ERROR, /*CURLE_HTTP2*/ 16, /*CURLE_HTTP2_STREAM*/ 92], true) && $waitFor[1] && 'C' !== $waitFor[0]) { + if (\in_array($result, [\CURLE_SEND_ERROR, \CURLE_RECV_ERROR, /*CURLE_HTTP2*/ 16, /*CURLE_HTTP2_STREAM*/ 92], true) && $waitFor[1] && 'C' !== $waitFor[0]) { curl_multi_remove_handle($multi->handle, $ch); $waitFor[1] = (string) ((int) $waitFor[1] - 1); // decrement the retry counter - curl_setopt($ch, CURLOPT_PRIVATE, $waitFor); + curl_setopt($ch, \CURLOPT_PRIVATE, $waitFor); if ('1' === $waitFor[1]) { - curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); + curl_setopt($ch, \CURLOPT_HTTP_VERSION, \CURL_HTTP_VERSION_1_1); } if (0 === curl_multi_add_handle($multi->handle, $ch)) { @@ -295,7 +308,7 @@ private static function perform(ClientState $multi, array &$responses = null): v } $multi->handlesActivity[$id][] = null; - $multi->handlesActivity[$id][] = \in_array($result, [CURLE_OK, CURLE_TOO_MANY_REDIRECTS], true) || '_0' === $waitFor || curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD) === curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD) ? null : new TransportException(sprintf('%s for "%s".', curl_strerror($result), curl_getinfo($ch, CURLINFO_EFFECTIVE_URL))); + $multi->handlesActivity[$id][] = \in_array($result, [\CURLE_OK, \CURLE_TOO_MANY_REDIRECTS], true) || '_0' === $waitFor || curl_getinfo($ch, \CURLINFO_SIZE_DOWNLOAD) === curl_getinfo($ch, \CURLINFO_CONTENT_LENGTH_DOWNLOAD) ? null : new TransportException(sprintf('%s for "%s".', curl_strerror($result), curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL))); } } finally { self::$performing = false; @@ -322,7 +335,7 @@ private static function select(ClientState $multi, float $timeout): int */ private static function parseHeaderLine($ch, string $data, array &$info, array &$headers, ?array $options, CurlClientState $multi, int $id, ?string &$location, ?callable $resolveRedirect, ?LoggerInterface $logger, &$content = null): int { - $waitFor = @curl_getinfo($ch, CURLINFO_PRIVATE) ?: '_0'; + $waitFor = @curl_getinfo($ch, \CURLINFO_PRIVATE) ?: '_0'; if ('H' !== $waitFor[0]) { return \strlen($data); // Ignore HTTP trailers @@ -347,16 +360,16 @@ private static function parseHeaderLine($ch, string $data, array &$info, array & return \strlen($data); } - if (\function_exists('openssl_x509_read') && $certinfo = curl_getinfo($ch, CURLINFO_CERTINFO)) { + if (\function_exists('openssl_x509_read') && $certinfo = curl_getinfo($ch, \CURLINFO_CERTINFO)) { $info['peer_certificate_chain'] = array_map('openssl_x509_read', array_column($certinfo, 'Cert')); } if (300 <= $info['http_code'] && $info['http_code'] < 400) { - if (curl_getinfo($ch, CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) { - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); + if (curl_getinfo($ch, \CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) { + curl_setopt($ch, \CURLOPT_FOLLOWLOCATION, false); } elseif (303 === $info['http_code'] || ('POST' === $info['http_method'] && \in_array($info['http_code'], [301, 302], true))) { $info['http_method'] = 'HEAD' === $info['http_method'] ? 'HEAD' : 'GET'; - curl_setopt($ch, CURLOPT_POSTFIELDS, ''); + curl_setopt($ch, \CURLOPT_POSTFIELDS, ''); } } @@ -365,7 +378,7 @@ private static function parseHeaderLine($ch, string $data, array &$info, array & // End of headers: handle informational responses, redirects, etc. - if (200 > $statusCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE)) { + if (200 > $statusCode = curl_getinfo($ch, \CURLINFO_RESPONSE_CODE)) { $multi->handlesActivity[$id][] = new InformationalChunk($statusCode, $headers); $location = null; @@ -376,16 +389,16 @@ private static function parseHeaderLine($ch, string $data, array &$info, array & if (300 <= $statusCode && $statusCode < 400 && null !== $location) { if (null === $info['redirect_url'] = $resolveRedirect($ch, $location)) { - $options['max_redirects'] = curl_getinfo($ch, CURLINFO_REDIRECT_COUNT); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); - curl_setopt($ch, CURLOPT_MAXREDIRS, $options['max_redirects']); + $options['max_redirects'] = curl_getinfo($ch, \CURLINFO_REDIRECT_COUNT); + curl_setopt($ch, \CURLOPT_FOLLOWLOCATION, false); + curl_setopt($ch, \CURLOPT_MAXREDIRS, $options['max_redirects']); } else { $url = parse_url($location ?? ':'); if (isset($url['host']) && null !== $ip = $multi->dnsCache->hostnames[$url['host'] = strtolower($url['host'])] ?? null) { // Populate DNS cache for redirects if needed - $port = $url['port'] ?? ('http' === ($url['scheme'] ?? parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL), PHP_URL_SCHEME)) ? 80 : 443); - curl_setopt($ch, CURLOPT_RESOLVE, ["{$url['host']}:$port:$ip"]); + $port = $url['port'] ?? ('http' === ($url['scheme'] ?? parse_url(curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL), \PHP_URL_SCHEME)) ? 80 : 443); + curl_setopt($ch, \CURLOPT_RESOLVE, ["{$url['host']}:$port:$ip"]); $multi->dnsCache->removals["-{$url['host']}:$port"] = "-{$url['host']}:$port"; } } @@ -393,7 +406,7 @@ private static function parseHeaderLine($ch, string $data, array &$info, array & if (401 === $statusCode && isset($options['auth_ntlm']) && 0 === strncasecmp($headers['www-authenticate'][0] ?? '', 'NTLM ', 5)) { // Continue with NTLM auth - } elseif ($statusCode < 300 || 400 <= $statusCode || null === $location || curl_getinfo($ch, CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) { + } elseif ($statusCode < 300 || 400 <= $statusCode || null === $location || curl_getinfo($ch, \CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) { // Headers and redirects completed, time to get the response's content $multi->handlesActivity[$id][] = new FirstChunk(); @@ -405,7 +418,7 @@ private static function parseHeaderLine($ch, string $data, array &$info, array & $waitFor[0] = 'C'; // C = content } - curl_setopt($ch, CURLOPT_PRIVATE, $waitFor); + curl_setopt($ch, \CURLOPT_PRIVATE, $waitFor); } elseif (null !== $info['redirect_url'] && $logger) { $logger->info(sprintf('Redirecting: "%s %s"', $info['http_code'], $info['redirect_url'])); } diff --git a/src/Symfony/Component/HttpClient/Response/NativeResponse.php b/src/Symfony/Component/HttpClient/Response/NativeResponse.php index 2ba1b010e41f..c06df1afb0f0 100644 --- a/src/Symfony/Component/HttpClient/Response/NativeResponse.php +++ b/src/Symfony/Component/HttpClient/Response/NativeResponse.php @@ -111,7 +111,7 @@ private function open(): void $url = $this->url; set_error_handler(function ($type, $msg) use (&$url) { - if (E_NOTICE !== $type || 'fopen(): Content-type not specified assuming application/x-www-form-urlencoded' !== $msg) { + if (\E_NOTICE !== $type || 'fopen(): Content-type not specified assuming application/x-www-form-urlencoded' !== $msg) { throw new TransportException($msg); } @@ -168,7 +168,7 @@ private function open(): void if (isset($this->headers['content-length'])) { $this->remaining = (int) $this->headers['content-length'][0]; } elseif ('chunked' === ($this->headers['transfer-encoding'][0] ?? null)) { - stream_filter_append($this->buffer, 'dechunk', STREAM_FILTER_WRITE); + stream_filter_append($this->buffer, 'dechunk', \STREAM_FILTER_WRITE); $this->remaining = -1; } else { $this->remaining = -2; diff --git a/src/Symfony/Component/HttpClient/Response/ResponseTrait.php b/src/Symfony/Component/HttpClient/Response/ResponseTrait.php index 9f67d7e96661..76af2dfa7e74 100644 --- a/src/Symfony/Component/HttpClient/Response/ResponseTrait.php +++ b/src/Symfony/Component/HttpClient/Response/ResponseTrait.php @@ -151,12 +151,12 @@ public function toArray(bool $throw = true): array } try { - $content = json_decode($content, true, 512, JSON_BIGINT_AS_STRING | (\PHP_VERSION_ID >= 70300 ? JSON_THROW_ON_ERROR : 0)); + $content = json_decode($content, true, 512, \JSON_BIGINT_AS_STRING | (\PHP_VERSION_ID >= 70300 ? \JSON_THROW_ON_ERROR : 0)); } catch (\JsonException $e) { throw new JsonException($e->getMessage().sprintf(' for "%s".', $this->getInfo('url')), $e->getCode()); } - if (\PHP_VERSION_ID < 70300 && JSON_ERROR_NONE !== json_last_error()) { + if (\PHP_VERSION_ID < 70300 && \JSON_ERROR_NONE !== json_last_error()) { throw new JsonException(json_last_error_msg().sprintf(' for "%s".', $this->getInfo('url')), json_last_error()); } @@ -270,7 +270,7 @@ private static function addResponseHeaders(array $responseHeaders, array &$info, $debug .= "< \r\n"; if (!$info['http_code']) { - throw new TransportException('Invalid or missing HTTP status line.'); + throw new TransportException(sprintf('Invalid or missing HTTP status line for "%s".', implode('', $info['url']))); } } @@ -321,7 +321,7 @@ public static function stream(iterable $responses, float $timeout = null): \Gene while (true) { $hasActivity = false; $timeoutMax = 0; - $timeoutMin = $timeout ?? INF; + $timeoutMin = $timeout ?? \INF; /** @var ClientState $multi */ foreach ($runningResponses as $i => [$multi]) { @@ -350,7 +350,7 @@ public static function stream(iterable $responses, float $timeout = null): \Gene if (\is_string($chunk = array_shift($multi->handlesActivity[$j]))) { if (null !== $response->inflate && false === $chunk = @inflate_add($response->inflate, $chunk)) { - $multi->handlesActivity[$j] = [null, new TransportException('Error while processing content unencoding.')]; + $multi->handlesActivity[$j] = [null, new TransportException(sprintf('Error while processing content unencoding for "%s".', $response->getInfo('url')))]; continue; } @@ -387,7 +387,7 @@ public static function stream(iterable $responses, float $timeout = null): \Gene $response->logger->info(sprintf('Response: "%s %s"', $info['http_code'], $info['url'])); } - $response->inflate = \extension_loaded('zlib') && $response->inflate && 'gzip' === ($response->headers['content-encoding'][0] ?? null) ? inflate_init(ZLIB_ENCODING_GZIP) : null; + $response->inflate = \extension_loaded('zlib') && $response->inflate && 'gzip' === ($response->headers['content-encoding'][0] ?? null) ? inflate_init(\ZLIB_ENCODING_GZIP) : null; if ($response->shouldBuffer instanceof \Closure) { try { diff --git a/src/Symfony/Component/HttpClient/Response/StreamWrapper.php b/src/Symfony/Component/HttpClient/Response/StreamWrapper.php index 087445d6e2d8..ac0031738ed7 100644 --- a/src/Symfony/Component/HttpClient/Response/StreamWrapper.php +++ b/src/Symfony/Component/HttpClient/Response/StreamWrapper.php @@ -50,7 +50,7 @@ class StreamWrapper public static function createResource(ResponseInterface $response, HttpClientInterface $client = null) { if ($response instanceof TraceableResponse || (\is_callable([$response, 'toStream']) && isset(class_uses($response)[ResponseTrait::class]))) { - $stack = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, 2); + $stack = debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS, 2); if ($response !== ($stack[1]['object'] ?? null)) { return $response->toStream(false); @@ -61,7 +61,7 @@ public static function createResource(ResponseInterface $response, HttpClientInt throw new \InvalidArgumentException(sprintf('Providing a client to "%s()" is required when the response doesn\'t have any "stream()" method.', __CLASS__)); } - if (false === stream_wrapper_register('symfony', __CLASS__, STREAM_IS_URL)) { + if (false === stream_wrapper_register('symfony', __CLASS__, \STREAM_IS_URL)) { throw new \RuntimeException(error_get_last()['message'] ?? 'Registering the "symfony" stream wrapper failed.'); } @@ -96,8 +96,8 @@ public function bindHandles(&$handle, &$content): void public function stream_open(string $path, string $mode, int $options): bool { if ('r' !== $mode) { - if ($options & STREAM_REPORT_ERRORS) { - trigger_error(sprintf('Invalid mode "%s": only "r" is supported.', $mode), E_USER_WARNING); + if ($options & \STREAM_REPORT_ERRORS) { + trigger_error(sprintf('Invalid mode "%s": only "r" is supported.', $mode), \E_USER_WARNING); } return false; @@ -112,8 +112,8 @@ public function stream_open(string $path, string $mode, int $options): bool return true; } - if ($options & STREAM_REPORT_ERRORS) { - trigger_error('Missing options "client" or "response" in "symfony" stream context.', E_USER_WARNING); + if ($options & \STREAM_REPORT_ERRORS) { + trigger_error('Missing options "client" or "response" in "symfony" stream context.', \E_USER_WARNING); } return false; @@ -129,7 +129,7 @@ public function stream_read(int $count) $this->response->getStatusCode(); // ignore 3/4/5xx } } catch (ExceptionInterface $e) { - trigger_error($e->getMessage(), E_USER_WARNING); + trigger_error($e->getMessage(), \E_USER_WARNING); return false; } @@ -140,7 +140,7 @@ public function stream_read(int $count) } if ('' !== $data = fread($this->content, $count)) { - fseek($this->content, 0, SEEK_END); + fseek($this->content, 0, \SEEK_END); $this->offset += \strlen($data); return $data; @@ -182,7 +182,7 @@ public function stream_read(int $count) return $data; } } catch (ExceptionInterface $e) { - trigger_error($e->getMessage(), E_USER_WARNING); + trigger_error($e->getMessage(), \E_USER_WARNING); return false; } @@ -193,9 +193,9 @@ public function stream_read(int $count) public function stream_set_option(int $option, int $arg1, ?int $arg2): bool { - if (STREAM_OPTION_BLOCKING === $option) { + if (\STREAM_OPTION_BLOCKING === $option) { $this->blocking = (bool) $arg1; - } elseif (STREAM_OPTION_READ_TIMEOUT === $option) { + } elseif (\STREAM_OPTION_READ_TIMEOUT === $option) { $this->timeout = $arg1 + $arg2 / 1e6; } else { return false; @@ -214,19 +214,19 @@ public function stream_eof(): bool return $this->eof && !\is_string($this->content); } - public function stream_seek(int $offset, int $whence = SEEK_SET): bool + public function stream_seek(int $offset, int $whence = \SEEK_SET): bool { - if (!\is_resource($this->content) || 0 !== fseek($this->content, 0, SEEK_END)) { + if (!\is_resource($this->content) || 0 !== fseek($this->content, 0, \SEEK_END)) { return false; } $size = ftell($this->content); - if (SEEK_CUR === $whence) { + if (\SEEK_CUR === $whence) { $offset += $this->offset; } - if (SEEK_END === $whence || $size < $offset) { + if (\SEEK_END === $whence || $size < $offset) { foreach ($this->client->stream([$this->response]) as $chunk) { try { if ($chunk->isFirst()) { @@ -236,17 +236,17 @@ public function stream_seek(int $offset, int $whence = SEEK_SET): bool // Chunks are buffered in $this->content already $size += \strlen($chunk->getContent()); - if (SEEK_END !== $whence && $offset <= $size) { + if (\SEEK_END !== $whence && $offset <= $size) { break; } } catch (ExceptionInterface $e) { - trigger_error($e->getMessage(), E_USER_WARNING); + trigger_error($e->getMessage(), \E_USER_WARNING); return false; } } - if (SEEK_END === $whence) { + if (\SEEK_END === $whence) { $offset += $size; } } @@ -263,7 +263,7 @@ public function stream_seek(int $offset, int $whence = SEEK_SET): bool public function stream_cast(int $castAs) { - if (STREAM_CAST_FOR_SELECT === $castAs) { + if (\STREAM_CAST_FOR_SELECT === $castAs) { $this->response->getHeaders(false); return $this->handle ?? false; @@ -277,7 +277,7 @@ public function stream_stat(): array try { $headers = $this->response->getHeaders(false); } catch (ExceptionInterface $e) { - trigger_error($e->getMessage(), E_USER_WARNING); + trigger_error($e->getMessage(), \E_USER_WARNING); $headers = []; } diff --git a/src/Symfony/Component/HttpClient/Tests/CachingHttpClientTest.php b/src/Symfony/Component/HttpClient/Tests/CachingHttpClientTest.php index 0525feed6c04..ad07f8645168 100644 --- a/src/Symfony/Component/HttpClient/Tests/CachingHttpClientTest.php +++ b/src/Symfony/Component/HttpClient/Tests/CachingHttpClientTest.php @@ -89,7 +89,7 @@ public function testRemovesXContentDigest() 'test', [ 'response_headers' => [ 'X-Content-Digest' => 'some-hash', - ] + ], ])); $headers = $response->getHeaders(); @@ -100,7 +100,7 @@ private function runRequest(MockResponse $mockResponse): ResponseInterface { $mockClient = new MockHttpClient($mockResponse); - $store = new Store(sys_get_temp_dir() . '/sf_http_cache'); + $store = new Store(sys_get_temp_dir().'/sf_http_cache'); $client = new CachingHttpClient($mockClient, $store); $response = $client->request('GET', 'http://test'); diff --git a/src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php b/src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php index 269464d400e3..0a628171835b 100644 --- a/src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php +++ b/src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php @@ -26,7 +26,7 @@ protected function getHttpClient(string $testCase): HttpClientInterface $this->markTestSkipped('PHP 7.3.0 to 7.3.3 don\'t support HTTP/2 PUSH'); } - if (!\defined('CURLMOPT_PUSHFUNCTION') || 0x073d00 > ($v = curl_version())['version_number'] || !(CURL_VERSION_HTTP2 & $v['features'])) { + if (!\defined('CURLMOPT_PUSHFUNCTION') || 0x073d00 > ($v = curl_version())['version_number'] || !(\CURL_VERSION_HTTP2 & $v['features'])) { $this->markTestSkipped('curl <7.61 is used or it is not compiled with support for HTTP/2 PUSH'); } } @@ -34,6 +34,21 @@ protected function getHttpClient(string $testCase): HttpClientInterface return new CurlHttpClient(['verify_peer' => false, 'verify_host' => false]); } + public function testBindToPort() + { + $client = $this->getHttpClient(__FUNCTION__); + $response = $client->request('GET', 'http://localhost:8057', ['bindto' => '127.0.0.1:9876']); + $response->getStatusCode(); + + $r = new \ReflectionProperty($response, 'handle'); + $r->setAccessible(true); + + $curlInfo = curl_getinfo($r->getValue($response)); + + self::assertSame('127.0.0.1', $curlInfo['local_ip']); + self::assertSame(9876, $curlInfo['local_port']); + } + public function testTimeoutIsNotAFatalError() { if ('\\' === \DIRECTORY_SEPARATOR) { diff --git a/src/Symfony/Component/HttpClient/Tests/Exception/HttpExceptionTraitTest.php b/src/Symfony/Component/HttpClient/Tests/Exception/HttpExceptionTraitTest.php index ac6c30df1f50..c2771cc3ae0a 100644 --- a/src/Symfony/Component/HttpClient/Tests/Exception/HttpExceptionTraitTest.php +++ b/src/Symfony/Component/HttpClient/Tests/Exception/HttpExceptionTraitTest.php @@ -22,15 +22,24 @@ class HttpExceptionTraitTest extends TestCase { public function provideParseError(): iterable { - yield ['application/ld+json', '{"hydra:title": "An error occurred", "hydra:description": "Some details"}']; - yield ['application/problem+json', '{"title": "An error occurred", "detail": "Some details"}']; - yield ['application/vnd.api+json', '{"title": "An error occurred", "detail": "Some details"}']; + $errorWithoutMessage = 'HTTP/1.1 400 Bad Request returned for "http://example.com".'; + + $errorWithMessage = <<createMock(ResponseInterface::class); $response @@ -47,12 +56,7 @@ public function testParseError(string $mimeType, string $json): void $e = new TestException($response); $this->assertSame(400, $e->getCode()); - $this->assertSame(<<getMessage()); + $this->assertSame($expectedMessage, $e->getMessage()); } } diff --git a/src/Symfony/Component/HttpClient/composer.json b/src/Symfony/Component/HttpClient/composer.json index b841695c0498..4d4164000244 100644 --- a/src/Symfony/Component/HttpClient/composer.json +++ b/src/Symfony/Component/HttpClient/composer.json @@ -23,7 +23,7 @@ "require": { "php": ">=7.2.5", "psr/log": "^1.0", - "symfony/http-client-contracts": "^2.1.1", + "symfony/http-client-contracts": "^2.2", "symfony/polyfill-php73": "^1.11", "symfony/polyfill-php80": "^1.15", "symfony/service-contracts": "^1.0|^2" diff --git a/src/Symfony/Component/HttpFoundation/File/UploadedFile.php b/src/Symfony/Component/HttpFoundation/File/UploadedFile.php index aa5cb9b1b3df..f490f8f7f32f 100644 --- a/src/Symfony/Component/HttpFoundation/File/UploadedFile.php +++ b/src/Symfony/Component/HttpFoundation/File/UploadedFile.php @@ -64,10 +64,10 @@ public function __construct(string $path, string $originalName, string $mimeType { $this->originalName = $this->getName($originalName); $this->mimeType = $mimeType ?: 'application/octet-stream'; - $this->error = $error ?: UPLOAD_ERR_OK; + $this->error = $error ?: \UPLOAD_ERR_OK; $this->test = $test; - parent::__construct($path, UPLOAD_ERR_OK === $this->error); + parent::__construct($path, \UPLOAD_ERR_OK === $this->error); } /** @@ -93,7 +93,7 @@ public function getClientOriginalName() */ public function getClientOriginalExtension() { - return pathinfo($this->originalName, PATHINFO_EXTENSION); + return pathinfo($this->originalName, \PATHINFO_EXTENSION); } /** @@ -160,7 +160,7 @@ public function getError() */ public function isValid() { - $isOk = UPLOAD_ERR_OK === $this->error; + $isOk = \UPLOAD_ERR_OK === $this->error; return $this->test ? $isOk : $isOk && is_uploaded_file($this->getPathname()); } @@ -194,19 +194,19 @@ public function move(string $directory, string $name = null) } switch ($this->error) { - case UPLOAD_ERR_INI_SIZE: + case \UPLOAD_ERR_INI_SIZE: throw new IniSizeFileException($this->getErrorMessage()); - case UPLOAD_ERR_FORM_SIZE: + case \UPLOAD_ERR_FORM_SIZE: throw new FormSizeFileException($this->getErrorMessage()); - case UPLOAD_ERR_PARTIAL: + case \UPLOAD_ERR_PARTIAL: throw new PartialFileException($this->getErrorMessage()); - case UPLOAD_ERR_NO_FILE: + case \UPLOAD_ERR_NO_FILE: throw new NoFileException($this->getErrorMessage()); - case UPLOAD_ERR_CANT_WRITE: + case \UPLOAD_ERR_CANT_WRITE: throw new CannotWriteFileException($this->getErrorMessage()); - case UPLOAD_ERR_NO_TMP_DIR: + case \UPLOAD_ERR_NO_TMP_DIR: throw new NoTmpDirFileException($this->getErrorMessage()); - case UPLOAD_ERR_EXTENSION: + case \UPLOAD_ERR_EXTENSION: throw new ExtensionFileException($this->getErrorMessage()); } @@ -223,7 +223,7 @@ public static function getMaxFilesize() $sizePostMax = self::parseFilesize(ini_get('post_max_size')); $sizeUploadMax = self::parseFilesize(ini_get('upload_max_filesize')); - return min($sizePostMax ?: PHP_INT_MAX, $sizeUploadMax ?: PHP_INT_MAX); + return min($sizePostMax ?: \PHP_INT_MAX, $sizeUploadMax ?: \PHP_INT_MAX); } /** @@ -267,17 +267,17 @@ private static function parseFilesize($size): int public function getErrorMessage() { static $errors = [ - UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d KiB).', - UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.', - UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.', - UPLOAD_ERR_NO_FILE => 'No file was uploaded.', - UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.', - UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.', - UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.', + \UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d KiB).', + \UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.', + \UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.', + \UPLOAD_ERR_NO_FILE => 'No file was uploaded.', + \UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.', + \UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.', + \UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.', ]; $errorCode = $this->error; - $maxFilesize = UPLOAD_ERR_INI_SIZE === $errorCode ? self::getMaxFilesize() / 1024 : 0; + $maxFilesize = \UPLOAD_ERR_INI_SIZE === $errorCode ? self::getMaxFilesize() / 1024 : 0; $message = isset($errors[$errorCode]) ? $errors[$errorCode] : 'The file "%s" was not uploaded due to an unknown error.'; return sprintf($message, $this->getClientOriginalName(), $maxFilesize); diff --git a/src/Symfony/Component/HttpFoundation/FileBag.php b/src/Symfony/Component/HttpFoundation/FileBag.php index 5edd372b6297..67784087ecfb 100644 --- a/src/Symfony/Component/HttpFoundation/FileBag.php +++ b/src/Symfony/Component/HttpFoundation/FileBag.php @@ -81,7 +81,7 @@ protected function convertFileInformation($file) sort($keys); if ($keys == self::$fileKeys) { - if (UPLOAD_ERR_NO_FILE == $file['error']) { + if (\UPLOAD_ERR_NO_FILE == $file['error']) { $file = null; } else { $file = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['error'], false); diff --git a/src/Symfony/Component/HttpFoundation/HeaderBag.php b/src/Symfony/Component/HttpFoundation/HeaderBag.php index d45d95e096f1..db0f4836512a 100644 --- a/src/Symfony/Component/HttpFoundation/HeaderBag.php +++ b/src/Symfony/Component/HttpFoundation/HeaderBag.php @@ -198,7 +198,7 @@ public function getDate(string $key, \DateTime $default = null) return $default; } - if (false === $date = \DateTime::createFromFormat(DATE_RFC2822, $value)) { + if (false === $date = \DateTime::createFromFormat(\DATE_RFC2822, $value)) { throw new \RuntimeException(sprintf('The "%s" HTTP header is not parseable (%s).', $key, $value)); } diff --git a/src/Symfony/Component/HttpFoundation/HeaderUtils.php b/src/Symfony/Component/HttpFoundation/HeaderUtils.php index 5866e3b2b53e..f4add930eb22 100644 --- a/src/Symfony/Component/HttpFoundation/HeaderUtils.php +++ b/src/Symfony/Component/HttpFoundation/HeaderUtils.php @@ -62,7 +62,7 @@ public static function split(string $header, string $separators): array \s* (?['.$quotedSeparators.']) \s* - /x', trim($header), $matches, PREG_SET_ORDER); + /x', trim($header), $matches, \PREG_SET_ORDER); return self::groupParts($matches, $separators); } diff --git a/src/Symfony/Component/HttpFoundation/InputBag.php b/src/Symfony/Component/HttpFoundation/InputBag.php index c83d63d6d520..a45c9529ed5f 100644 --- a/src/Symfony/Component/HttpFoundation/InputBag.php +++ b/src/Symfony/Component/HttpFoundation/InputBag.php @@ -86,7 +86,7 @@ public function set(string $key, $value) /** * {@inheritdoc} */ - public function filter(string $key, $default = null, int $filter = FILTER_DEFAULT, $options = []) + public function filter(string $key, $default = null, int $filter = \FILTER_DEFAULT, $options = []) { $value = $this->has($key) ? $this->all()[$key] : $default; @@ -95,11 +95,11 @@ public function filter(string $key, $default = null, int $filter = FILTER_DEFAUL $options = ['flags' => $options]; } - if (\is_array($value) && !(($options['flags'] ?? 0) & (FILTER_REQUIRE_ARRAY | FILTER_FORCE_ARRAY))) { + if (\is_array($value) && !(($options['flags'] ?? 0) & (\FILTER_REQUIRE_ARRAY | \FILTER_FORCE_ARRAY))) { trigger_deprecation('symfony/http-foundation', '5.1', 'Filtering an array value with "%s()" without passing the FILTER_REQUIRE_ARRAY or FILTER_FORCE_ARRAY flag is deprecated', __METHOD__); if (!isset($options['flags'])) { - $options['flags'] = FILTER_REQUIRE_ARRAY; + $options['flags'] = \FILTER_REQUIRE_ARRAY; } } diff --git a/src/Symfony/Component/HttpFoundation/IpUtils.php b/src/Symfony/Component/HttpFoundation/IpUtils.php index 80c5a950c932..0599ce553ef5 100644 --- a/src/Symfony/Component/HttpFoundation/IpUtils.php +++ b/src/Symfony/Component/HttpFoundation/IpUtils.php @@ -66,7 +66,7 @@ public static function checkIp4(?string $requestIp, string $ip) return self::$checkedIps[$cacheKey]; } - if (!filter_var($requestIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + if (!filter_var($requestIp, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) { return self::$checkedIps[$cacheKey] = false; } @@ -74,7 +74,7 @@ public static function checkIp4(?string $requestIp, string $ip) list($address, $netmask) = explode('/', $ip, 2); if ('0' === $netmask) { - return self::$checkedIps[$cacheKey] = filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); + return self::$checkedIps[$cacheKey] = filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4); } if ($netmask < 0 || $netmask > 32) { diff --git a/src/Symfony/Component/HttpFoundation/JsonResponse.php b/src/Symfony/Component/HttpFoundation/JsonResponse.php index b361d0852d50..cf15c59a58f2 100644 --- a/src/Symfony/Component/HttpFoundation/JsonResponse.php +++ b/src/Symfony/Component/HttpFoundation/JsonResponse.php @@ -161,11 +161,11 @@ public function setData($data = []) throw $e; } - if (\PHP_VERSION_ID >= 70300 && (JSON_THROW_ON_ERROR & $this->encodingOptions)) { + if (\PHP_VERSION_ID >= 70300 && (\JSON_THROW_ON_ERROR & $this->encodingOptions)) { return $this->setJson($data); } - if (JSON_ERROR_NONE !== json_last_error()) { + if (\JSON_ERROR_NONE !== json_last_error()) { throw new \InvalidArgumentException(json_last_error_msg()); } diff --git a/src/Symfony/Component/HttpFoundation/ParameterBag.php b/src/Symfony/Component/HttpFoundation/ParameterBag.php index dc45bec4d505..1de54859a188 100644 --- a/src/Symfony/Component/HttpFoundation/ParameterBag.php +++ b/src/Symfony/Component/HttpFoundation/ParameterBag.php @@ -146,7 +146,7 @@ public function getAlnum(string $key, string $default = '') public function getDigits(string $key, string $default = '') { // we need to remove - and + because they're allowed in the filter - return str_replace(['-', '+'], '', $this->filter($key, $default, FILTER_SANITIZE_NUMBER_INT)); + return str_replace(['-', '+'], '', $this->filter($key, $default, \FILTER_SANITIZE_NUMBER_INT)); } /** @@ -166,7 +166,7 @@ public function getInt(string $key, int $default = 0) */ public function getBoolean(string $key, bool $default = false) { - return $this->filter($key, $default, FILTER_VALIDATE_BOOLEAN); + return $this->filter($key, $default, \FILTER_VALIDATE_BOOLEAN); } /** @@ -180,7 +180,7 @@ public function getBoolean(string $key, bool $default = false) * * @return mixed */ - public function filter(string $key, $default = null, int $filter = FILTER_DEFAULT, $options = []) + public function filter(string $key, $default = null, int $filter = \FILTER_DEFAULT, $options = []) { $value = $this->get($key, $default); @@ -191,7 +191,7 @@ public function filter(string $key, $default = null, int $filter = FILTER_DEFAUL // Add a convenience check for arrays. if (\is_array($value) && !isset($options['flags'])) { - $options['flags'] = FILTER_REQUIRE_ARRAY; + $options['flags'] = \FILTER_REQUIRE_ARRAY; } return filter_var($value, $filter, $options); diff --git a/src/Symfony/Component/HttpFoundation/RedirectResponse.php b/src/Symfony/Component/HttpFoundation/RedirectResponse.php index 0dfb80c03981..c00548348fde 100644 --- a/src/Symfony/Component/HttpFoundation/RedirectResponse.php +++ b/src/Symfony/Component/HttpFoundation/RedirectResponse.php @@ -42,7 +42,7 @@ public function __construct(string $url, int $status = 302, array $headers = []) throw new \InvalidArgumentException(sprintf('The HTTP status code is not a redirect ("%s" given).', $status)); } - if (301 == $status && !\array_key_exists('cache-control', array_change_key_case($headers, CASE_LOWER))) { + if (301 == $status && !\array_key_exists('cache-control', array_change_key_case($headers, \CASE_LOWER))) { $this->headers->remove('cache-control'); } } @@ -100,7 +100,7 @@ public function setTargetUrl(string $url) Redirecting to %1$s. -', htmlspecialchars($url, ENT_QUOTES, 'UTF-8'))); +', htmlspecialchars($url, \ENT_QUOTES, 'UTF-8'))); $this->headers->set('Location', $url); diff --git a/src/Symfony/Component/HttpFoundation/Request.php b/src/Symfony/Component/HttpFoundation/Request.php index e737a7e58c83..60fe3bf55220 100644 --- a/src/Symfony/Component/HttpFoundation/Request.php +++ b/src/Symfony/Component/HttpFoundation/Request.php @@ -517,7 +517,7 @@ public function __toString() throw $e; } - return trigger_error($e, E_USER_ERROR); + return trigger_error($e, \E_USER_ERROR); } $cookieHeader = ''; @@ -663,7 +663,7 @@ public static function normalizeQueryString(?string $qs) parse_str($qs, $qs); ksort($qs); - return http_build_query($qs, '', '&', PHP_QUERY_RFC3986); + return http_build_query($qs, '', '&', \PHP_QUERY_RFC3986); } /** @@ -1554,7 +1554,7 @@ public function getContent(bool $asResource = false) */ public function getETags() { - return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY); + return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, \PREG_SPLIT_NO_EMPTY); } /** @@ -2076,7 +2076,7 @@ private function normalizeAndFilterClientIps(array $clientIps, string $ip): arra $clientIps[$key] = $clientIp = substr($clientIp, 1, $i - 1); } - if (!filter_var($clientIp, FILTER_VALIDATE_IP)) { + if (!filter_var($clientIp, \FILTER_VALIDATE_IP)) { unset($clientIps[$key]); continue; diff --git a/src/Symfony/Component/HttpFoundation/Response.php b/src/Symfony/Component/HttpFoundation/Response.php index ddfd1826e46c..df6565245640 100644 --- a/src/Symfony/Component/HttpFoundation/Response.php +++ b/src/Symfony/Component/HttpFoundation/Response.php @@ -1228,7 +1228,7 @@ public static function closeOutputBuffers(int $targetLevel, bool $flush): void { $status = ob_get_status(true); $level = \count($status); - $flags = PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE); + $flags = \PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? \PHP_OUTPUT_HANDLER_FLUSHABLE : \PHP_OUTPUT_HANDLER_CLEANABLE); while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) { if ($flush) { diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/AbstractSessionHandler.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/AbstractSessionHandler.php index 15b3ba0df4d2..0bb236156d6f 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/AbstractSessionHandler.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/AbstractSessionHandler.php @@ -66,7 +66,7 @@ public function validateId($sessionId) if (\PHP_VERSION_ID < 70317 || (70400 <= \PHP_VERSION_ID && \PHP_VERSION_ID < 70405)) { // work around https://bugs.php.net/79413 - foreach (debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) as $frame) { + foreach (debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS) as $frame) { if (!isset($frame['class']) && isset($frame['function']) && \in_array($frame['function'], ['session_regenerate_id', 'session_create_id'], true)) { return '' === $this->prefetchData; } @@ -121,7 +121,7 @@ public function write($sessionId, $data) */ public function destroy($sessionId) { - if (!headers_sent() && filter_var(ini_get('session.use_cookies'), FILTER_VALIDATE_BOOLEAN)) { + if (!headers_sent() && filter_var(ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOLEAN)) { if (!$this->sessionName) { throw new \LogicException(sprintf('Session name cannot be empty, did you forget to call "parent::open()" in "%s"?.', static::class)); } @@ -136,7 +136,7 @@ public function destroy($sessionId) */ if (null === $cookie || isset($_COOKIE[$this->sessionName])) { if (\PHP_VERSION_ID < 70300) { - setcookie($this->sessionName, '', 0, ini_get('session.cookie_path'), ini_get('session.cookie_domain'), filter_var(ini_get('session.cookie_secure'), FILTER_VALIDATE_BOOLEAN), filter_var(ini_get('session.cookie_httponly'), FILTER_VALIDATE_BOOLEAN)); + setcookie($this->sessionName, '', 0, ini_get('session.cookie_path'), ini_get('session.cookie_domain'), filter_var(ini_get('session.cookie_secure'), \FILTER_VALIDATE_BOOLEAN), filter_var(ini_get('session.cookie_httponly'), \FILTER_VALIDATE_BOOLEAN)); } else { $params = session_get_cookie_params(); unset($params['lifetime']); diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php index a301e9f054b6..92174485c704 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php @@ -643,7 +643,7 @@ protected function doRead(string $sessionId) throw new \RuntimeException('Failed to read session: INSERT reported a duplicate id but next SELECT did not return any data.'); } - if (!filter_var(ini_get('session.use_strict_mode'), FILTER_VALIDATE_BOOLEAN) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) { + if (!filter_var(ini_get('session.use_strict_mode'), \FILTER_VALIDATE_BOOLEAN) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) { // In strict mode, session fixation is not possible: new sessions always start with a unique // random id, so that concurrency is not possible and this code path can be skipped. // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php index 2446b3695893..bb34d724b36d 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php @@ -144,11 +144,11 @@ public function start() return true; } - if (PHP_SESSION_ACTIVE === session_status()) { + if (\PHP_SESSION_ACTIVE === session_status()) { throw new \RuntimeException('Failed to start the session: already started by PHP.'); } - if (filter_var(ini_get('session.use_cookies'), FILTER_VALIDATE_BOOLEAN) && headers_sent($file, $line)) { + if (filter_var(ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOLEAN) && headers_sent($file, $line)) { throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line)); } @@ -207,7 +207,7 @@ public function setName(string $name) public function regenerate(bool $destroy = false, int $lifetime = null) { // Cannot regenerate the session ID for non-active sessions. - if (PHP_SESSION_ACTIVE !== session_status()) { + if (\PHP_SESSION_ACTIVE !== session_status()) { return false; } @@ -256,7 +256,7 @@ public function save() // Register error handler to add information about the current save handler $previousHandler = set_error_handler(function ($type, $msg, $file, $line) use (&$previousHandler) { - if (E_WARNING === $type && 0 === strpos($msg, 'session_write_close():')) { + if (\E_WARNING === $type && 0 === strpos($msg, 'session_write_close():')) { $handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler; $msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', \get_class($handler)); } @@ -365,7 +365,7 @@ public function isStarted() */ public function setOptions(array $options) { - if (headers_sent() || PHP_SESSION_ACTIVE === session_status()) { + if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) { return; } @@ -430,7 +430,7 @@ public function setSaveHandler($saveHandler = null) } $this->saveHandler = $saveHandler; - if (headers_sent() || PHP_SESSION_ACTIVE === session_status()) { + if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) { return; } diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Proxy/AbstractProxy.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Proxy/AbstractProxy.php index e7be22c01981..edd04dff80b4 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/Proxy/AbstractProxy.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Proxy/AbstractProxy.php @@ -65,7 +65,7 @@ public function isWrapper() */ public function isActive() { - return PHP_SESSION_ACTIVE === session_status(); + return \PHP_SESSION_ACTIVE === session_status(); } /** diff --git a/src/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.php b/src/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.php index 86fa24e454ea..5565b0384fb3 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.php @@ -48,7 +48,7 @@ public function testFileUploadsWithNoMimeType() __DIR__.'/Fixtures/test.gif', 'original.gif', null, - UPLOAD_ERR_OK + \UPLOAD_ERR_OK ); $this->assertEquals('application/octet-stream', $file->getClientMimeType()); @@ -64,7 +64,7 @@ public function testFileUploadsWithUnknownMimeType() __DIR__.'/Fixtures/.unknownextension', 'original.gif', null, - UPLOAD_ERR_OK + \UPLOAD_ERR_OK ); $this->assertEquals('application/octet-stream', $file->getClientMimeType()); @@ -115,7 +115,7 @@ public function testErrorIsOkByDefault() null ); - $this->assertEquals(UPLOAD_ERR_OK, $file->getError()); + $this->assertEquals(\UPLOAD_ERR_OK, $file->getError()); } public function testGetClientOriginalName() @@ -149,7 +149,7 @@ public function testMoveLocalFileIsNotAllowed() __DIR__.'/Fixtures/test.gif', 'original.gif', 'image/gif', - UPLOAD_ERR_OK + \UPLOAD_ERR_OK ); $file->move(__DIR__.'/Fixtures/directory'); @@ -157,7 +157,7 @@ public function testMoveLocalFileIsNotAllowed() public function failedUploadedFile() { - foreach ([UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_PARTIAL, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_EXTENSION, -1] as $error) { + foreach ([\UPLOAD_ERR_INI_SIZE, \UPLOAD_ERR_FORM_SIZE, \UPLOAD_ERR_PARTIAL, \UPLOAD_ERR_NO_FILE, \UPLOAD_ERR_CANT_WRITE, \UPLOAD_ERR_NO_TMP_DIR, \UPLOAD_ERR_EXTENSION, -1] as $error) { yield [new UploadedFile( __DIR__.'/Fixtures/test.gif', 'original.gif', @@ -173,25 +173,25 @@ public function failedUploadedFile() public function testMoveFailed(UploadedFile $file) { switch ($file->getError()) { - case UPLOAD_ERR_INI_SIZE: + case \UPLOAD_ERR_INI_SIZE: $exceptionClass = IniSizeFileException::class; break; - case UPLOAD_ERR_FORM_SIZE: + case \UPLOAD_ERR_FORM_SIZE: $exceptionClass = FormSizeFileException::class; break; - case UPLOAD_ERR_PARTIAL: + case \UPLOAD_ERR_PARTIAL: $exceptionClass = PartialFileException::class; break; - case UPLOAD_ERR_NO_FILE: + case \UPLOAD_ERR_NO_FILE: $exceptionClass = NoFileException::class; break; - case UPLOAD_ERR_CANT_WRITE: + case \UPLOAD_ERR_CANT_WRITE: $exceptionClass = CannotWriteFileException::class; break; - case UPLOAD_ERR_NO_TMP_DIR: + case \UPLOAD_ERR_NO_TMP_DIR: $exceptionClass = NoTmpDirFileException::class; break; - case UPLOAD_ERR_EXTENSION: + case \UPLOAD_ERR_EXTENSION: $exceptionClass = ExtensionFileException::class; break; default: @@ -216,7 +216,7 @@ public function testMoveLocalFileIsAllowedInTestMode() $path, 'original.gif', 'image/gif', - UPLOAD_ERR_OK, + \UPLOAD_ERR_OK, true ); @@ -275,7 +275,7 @@ public function testIsValid() __DIR__.'/Fixtures/test.gif', 'original.gif', null, - UPLOAD_ERR_OK, + \UPLOAD_ERR_OK, true ); @@ -300,11 +300,11 @@ public function testIsInvalidOnUploadError($error) public function uploadedFileErrorProvider() { return [ - [UPLOAD_ERR_INI_SIZE], - [UPLOAD_ERR_FORM_SIZE], - [UPLOAD_ERR_PARTIAL], - [UPLOAD_ERR_NO_TMP_DIR], - [UPLOAD_ERR_EXTENSION], + [\UPLOAD_ERR_INI_SIZE], + [\UPLOAD_ERR_FORM_SIZE], + [\UPLOAD_ERR_PARTIAL], + [\UPLOAD_ERR_NO_TMP_DIR], + [\UPLOAD_ERR_EXTENSION], ]; } @@ -314,7 +314,7 @@ public function testIsInvalidIfNotHttpUpload() __DIR__.'/Fixtures/test.gif', 'original.gif', null, - UPLOAD_ERR_OK + \UPLOAD_ERR_OK ); $this->assertFalse($file->isValid()); @@ -328,9 +328,9 @@ public function testGetMaxFilesize() $this->assertGreaterThan(0, $size); if (0 === (int) ini_get('post_max_size') && 0 === (int) ini_get('upload_max_filesize')) { - $this->assertSame(PHP_INT_MAX, $size); + $this->assertSame(\PHP_INT_MAX, $size); } else { - $this->assertLessThan(PHP_INT_MAX, $size); + $this->assertLessThan(\PHP_INT_MAX, $size); } } } diff --git a/src/Symfony/Component/HttpFoundation/Tests/FileBagTest.php b/src/Symfony/Component/HttpFoundation/Tests/FileBagTest.php index bde664194b85..ec6ae402481f 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/FileBagTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/FileBagTest.php @@ -51,7 +51,7 @@ public function testShouldSetEmptyUploadedFilesToNull() 'name' => '', 'type' => '', 'tmp_name' => '', - 'error' => UPLOAD_ERR_NO_FILE, + 'error' => \UPLOAD_ERR_NO_FILE, 'size' => 0, ]]); @@ -64,7 +64,7 @@ public function testShouldRemoveEmptyUploadedFilesForMultiUpload() 'name' => [''], 'type' => [''], 'tmp_name' => [''], - 'error' => [UPLOAD_ERR_NO_FILE], + 'error' => [\UPLOAD_ERR_NO_FILE], 'size' => [0], ]]); @@ -77,7 +77,7 @@ public function testShouldNotRemoveEmptyUploadedFilesForAssociativeArray() 'name' => ['file1' => ''], 'type' => ['file1' => ''], 'tmp_name' => ['file1' => ''], - 'error' => ['file1' => UPLOAD_ERR_NO_FILE], + 'error' => ['file1' => \UPLOAD_ERR_NO_FILE], 'size' => ['file1' => 0], ]]); diff --git a/src/Symfony/Component/HttpFoundation/Tests/InputBagTest.php b/src/Symfony/Component/HttpFoundation/Tests/InputBagTest.php index 1fb4660ed7a7..870057e41bdb 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/InputBagTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/InputBagTest.php @@ -41,7 +41,7 @@ public function testFilterArray() 'foo' => ['12', '8'], ]); - $result = $bag->filter('foo', null, FILTER_VALIDATE_INT, FILTER_FORCE_ARRAY); + $result = $bag->filter('foo', null, \FILTER_VALIDATE_INT, \FILTER_FORCE_ARRAY); $this->assertSame([12, 8], $result); } @@ -82,6 +82,6 @@ public function testFilterArrayWithoutArrayFlagIsDeprecated() { $bag = new InputBag(['foo' => ['bar', 'baz']]); $this->expectDeprecation('Since symfony/http-foundation 5.1: Filtering an array value with "Symfony\Component\HttpFoundation\InputBag::filter()" without passing the FILTER_REQUIRE_ARRAY or FILTER_FORCE_ARRAY flag is deprecated'); - $bag->filter('foo', FILTER_VALIDATE_INT); + $bag->filter('foo', \FILTER_VALIDATE_INT); } } diff --git a/src/Symfony/Component/HttpFoundation/Tests/JsonResponseTest.php b/src/Symfony/Component/HttpFoundation/Tests/JsonResponseTest.php index ca9cfb1ceec0..702f4c7bea37 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/JsonResponseTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/JsonResponseTest.php @@ -213,7 +213,7 @@ public function testGetEncodingOptions() { $response = new JsonResponse(); - $this->assertEquals(JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT, $response->getEncodingOptions()); + $this->assertEquals(\JSON_HEX_TAG | \JSON_HEX_APOS | \JSON_HEX_AMP | \JSON_HEX_QUOT, $response->getEncodingOptions()); } public function testSetEncodingOptions() @@ -223,7 +223,7 @@ public function testSetEncodingOptions() $this->assertEquals('[[1,2,3]]', $response->getContent()); - $response->setEncodingOptions(JSON_FORCE_OBJECT); + $response->setEncodingOptions(\JSON_FORCE_OBJECT); $this->assertEquals('{"0":{"0":1,"1":2,"2":3}}', $response->getContent()); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/ParameterBagTest.php b/src/Symfony/Component/HttpFoundation/Tests/ParameterBagTest.php index d7cc3ca249eb..e5f436e8e700 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/ParameterBagTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/ParameterBagTest.php @@ -154,22 +154,22 @@ public function testFilter() $this->assertEmpty($bag->filter('nokey'), '->filter() should return empty by default if no key is found'); - $this->assertEquals('0123', $bag->filter('digits', '', FILTER_SANITIZE_NUMBER_INT), '->filter() gets a value of parameter as integer filtering out invalid characters'); + $this->assertEquals('0123', $bag->filter('digits', '', \FILTER_SANITIZE_NUMBER_INT), '->filter() gets a value of parameter as integer filtering out invalid characters'); - $this->assertEquals('example@example.com', $bag->filter('email', '', FILTER_VALIDATE_EMAIL), '->filter() gets a value of parameter as email'); + $this->assertEquals('example@example.com', $bag->filter('email', '', \FILTER_VALIDATE_EMAIL), '->filter() gets a value of parameter as email'); - $this->assertEquals('http://example.com/foo', $bag->filter('url', '', FILTER_VALIDATE_URL, ['flags' => FILTER_FLAG_PATH_REQUIRED]), '->filter() gets a value of parameter as URL with a path'); + $this->assertEquals('http://example.com/foo', $bag->filter('url', '', \FILTER_VALIDATE_URL, ['flags' => \FILTER_FLAG_PATH_REQUIRED]), '->filter() gets a value of parameter as URL with a path'); // This test is repeated for code-coverage - $this->assertEquals('http://example.com/foo', $bag->filter('url', '', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED), '->filter() gets a value of parameter as URL with a path'); + $this->assertEquals('http://example.com/foo', $bag->filter('url', '', \FILTER_VALIDATE_URL, \FILTER_FLAG_PATH_REQUIRED), '->filter() gets a value of parameter as URL with a path'); - $this->assertFalse($bag->filter('dec', '', FILTER_VALIDATE_INT, [ - 'flags' => FILTER_FLAG_ALLOW_HEX, + $this->assertFalse($bag->filter('dec', '', \FILTER_VALIDATE_INT, [ + 'flags' => \FILTER_FLAG_ALLOW_HEX, 'options' => ['min_range' => 1, 'max_range' => 0xff], ]), '->filter() gets a value of parameter as integer between boundaries'); - $this->assertFalse($bag->filter('hex', '', FILTER_VALIDATE_INT, [ - 'flags' => FILTER_FLAG_ALLOW_HEX, + $this->assertFalse($bag->filter('hex', '', \FILTER_VALIDATE_INT, [ + 'flags' => \FILTER_FLAG_ALLOW_HEX, 'options' => ['min_range' => 1, 'max_range' => 0xff], ]), '->filter() gets a value of parameter as integer between boundaries'); diff --git a/src/Symfony/Component/HttpFoundation/Tests/ResponseFunctionalTest.php b/src/Symfony/Component/HttpFoundation/Tests/ResponseFunctionalTest.php index 849a1395d330..e94f4defc497 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/ResponseFunctionalTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/ResponseFunctionalTest.php @@ -42,6 +42,10 @@ public static function tearDownAfterClass(): void */ public function testCookie($fixture) { + if (\PHP_VERSION_ID >= 80000 && 'cookie_max_age' === $fixture) { + $this->markTestSkipped('This fixture produces a fatal error on PHP 8.'); + } + $result = file_get_contents(sprintf('http://localhost:8054/%s.php', $fixture)); $this->assertStringMatchesFormatFile(__DIR__.sprintf('/Fixtures/response-functional/%s.expected', $fixture), $result); } @@ -49,7 +53,7 @@ public function testCookie($fixture) public function provideCookie() { foreach (glob(__DIR__.'/Fixtures/response-functional/*.php') as $file) { - yield [pathinfo($file, PATHINFO_FILENAME)]; + yield [pathinfo($file, \PATHINFO_FILENAME)]; } } } diff --git a/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php b/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php index 5fcbeee2e97c..2fbbb5bd4f57 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php @@ -257,7 +257,7 @@ public function testIsNotModifiedIfModifiedSinceAndEtagWithoutLastModified() public function testIsValidateable() { - $response = new Response('', 200, ['Last-Modified' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)]); + $response = new Response('', 200, ['Last-Modified' => $this->createDateTimeOneHourAgo()->format(\DATE_RFC2822)]); $this->assertTrue($response->isValidateable(), '->isValidateable() returns true if Last-Modified is present'); $response = new Response('', 200, ['ETag' => '"12345"']); @@ -270,7 +270,7 @@ public function testIsValidateable() public function testGetDate() { $oneHourAgo = $this->createDateTimeOneHourAgo(); - $response = new Response('', 200, ['Date' => $oneHourAgo->format(DATE_RFC2822)]); + $response = new Response('', 200, ['Date' => $oneHourAgo->format(\DATE_RFC2822)]); $date = $response->getDate(); $this->assertEquals($oneHourAgo->getTimestamp(), $date->getTimestamp(), '->getDate() returns the Date header if present'); @@ -278,9 +278,9 @@ public function testGetDate() $date = $response->getDate(); $this->assertEquals(time(), $date->getTimestamp(), '->getDate() returns the current Date if no Date header present'); - $response = new Response('', 200, ['Date' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)]); + $response = new Response('', 200, ['Date' => $this->createDateTimeOneHourAgo()->format(\DATE_RFC2822)]); $now = $this->createDateTimeNow(); - $response->headers->set('Date', $now->format(DATE_RFC2822)); + $response->headers->set('Date', $now->format(\DATE_RFC2822)); $date = $response->getDate(); $this->assertEquals($now->getTimestamp(), $date->getTimestamp(), '->getDate() returns the date when the header has been modified'); @@ -303,7 +303,7 @@ public function testGetMaxAge() $response = new Response(); $response->headers->set('Cache-Control', 'must-revalidate'); - $response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822)); + $response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(\DATE_RFC2822)); $this->assertEquals(3600, $response->getMaxAge(), '->getMaxAge() falls back to Expires when no max-age or s-maxage directive present'); $response = new Response(); @@ -368,7 +368,7 @@ public function testExpire() $this->assertNull($response->headers->get('Age'), '->expire() does not set the Age when the response is expired'); $response = new Response(); - $response->headers->set('Expires', date(DATE_RFC2822, time() + 600)); + $response->headers->set('Expires', date(\DATE_RFC2822, time() + 600)); $response->expire(); $this->assertNull($response->headers->get('Expires'), '->expire() removes the Expires header when the response is fresh'); } @@ -385,15 +385,15 @@ public function testGetTtl() $this->assertNull($response->getTtl(), '->getTtl() returns null when no Expires or Cache-Control headers are present'); $response = new Response(); - $response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822)); + $response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(\DATE_RFC2822)); $this->assertEquals(3600, $response->getTtl(), '->getTtl() uses the Expires header when no max-age is present'); $response = new Response(); - $response->headers->set('Expires', $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)); + $response->headers->set('Expires', $this->createDateTimeOneHourAgo()->format(\DATE_RFC2822)); $this->assertLessThan(0, $response->getTtl(), '->getTtl() returns negative values when Expires is in past'); $response = new Response(); - $response->headers->set('Expires', $response->getDate()->format(DATE_RFC2822)); + $response->headers->set('Expires', $response->getDate()->format(\DATE_RFC2822)); $response->headers->set('Age', 0); $this->assertSame(0, $response->getTtl(), '->getTtl() correctly handles zero'); diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php index b25b68bbb370..4a045f2ad231 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php @@ -52,7 +52,7 @@ public function testSession($fixture) public function provideSession() { foreach (glob(__DIR__.'/Fixtures/*.php') as $file) { - yield [pathinfo($file, PATHINFO_FILENAME)]; + yield [pathinfo($file, \PATHINFO_FILENAME)]; } } } diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index 03796e66e793..6042b88d27a1 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -147,7 +147,7 @@ public function testReadConvertsStreamToString() public function testReadLockedConvertsStreamToString() { - if (filter_var(ini_get('session.use_strict_mode'), FILTER_VALIDATE_BOOLEAN)) { + if (filter_var(ini_get('session.use_strict_mode'), \FILTER_VALIDATE_BOOLEAN)) { $this->markTestSkipped('Strict mode needs no locking for new sessions.'); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php index 76cd0fcf4269..4f7b37b1f304 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php @@ -194,10 +194,6 @@ public function testCookieOptions() public function testSessionOptions() { - if (\defined('HHVM_VERSION')) { - $this->markTestSkipped('HHVM is not handled in this test case.'); - } - $options = [ 'url_rewriter.tags' => 'a=href', 'cache_expire' => '200', diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/PhpBridgeSessionStorageTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/PhpBridgeSessionStorageTest.php index b546b958e03d..472456b7204f 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/PhpBridgeSessionStorageTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/PhpBridgeSessionStorageTest.php @@ -61,12 +61,12 @@ public function testPhpSession() { $storage = $this->getStorage(); - $this->assertNotSame(PHP_SESSION_ACTIVE, session_status()); + $this->assertNotSame(\PHP_SESSION_ACTIVE, session_status()); $this->assertFalse($storage->isStarted()); session_start(); $this->assertTrue(isset($_SESSION)); - $this->assertSame(PHP_SESSION_ACTIVE, session_status()); + $this->assertSame(\PHP_SESSION_ACTIVE, session_status()); // PHP session might have started, but the storage driver has not, so false is correct here $this->assertFalse($storage->isStarted()); diff --git a/src/Symfony/Component/HttpKernel/CacheWarmer/CacheWarmerAggregate.php b/src/Symfony/Component/HttpKernel/CacheWarmer/CacheWarmerAggregate.php index f89b1cd7a0cd..30e82449b45c 100644 --- a/src/Symfony/Component/HttpKernel/CacheWarmer/CacheWarmerAggregate.php +++ b/src/Symfony/Component/HttpKernel/CacheWarmer/CacheWarmerAggregate.php @@ -53,7 +53,7 @@ public function warmUp(string $cacheDir) if ($collectDeprecations = $this->debug && !\defined('PHPUNIT_COMPOSER_INSTALL')) { $collectedLogs = []; $previousHandler = set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) { - if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) { + if (\E_USER_DEPRECATED !== $type && \E_DEPRECATED !== $type) { return $previousHandler ? $previousHandler($type, $message, $file, $line) : false; } @@ -63,7 +63,7 @@ public function warmUp(string $cacheDir) return null; } - $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3); + $backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 3); // Clean the trace by removing first frames added by the error handler itself. for ($i = 0; isset($backtrace[$i]); ++$i) { if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) { diff --git a/src/Symfony/Component/HttpKernel/DataCollector/ConfigDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/ConfigDataCollector.php index 0632f92a1822..ba0a3eec6e0c 100644 --- a/src/Symfony/Component/HttpKernel/DataCollector/ConfigDataCollector.php +++ b/src/Symfony/Component/HttpKernel/DataCollector/ConfigDataCollector.php @@ -48,13 +48,13 @@ public function collect(Request $request, Response $response, \Throwable $except 'symfony_state' => 'unknown', 'env' => isset($this->kernel) ? $this->kernel->getEnvironment() : 'n/a', 'debug' => isset($this->kernel) ? $this->kernel->isDebug() : 'n/a', - 'php_version' => PHP_VERSION, + 'php_version' => \PHP_VERSION, 'php_architecture' => \PHP_INT_SIZE * 8, 'php_intl_locale' => class_exists('Locale', false) && \Locale::getDefault() ? \Locale::getDefault() : 'n/a', 'php_timezone' => date_default_timezone_get(), 'xdebug_enabled' => \extension_loaded('xdebug'), - 'apcu_enabled' => \extension_loaded('apcu') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN), - 'zend_opcache_enabled' => \extension_loaded('Zend OPcache') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN), + 'apcu_enabled' => \extension_loaded('apcu') && filter_var(ini_get('apc.enabled'), \FILTER_VALIDATE_BOOLEAN), + 'zend_opcache_enabled' => \extension_loaded('Zend OPcache') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN), 'bundles' => [], 'sapi_name' => \PHP_SAPI, ]; diff --git a/src/Symfony/Component/HttpKernel/DataCollector/LoggerDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/LoggerDataCollector.php index 34c6dc4297ee..504319aea9f9 100644 --- a/src/Symfony/Component/HttpKernel/DataCollector/LoggerDataCollector.php +++ b/src/Symfony/Component/HttpKernel/DataCollector/LoggerDataCollector.php @@ -153,7 +153,7 @@ private function getContainerCompilerLogs(string $compilerLogsFilepath = null): } $logs = []; - foreach (file($compilerLogsFilepath, FILE_IGNORE_NEW_LINES) as $log) { + foreach (file($compilerLogsFilepath, \FILE_IGNORE_NEW_LINES) as $log) { $log = explode(': ', $log, 2); if (!isset($log[1]) || !preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)++$/', $log[0])) { $log = ['Unknown Compiler Pass', implode(': ', $log)]; @@ -226,7 +226,7 @@ private function isSilencedOrDeprecationErrorLog(array $log): bool return true; } - if ($exception instanceof \ErrorException && \in_array($exception->getSeverity(), [E_DEPRECATED, E_USER_DEPRECATED], true)) { + if ($exception instanceof \ErrorException && \in_array($exception->getSeverity(), [\E_DEPRECATED, \E_USER_DEPRECATED], true)) { return true; } diff --git a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php index b92518d8062b..da3fa419d624 100644 --- a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php +++ b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php @@ -64,8 +64,8 @@ public function collect(Request $request, Response $response, \Throwable $except if ($request->hasSession()) { $session = $request->getSession(); if ($session->isStarted()) { - $sessionMetadata['Created'] = date(DATE_RFC822, $session->getMetadataBag()->getCreated()); - $sessionMetadata['Last used'] = date(DATE_RFC822, $session->getMetadataBag()->getLastUsed()); + $sessionMetadata['Created'] = date(\DATE_RFC822, $session->getMetadataBag()->getCreated()); + $sessionMetadata['Last used'] = date(\DATE_RFC822, $session->getMetadataBag()->getLastUsed()); $sessionMetadata['Lifetime'] = $session->getMetadataBag()->getLifetime(); $sessionAttributes = $session->all(); $flashes = $session->getFlashBag()->peekAll(); @@ -261,7 +261,7 @@ public function getPrettyJson() { $decoded = json_decode($this->getContent()); - return JSON_ERROR_NONE === json_last_error() ? json_encode($decoded, JSON_PRETTY_PRINT) : null; + return \JSON_ERROR_NONE === json_last_error() ? json_encode($decoded, \JSON_PRETTY_PRINT) : null; } public function getContentType() diff --git a/src/Symfony/Component/HttpKernel/Debug/FileLinkFormatter.php b/src/Symfony/Component/HttpKernel/Debug/FileLinkFormatter.php index 74abb818626d..87672a9d192e 100644 --- a/src/Symfony/Component/HttpKernel/Debug/FileLinkFormatter.php +++ b/src/Symfony/Component/HttpKernel/Debug/FileLinkFormatter.php @@ -37,7 +37,7 @@ public function __construct($fileLinkFormat = null, RequestStack $requestStack = $fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format'); if ($fileLinkFormat && !\is_array($fileLinkFormat)) { $i = strpos($f = $fileLinkFormat, '&', max(strrpos($f, '%f'), strrpos($f, '%l'))) ?: \strlen($f); - $fileLinkFormat = [substr($f, 0, $i)] + preg_split('/&([^>]++)>/', substr($f, $i), -1, PREG_SPLIT_DELIM_CAPTURE); + $fileLinkFormat = [substr($f, 0, $i)] + preg_split('/&([^>]++)>/', substr($f, $i), -1, \PREG_SPLIT_DELIM_CAPTURE); } $this->fileLinkFormat = $fileLinkFormat; diff --git a/src/Symfony/Component/HttpKernel/DependencyInjection/RegisterControllerArgumentLocatorsPass.php b/src/Symfony/Component/HttpKernel/DependencyInjection/RegisterControllerArgumentLocatorsPass.php index 82d45a8dcf60..286f212f9a18 100644 --- a/src/Symfony/Component/HttpKernel/DependencyInjection/RegisterControllerArgumentLocatorsPass.php +++ b/src/Symfony/Component/HttpKernel/DependencyInjection/RegisterControllerArgumentLocatorsPass.php @@ -100,7 +100,7 @@ public function process(ContainerBuilder $container) } foreach (['action', 'argument', 'id'] as $k) { if (!isset($attributes[$k][0])) { - throw new InvalidArgumentException(sprintf('Missing "%s" attribute on tag "%s" %s for service "%s".', $k, $this->controllerTag, json_encode($attributes, JSON_UNESCAPED_UNICODE), $id)); + throw new InvalidArgumentException(sprintf('Missing "%s" attribute on tag "%s" %s for service "%s".', $k, $this->controllerTag, json_encode($attributes, \JSON_UNESCAPED_UNICODE), $id)); } } if (!isset($methods[$action = strtolower($attributes['action'])])) { diff --git a/src/Symfony/Component/HttpKernel/EventListener/DebugHandlersListener.php b/src/Symfony/Component/HttpKernel/EventListener/DebugHandlersListener.php index 44b1ddb1878b..6b677edd7ca6 100644 --- a/src/Symfony/Component/HttpKernel/EventListener/DebugHandlersListener.php +++ b/src/Symfony/Component/HttpKernel/EventListener/DebugHandlersListener.php @@ -49,12 +49,12 @@ class DebugHandlersListener implements EventSubscriberInterface * @param string|FileLinkFormatter|null $fileLinkFormat The format for links to source files * @param bool $scope Enables/disables scoping mode */ - public function __construct(callable $exceptionHandler = null, LoggerInterface $logger = null, $levels = E_ALL, ?int $throwAt = E_ALL, bool $scream = true, $fileLinkFormat = null, bool $scope = true, LoggerInterface $deprecationLogger = null) + public function __construct(callable $exceptionHandler = null, LoggerInterface $logger = null, $levels = \E_ALL, ?int $throwAt = \E_ALL, bool $scream = true, $fileLinkFormat = null, bool $scope = true, LoggerInterface $deprecationLogger = null) { $this->exceptionHandler = $exceptionHandler; $this->logger = $logger; - $this->levels = null === $levels ? E_ALL : $levels; - $this->throwAt = \is_int($throwAt) ? $throwAt : (null === $throwAt ? null : ($throwAt ? E_ALL : null)); + $this->levels = null === $levels ? \E_ALL : $levels; + $this->throwAt = \is_int($throwAt) ? $throwAt : (null === $throwAt ? null : ($throwAt ? \E_ALL : null)); $this->scream = $scream; $this->fileLinkFormat = $fileLinkFormat; $this->scope = $scope; @@ -94,7 +94,7 @@ public function configure(object $event = null) $handler->screamAt($levels); } if ($this->scope) { - $handler->scopeAt($levels & ~E_USER_DEPRECATED & ~E_DEPRECATED); + $handler->scopeAt($levels & ~\E_USER_DEPRECATED & ~\E_DEPRECATED); } else { $handler->scopeAt(0, true); } @@ -142,15 +142,15 @@ private function setDefaultLoggers(ErrorHandler $handler): void $levelsDeprecatedOnly = []; $levelsWithoutDeprecated = []; foreach ($this->levels as $type => $log) { - if (E_DEPRECATED == $type || E_USER_DEPRECATED == $type) { + if (\E_DEPRECATED == $type || \E_USER_DEPRECATED == $type) { $levelsDeprecatedOnly[$type] = $log; } else { $levelsWithoutDeprecated[$type] = $log; } } } else { - $levelsDeprecatedOnly = $this->levels & (E_DEPRECATED | E_USER_DEPRECATED); - $levelsWithoutDeprecated = $this->levels & ~E_DEPRECATED & ~E_USER_DEPRECATED; + $levelsDeprecatedOnly = $this->levels & (\E_DEPRECATED | \E_USER_DEPRECATED); + $levelsWithoutDeprecated = $this->levels & ~\E_DEPRECATED & ~\E_USER_DEPRECATED; } $defaultLoggerLevels = $this->levels; diff --git a/src/Symfony/Component/HttpKernel/Fragment/HIncludeFragmentRenderer.php b/src/Symfony/Component/HttpKernel/Fragment/HIncludeFragmentRenderer.php index 618859d0f9e0..634eabfba5e3 100644 --- a/src/Symfony/Component/HttpKernel/Fragment/HIncludeFragmentRenderer.php +++ b/src/Symfony/Component/HttpKernel/Fragment/HIncludeFragmentRenderer.php @@ -86,7 +86,7 @@ public function render($uri, Request $request, array $options = []) } $renderedAttributes = ''; if (\count($attributes) > 0) { - $flags = ENT_QUOTES | ENT_SUBSTITUTE; + $flags = \ENT_QUOTES | \ENT_SUBSTITUTE; foreach ($attributes as $attribute => $value) { $renderedAttributes .= sprintf( ' %s="%s"', diff --git a/src/Symfony/Component/HttpKernel/HttpCache/Esi.php b/src/Symfony/Component/HttpKernel/HttpCache/Esi.php index af67e8ffb8bd..458b2c5d7483 100644 --- a/src/Symfony/Component/HttpKernel/HttpCache/Esi.php +++ b/src/Symfony/Component/HttpKernel/HttpCache/Esi.php @@ -80,13 +80,13 @@ public function process(Request $request, Response $response) $content = preg_replace('#.*?#s', '', $content); $content = preg_replace('#]+>#s', '', $content); - $chunks = preg_split('##', $content, -1, PREG_SPLIT_DELIM_CAPTURE); + $chunks = preg_split('##', $content, -1, \PREG_SPLIT_DELIM_CAPTURE); $chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]); $i = 1; while (isset($chunks[$i])) { $options = []; - preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER); + preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, \PREG_SET_ORDER); foreach ($matches as $set) { $options[$set[1]] = $set[2]; } diff --git a/src/Symfony/Component/HttpKernel/HttpCache/Ssi.php b/src/Symfony/Component/HttpKernel/HttpCache/Ssi.php index 587c43a0eb3f..0ba351dd129c 100644 --- a/src/Symfony/Component/HttpKernel/HttpCache/Ssi.php +++ b/src/Symfony/Component/HttpKernel/HttpCache/Ssi.php @@ -65,13 +65,13 @@ public function process(Request $request, Response $response) // we don't use a proper XML parser here as we can have SSI tags in a plain text response $content = $response->getContent(); - $chunks = preg_split('##', $content, -1, PREG_SPLIT_DELIM_CAPTURE); + $chunks = preg_split('##', $content, -1, \PREG_SPLIT_DELIM_CAPTURE); $chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]); $i = 1; while (isset($chunks[$i])) { $options = []; - preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER); + preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, \PREG_SET_ORDER); foreach ($matches as $set) { $options[$set[1]] = $set[2]; } diff --git a/src/Symfony/Component/HttpKernel/HttpCache/Store.php b/src/Symfony/Component/HttpKernel/HttpCache/Store.php index 22a03f261f6a..b5dec855e819 100644 --- a/src/Symfony/Component/HttpKernel/HttpCache/Store.php +++ b/src/Symfony/Component/HttpKernel/HttpCache/Store.php @@ -48,7 +48,7 @@ public function cleanup() { // unlock everything foreach ($this->locks as $lock) { - flock($lock, LOCK_UN); + flock($lock, \LOCK_UN); fclose($lock); } @@ -70,7 +70,7 @@ public function lock(Request $request) return $path; } $h = fopen($path, 'cb'); - if (!flock($h, LOCK_EX | LOCK_NB)) { + if (!flock($h, \LOCK_EX | \LOCK_NB)) { fclose($h); return $path; @@ -92,7 +92,7 @@ public function unlock(Request $request) $key = $this->getCacheKey($request); if (isset($this->locks[$key])) { - flock($this->locks[$key], LOCK_UN); + flock($this->locks[$key], \LOCK_UN); fclose($this->locks[$key]); unset($this->locks[$key]); @@ -115,8 +115,8 @@ public function isLocked(Request $request) } $h = fopen($path, 'rb'); - flock($h, LOCK_EX | LOCK_NB, $wouldBlock); - flock($h, LOCK_UN); // release the lock we just acquired + flock($h, \LOCK_EX | \LOCK_NB, $wouldBlock); + flock($h, \LOCK_UN); // release the lock we just acquired fclose($h); return (bool) $wouldBlock; @@ -326,7 +326,7 @@ private function doPurge(string $url): bool { $key = $this->getCacheKey(Request::create($url)); if (isset($this->locks[$key])) { - flock($this->locks[$key], LOCK_UN); + flock($this->locks[$key], \LOCK_UN); fclose($this->locks[$key]); unset($this->locks[$key]); } diff --git a/src/Symfony/Component/HttpKernel/HttpClientKernel.php b/src/Symfony/Component/HttpKernel/HttpClientKernel.php index a5e207d54667..818082f43994 100644 --- a/src/Symfony/Component/HttpKernel/HttpClientKernel.php +++ b/src/Symfony/Component/HttpKernel/HttpClientKernel.php @@ -35,7 +35,7 @@ final class HttpClientKernel implements HttpKernelInterface public function __construct(HttpClientInterface $client = null) { - if (!class_exists(HttpClient::class)) { + if (null === $client && !class_exists(HttpClient::class)) { throw new \LogicException(sprintf('You cannot use "%s" as the HttpClient component is not installed. Try running "composer require symfony/http-client".', __CLASS__)); } @@ -53,7 +53,6 @@ public function handle(Request $request, int $type = HttpKernelInterface::MASTER $response = $this->client->request($request->getMethod(), $request->getUri(), [ 'headers' => $headers, 'body' => $body, - 'max_redirects' => 0, ] + $request->attributes->get('http_client_options', [])); $response = new Response($response->getContent(!$catch), $response->getStatusCode(), $response->getHeaders(!$catch)); diff --git a/src/Symfony/Component/HttpKernel/HttpKernelBrowser.php b/src/Symfony/Component/HttpKernel/HttpKernelBrowser.php index d28be997417b..c1f5b4c922d3 100644 --- a/src/Symfony/Component/HttpKernel/HttpKernelBrowser.php +++ b/src/Symfony/Component/HttpKernel/HttpKernelBrowser.php @@ -164,7 +164,7 @@ protected function filterFiles(array $files) '', $value->getClientOriginalName(), $value->getClientMimeType(), - UPLOAD_ERR_INI_SIZE, + \UPLOAD_ERR_INI_SIZE, true ); } else { diff --git a/src/Symfony/Component/HttpKernel/Kernel.php b/src/Symfony/Component/HttpKernel/Kernel.php index c90c77ae7757..a4b05ebd9735 100644 --- a/src/Symfony/Component/HttpKernel/Kernel.php +++ b/src/Symfony/Component/HttpKernel/Kernel.php @@ -73,11 +73,11 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl private static $freshCache = []; - const VERSION = '5.1.5'; - const VERSION_ID = 50105; + const VERSION = '5.1.6'; + const VERSION_ID = 50106; const MAJOR_VERSION = 5; const MINOR_VERSION = 1; - const RELEASE_VERSION = 5; + const RELEASE_VERSION = 6; const EXTRA_VERSION = ''; const END_OF_MAINTENANCE = '01/2021'; @@ -324,7 +324,7 @@ public function setAnnotatedClassCache(array $annotatedClasses) */ public function getStartTime() { - return $this->debug && null !== $this->startTime ? $this->startTime : -INF; + return $this->debug && null !== $this->startTime ? $this->startTime : -\INF; } /** @@ -432,7 +432,7 @@ protected function initializeContainer() $cachePath = $cache->getPath(); // Silence E_WARNING to ignore "include" failures - don't use "@" to prevent silencing fatal errors - $errorLevel = error_reporting(E_ALL ^ E_WARNING); + $errorLevel = error_reporting(\E_ALL ^ \E_WARNING); try { if (is_file($cachePath) && \is_object($this->container = include $cachePath) @@ -453,15 +453,15 @@ protected function initializeContainer() is_dir($cacheDir) ?: mkdir($cacheDir, 0777, true); if ($lock = fopen($cachePath.'.lock', 'w')) { - flock($lock, LOCK_EX | LOCK_NB, $wouldBlock); + flock($lock, \LOCK_EX | \LOCK_NB, $wouldBlock); - if (!flock($lock, $wouldBlock ? LOCK_SH : LOCK_EX)) { + if (!flock($lock, $wouldBlock ? \LOCK_SH : \LOCK_EX)) { fclose($lock); $lock = null; } elseif (!\is_object($this->container = include $cachePath)) { $this->container = null; } elseif (!$oldContainer || \get_class($this->container) !== $oldContainer->name) { - flock($lock, LOCK_UN); + flock($lock, \LOCK_UN); fclose($lock); $this->container->set('kernel', $this); @@ -476,7 +476,7 @@ protected function initializeContainer() if ($collectDeprecations = $this->debug && !\defined('PHPUNIT_COMPOSER_INSTALL')) { $collectedLogs = []; $previousHandler = set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) { - if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) { + if (\E_USER_DEPRECATED !== $type && \E_DEPRECATED !== $type) { return $previousHandler ? $previousHandler($type, $message, $file, $line) : false; } @@ -486,7 +486,7 @@ protected function initializeContainer() return null; } - $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5); + $backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 5); // Clean the trace by removing first frames added by the error handler itself. for ($i = 0; isset($backtrace[$i]); ++$i) { if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) { @@ -543,7 +543,7 @@ protected function initializeContainer() $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass()); if ($lock) { - flock($lock, LOCK_UN); + flock($lock, \LOCK_UN); fclose($lock); } @@ -557,7 +557,7 @@ protected function initializeContainer() static $legacyContainers = []; $oldContainerDir = \dirname($oldContainer->getFileName()); $legacyContainers[$oldContainerDir.'.legacy'] = true; - foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy', GLOB_NOSORT) as $legacyContainer) { + foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy', \GLOB_NOSORT) as $legacyContainer) { if (!isset($legacyContainers[$legacyContainer]) && @unlink($legacyContainer)) { (new Filesystem())->remove(substr($legacyContainer, 0, -7)); } @@ -774,14 +774,14 @@ public static function stripComments(string $source) $token = $tokens[$i]; if (!isset($token[1]) || 'b"' === $token) { $rawChunk .= $token; - } elseif (T_START_HEREDOC === $token[0]) { + } elseif (\T_START_HEREDOC === $token[0]) { $output .= $rawChunk.$token[1]; do { $token = $tokens[++$i]; $output .= isset($token[1]) && 'b"' !== $token ? $token[1] : $token; - } while (T_END_HEREDOC !== $token[0]); + } while (\T_END_HEREDOC !== $token[0]); $rawChunk = ''; - } elseif (T_WHITESPACE === $token[0]) { + } elseif (\T_WHITESPACE === $token[0]) { if ($ignoreSpace) { $ignoreSpace = false; @@ -790,13 +790,13 @@ public static function stripComments(string $source) // replace multiple new lines with a single newline $rawChunk .= preg_replace(['/\n{2,}/S'], "\n", $token[1]); - } elseif (\in_array($token[0], [T_COMMENT, T_DOC_COMMENT])) { + } elseif (\in_array($token[0], [\T_COMMENT, \T_DOC_COMMENT])) { $ignoreSpace = true; } else { $rawChunk .= $token[1]; // The PHP-open tag already has a new-line - if (T_OPEN_TAG === $token[0]) { + if (\T_OPEN_TAG === $token[0]) { $ignoreSpace = true; } } diff --git a/src/Symfony/Component/HttpKernel/Log/Logger.php b/src/Symfony/Component/HttpKernel/Log/Logger.php index 1e6308d6e0ed..c97673dd899d 100644 --- a/src/Symfony/Component/HttpKernel/Log/Logger.php +++ b/src/Symfony/Component/HttpKernel/Log/Logger.php @@ -105,7 +105,7 @@ private function format(string $level, string $message, array $context, bool $pr $message = strtr($message, $replacements); } - $log = sprintf('[%s] %s', $level, $message).PHP_EOL; + $log = sprintf('[%s] %s', $level, $message).\PHP_EOL; if ($prefixDate) { $log = date(\DateTime::RFC3339).' '.$log; } diff --git a/src/Symfony/Component/HttpKernel/Profiler/FileProfilerStorage.php b/src/Symfony/Component/HttpKernel/Profiler/FileProfilerStorage.php index 3b5dfbf26f12..4f63b41889c2 100644 --- a/src/Symfony/Component/HttpKernel/Profiler/FileProfilerStorage.php +++ b/src/Symfony/Component/HttpKernel/Profiler/FileProfilerStorage.php @@ -56,7 +56,7 @@ public function find(?string $ip, ?string $url, ?int $limit, ?string $method, in } $file = fopen($file, 'r'); - fseek($file, 0, SEEK_END); + fseek($file, 0, \SEEK_END); $result = []; while (\count($result) < $limit && $line = $this->readLineFromFile($file)) { @@ -258,7 +258,7 @@ protected function readLineFromFile($file) $position += $upTo; $line = substr($buffer, $upTo + 1).$line; - fseek($file, max(0, $position), SEEK_SET); + fseek($file, max(0, $position), \SEEK_SET); if ('' !== $line) { break; diff --git a/src/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php b/src/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php index d5ac4ad5c260..de6dfc2546bb 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php @@ -170,9 +170,9 @@ public function getUndefinedControllers() $controller = new ControllerTest(); return [ - ['foo', \Error::class, 'Class \'foo\' not found'], - ['oof::bar', \Error::class, 'Class \'oof\' not found'], - [['oof', 'bar'], \Error::class, 'Class \'oof\' not found'], + ['foo', \Error::class, \PHP_VERSION_ID < 80000 ? 'Class \'foo\' not found' : 'Class "foo" not found'], + ['oof::bar', \Error::class, \PHP_VERSION_ID < 80000 ? 'Class \'oof\' not found' : 'Class "oof" not found'], + [['oof', 'bar'], \Error::class, \PHP_VERSION_ID < 80000 ? 'Class \'oof\' not found' : 'Class "oof" not found'], ['Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::staticsAction', \InvalidArgumentException::class, 'The controller for URI "/" is not callable: Expected method "staticsAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest", did you mean "staticAction"?'], ['Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::privateAction', \InvalidArgumentException::class, 'The controller for URI "/" is not callable: Method "privateAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'], ['Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::protectedAction', \InvalidArgumentException::class, 'The controller for URI "/" is not callable: Method "protectedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'], diff --git a/src/Symfony/Component/HttpKernel/Tests/DataCollector/ConfigDataCollectorTest.php b/src/Symfony/Component/HttpKernel/Tests/DataCollector/ConfigDataCollectorTest.php index 9cb75a6051de..308a20127acf 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DataCollector/ConfigDataCollectorTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DataCollector/ConfigDataCollectorTest.php @@ -30,8 +30,8 @@ public function testCollect() $this->assertSame('test', $c->getEnv()); $this->assertTrue($c->isDebug()); $this->assertSame('config', $c->getName()); - $this->assertMatchesRegularExpression('~^'.preg_quote($c->getPhpVersion(), '~').'~', PHP_VERSION); - $this->assertMatchesRegularExpression('~'.preg_quote((string) $c->getPhpVersionExtra(), '~').'$~', PHP_VERSION); + $this->assertMatchesRegularExpression('~^'.preg_quote($c->getPhpVersion(), '~').'~', \PHP_VERSION); + $this->assertMatchesRegularExpression('~'.preg_quote((string) $c->getPhpVersionExtra(), '~').'$~', \PHP_VERSION); $this->assertSame(\PHP_INT_SIZE * 8, $c->getPhpArchitecture()); $this->assertSame(class_exists('Locale', false) && \Locale::getDefault() ? \Locale::getDefault() : 'n/a', $c->getPhpIntlLocale()); $this->assertSame(date_default_timezone_get(), $c->getPhpTimezone()); @@ -39,8 +39,8 @@ public function testCollect() $this->assertSame(4 === Kernel::MINOR_VERSION, $c->isSymfonyLts()); $this->assertNull($c->getToken()); $this->assertSame(\extension_loaded('xdebug'), $c->hasXDebug()); - $this->assertSame(\extension_loaded('Zend OPcache') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN), $c->hasZendOpcache()); - $this->assertSame(\extension_loaded('apcu') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN), $c->hasApcu()); + $this->assertSame(\extension_loaded('Zend OPcache') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN), $c->hasZendOpcache()); + $this->assertSame(\extension_loaded('apcu') && filter_var(ini_get('apc.enabled'), \FILTER_VALIDATE_BOOLEAN), $c->hasApcu()); } } diff --git a/src/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php b/src/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php index 9c175397fced..de9364bb47ed 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php @@ -157,14 +157,14 @@ public function getCollectTestData() yield 'logs with some deprecations' => [ 1, [ - ['message' => 'foo3', 'context' => ['exception' => new \ErrorException('warning', 0, E_USER_WARNING)], 'priority' => 100, 'priorityName' => 'DEBUG'], - ['message' => 'foo', 'context' => ['exception' => new \ErrorException('deprecated', 0, E_DEPRECATED)], 'priority' => 100, 'priorityName' => 'DEBUG'], - ['message' => 'foo2', 'context' => ['exception' => new \ErrorException('deprecated', 0, E_USER_DEPRECATED)], 'priority' => 100, 'priorityName' => 'DEBUG'], + ['message' => 'foo3', 'context' => ['exception' => new \ErrorException('warning', 0, \E_USER_WARNING)], 'priority' => 100, 'priorityName' => 'DEBUG'], + ['message' => 'foo', 'context' => ['exception' => new \ErrorException('deprecated', 0, \E_DEPRECATED)], 'priority' => 100, 'priorityName' => 'DEBUG'], + ['message' => 'foo2', 'context' => ['exception' => new \ErrorException('deprecated', 0, \E_USER_DEPRECATED)], 'priority' => 100, 'priorityName' => 'DEBUG'], ], [ - ['message' => 'foo3', 'context' => ['exception' => ['warning', E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG'], - ['message' => 'foo', 'context' => ['exception' => ['deprecated', E_DEPRECATED]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false], - ['message' => 'foo2', 'context' => ['exception' => ['deprecated', E_USER_DEPRECATED]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false], + ['message' => 'foo3', 'context' => ['exception' => ['warning', \E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG'], + ['message' => 'foo', 'context' => ['exception' => ['deprecated', \E_DEPRECATED]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false], + ['message' => 'foo2', 'context' => ['exception' => ['deprecated', \E_USER_DEPRECATED]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false], ], 2, 0, @@ -174,14 +174,14 @@ public function getCollectTestData() yield 'logs with some silent errors' => [ 1, [ - ['message' => 'foo3', 'context' => ['exception' => new \ErrorException('warning', 0, E_USER_WARNING)], 'priority' => 100, 'priorityName' => 'DEBUG'], - ['message' => 'foo3', 'context' => ['exception' => new SilencedErrorContext(E_USER_WARNING, __FILE__, __LINE__)], 'priority' => 100, 'priorityName' => 'DEBUG'], - ['message' => '0', 'context' => ['exception' => new SilencedErrorContext(E_USER_WARNING, __FILE__, __LINE__)], 'priority' => 100, 'priorityName' => 'DEBUG'], + ['message' => 'foo3', 'context' => ['exception' => new \ErrorException('warning', 0, \E_USER_WARNING)], 'priority' => 100, 'priorityName' => 'DEBUG'], + ['message' => 'foo3', 'context' => ['exception' => new SilencedErrorContext(\E_USER_WARNING, __FILE__, __LINE__)], 'priority' => 100, 'priorityName' => 'DEBUG'], + ['message' => '0', 'context' => ['exception' => new SilencedErrorContext(\E_USER_WARNING, __FILE__, __LINE__)], 'priority' => 100, 'priorityName' => 'DEBUG'], ], [ - ['message' => 'foo3', 'context' => ['exception' => ['warning', E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG'], - ['message' => 'foo3', 'context' => ['exception' => [E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => true], - ['message' => '0', 'context' => ['exception' => [E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => true], + ['message' => 'foo3', 'context' => ['exception' => ['warning', \E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG'], + ['message' => 'foo3', 'context' => ['exception' => [\E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => true], + ['message' => '0', 'context' => ['exception' => [\E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => true], ], 0, 2, diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/DebugHandlersListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/DebugHandlersListenerTest.php index abd202f3814f..12df18757176 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/DebugHandlersListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/DebugHandlersListenerTest.php @@ -59,8 +59,8 @@ public function testConfigure() $loggers = $eHandler->setLoggers([]); - $this->assertArrayHasKey(E_DEPRECATED, $loggers); - $this->assertSame([$logger, LogLevel::INFO], $loggers[E_DEPRECATED]); + $this->assertArrayHasKey(\E_DEPRECATED, $loggers); + $this->assertSame([$logger, LogLevel::INFO], $loggers[\E_DEPRECATED]); } public function testConfigureForHttpKernelWithNoTerminateWithException() @@ -156,28 +156,28 @@ public function provideLevelsAssignedToLoggers(): array { return [ [false, false, '0', null, null], - [false, false, E_ALL, null, null], + [false, false, \E_ALL, null, null], [false, false, [], null, null], - [false, false, [E_WARNING => LogLevel::WARNING, E_USER_DEPRECATED => LogLevel::NOTICE], null, null], + [false, false, [\E_WARNING => LogLevel::WARNING, \E_USER_DEPRECATED => LogLevel::NOTICE], null, null], - [true, false, E_ALL, E_ALL, null], - [true, false, E_DEPRECATED, E_DEPRECATED, null], + [true, false, \E_ALL, \E_ALL, null], + [true, false, \E_DEPRECATED, \E_DEPRECATED, null], [true, false, [], null, null], - [true, false, [E_WARNING => LogLevel::WARNING, E_DEPRECATED => LogLevel::NOTICE], [E_WARNING => LogLevel::WARNING, E_DEPRECATED => LogLevel::NOTICE], null], + [true, false, [\E_WARNING => LogLevel::WARNING, \E_DEPRECATED => LogLevel::NOTICE], [\E_WARNING => LogLevel::WARNING, \E_DEPRECATED => LogLevel::NOTICE], null], [false, true, '0', null, null], - [false, true, E_ALL, null, E_DEPRECATED | E_USER_DEPRECATED], - [false, true, E_ERROR, null, null], + [false, true, \E_ALL, null, \E_DEPRECATED | \E_USER_DEPRECATED], + [false, true, \E_ERROR, null, null], [false, true, [], null, null], - [false, true, [E_ERROR => LogLevel::ERROR, E_DEPRECATED => LogLevel::DEBUG], null, [E_DEPRECATED => LogLevel::DEBUG]], + [false, true, [\E_ERROR => LogLevel::ERROR, \E_DEPRECATED => LogLevel::DEBUG], null, [\E_DEPRECATED => LogLevel::DEBUG]], [true, true, '0', null, null], - [true, true, E_ALL, E_ALL & ~(E_DEPRECATED | E_USER_DEPRECATED), E_DEPRECATED | E_USER_DEPRECATED], - [true, true, E_ERROR, E_ERROR, null], - [true, true, E_USER_DEPRECATED, null, E_USER_DEPRECATED], - [true, true, [E_ERROR => LogLevel::ERROR, E_DEPRECATED => LogLevel::DEBUG], [E_ERROR => LogLevel::ERROR], [E_DEPRECATED => LogLevel::DEBUG]], - [true, true, [E_ERROR => LogLevel::ALERT], [E_ERROR => LogLevel::ALERT], null], - [true, true, [E_USER_DEPRECATED => LogLevel::NOTICE], null, [E_USER_DEPRECATED => LogLevel::NOTICE]], + [true, true, \E_ALL, \E_ALL & ~(\E_DEPRECATED | \E_USER_DEPRECATED), \E_DEPRECATED | \E_USER_DEPRECATED], + [true, true, \E_ERROR, \E_ERROR, null], + [true, true, \E_USER_DEPRECATED, null, \E_USER_DEPRECATED], + [true, true, [\E_ERROR => LogLevel::ERROR, \E_DEPRECATED => LogLevel::DEBUG], [\E_ERROR => LogLevel::ERROR], [\E_DEPRECATED => LogLevel::DEBUG]], + [true, true, [\E_ERROR => LogLevel::ALERT], [\E_ERROR => LogLevel::ALERT], null], + [true, true, [\E_USER_DEPRECATED => LogLevel::NOTICE], null, [\E_USER_DEPRECATED => LogLevel::NOTICE]], ]; } diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php index 802f1d100757..6ad64e47917a 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php @@ -129,8 +129,8 @@ public function testRespondsWith304WhenIfModifiedSinceMatchesLastModified() { $time = \DateTime::createFromFormat('U', time()); - $this->setNextResponse(200, ['Cache-Control' => 'public', 'Last-Modified' => $time->format(DATE_RFC2822), 'Content-Type' => 'text/plain'], 'Hello World'); - $this->request('GET', '/', ['HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822)]); + $this->setNextResponse(200, ['Cache-Control' => 'public', 'Last-Modified' => $time->format(\DATE_RFC2822), 'Content-Type' => 'text/plain'], 'Hello World'); + $this->request('GET', '/', ['HTTP_IF_MODIFIED_SINCE' => $time->format(\DATE_RFC2822)]); $this->assertHttpKernelIsCalled(); $this->assertEquals(304, $this->response->getStatusCode()); @@ -161,24 +161,24 @@ public function testRespondsWith304OnlyIfIfNoneMatchAndIfModifiedSinceBothMatch( $this->setNextResponse(200, [], '', function ($request, $response) use ($time) { $response->setStatusCode(200); $response->headers->set('ETag', '12345'); - $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); + $response->headers->set('Last-Modified', $time->format(\DATE_RFC2822)); $response->headers->set('Content-Type', 'text/plain'); $response->setContent('Hello World'); }); // only ETag matches $t = \DateTime::createFromFormat('U', time() - 3600); - $this->request('GET', '/', ['HTTP_IF_NONE_MATCH' => '12345', 'HTTP_IF_MODIFIED_SINCE' => $t->format(DATE_RFC2822)]); + $this->request('GET', '/', ['HTTP_IF_NONE_MATCH' => '12345', 'HTTP_IF_MODIFIED_SINCE' => $t->format(\DATE_RFC2822)]); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); // only Last-Modified matches - $this->request('GET', '/', ['HTTP_IF_NONE_MATCH' => '1234', 'HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822)]); + $this->request('GET', '/', ['HTTP_IF_NONE_MATCH' => '1234', 'HTTP_IF_MODIFIED_SINCE' => $time->format(\DATE_RFC2822)]); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); // Both matches - $this->request('GET', '/', ['HTTP_IF_NONE_MATCH' => '12345', 'HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822)]); + $this->request('GET', '/', ['HTTP_IF_NONE_MATCH' => '12345', 'HTTP_IF_MODIFIED_SINCE' => $time->format(\DATE_RFC2822)]); $this->assertHttpKernelIsCalled(); $this->assertEquals(304, $this->response->getStatusCode()); } @@ -257,7 +257,7 @@ public function testStoresResponsesWhenNoCacheRequestDirectivePresent() { $time = \DateTime::createFromFormat('U', time() + 5); - $this->setNextResponse(200, ['Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822)]); + $this->setNextResponse(200, ['Cache-Control' => 'public', 'Expires' => $time->format(\DATE_RFC2822)]); $this->request('GET', '/', ['HTTP_CACHE_CONTROL' => 'no-cache']); $this->assertHttpKernelIsCalled(); @@ -393,7 +393,7 @@ public function testDoesNotRevalidateFreshCacheEntryWhenEnableRevalidateOptionIs public function testFetchesResponseFromBackendWhenCacheMisses() { $time = \DateTime::createFromFormat('U', time() + 5); - $this->setNextResponse(200, ['Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822)]); + $this->setNextResponse(200, ['Cache-Control' => 'public', 'Expires' => $time->format(\DATE_RFC2822)]); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); @@ -405,7 +405,7 @@ public function testDoesNotCacheSomeStatusCodeResponses() { foreach (array_merge(range(201, 202), range(204, 206), range(303, 305), range(400, 403), range(405, 409), range(411, 417), range(500, 505)) as $code) { $time = \DateTime::createFromFormat('U', time() + 5); - $this->setNextResponse($code, ['Expires' => $time->format(DATE_RFC2822)]); + $this->setNextResponse($code, ['Expires' => $time->format(\DATE_RFC2822)]); $this->request('GET', '/'); $this->assertEquals($code, $this->response->getStatusCode()); @@ -417,7 +417,7 @@ public function testDoesNotCacheSomeStatusCodeResponses() public function testDoesNotCacheResponsesWithExplicitNoStoreDirective() { $time = \DateTime::createFromFormat('U', time() + 5); - $this->setNextResponse(200, ['Expires' => $time->format(DATE_RFC2822), 'Cache-Control' => 'no-store']); + $this->setNextResponse(200, ['Expires' => $time->format(\DATE_RFC2822), 'Cache-Control' => 'no-store']); $this->request('GET', '/'); $this->assertTraceNotContains('store'); @@ -436,7 +436,7 @@ public function testDoesNotCacheResponsesWithoutFreshnessInformationOrAValidator public function testCachesResponsesWithExplicitNoCacheDirective() { $time = \DateTime::createFromFormat('U', time() + 5); - $this->setNextResponse(200, ['Expires' => $time->format(DATE_RFC2822), 'Cache-Control' => 'public, no-cache']); + $this->setNextResponse(200, ['Expires' => $time->format(\DATE_RFC2822), 'Cache-Control' => 'public, no-cache']); $this->request('GET', '/'); $this->assertTraceContains('store'); @@ -462,7 +462,7 @@ public function testRevalidatesResponsesWithNoCacheDirectiveEvenIfFresh() public function testCachesResponsesWithAnExpirationHeader() { $time = \DateTime::createFromFormat('U', time() + 5); - $this->setNextResponse(200, ['Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822)]); + $this->setNextResponse(200, ['Cache-Control' => 'public', 'Expires' => $time->format(\DATE_RFC2822)]); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); @@ -511,7 +511,7 @@ public function testCachesResponsesWithASMaxAgeDirective() public function testCachesResponsesWithALastModifiedValidatorButNoFreshnessInformation() { $time = \DateTime::createFromFormat('U', time()); - $this->setNextResponse(200, ['Cache-Control' => 'public', 'Last-Modified' => $time->format(DATE_RFC2822)]); + $this->setNextResponse(200, ['Cache-Control' => 'public', 'Last-Modified' => $time->format(\DATE_RFC2822)]); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); @@ -535,7 +535,7 @@ public function testHitsCachedResponsesWithExpiresHeader() { $time1 = \DateTime::createFromFormat('U', time() - 5); $time2 = \DateTime::createFromFormat('U', time() + 5); - $this->setNextResponse(200, ['Cache-Control' => 'public', 'Date' => $time1->format(DATE_RFC2822), 'Expires' => $time2->format(DATE_RFC2822)]); + $this->setNextResponse(200, ['Cache-Control' => 'public', 'Date' => $time1->format(\DATE_RFC2822), 'Expires' => $time2->format(\DATE_RFC2822)]); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); @@ -559,7 +559,7 @@ public function testHitsCachedResponsesWithExpiresHeader() public function testHitsCachedResponseWithMaxAgeDirective() { $time = \DateTime::createFromFormat('U', time() - 5); - $this->setNextResponse(200, ['Date' => $time->format(DATE_RFC2822), 'Cache-Control' => 'public, max-age=10']); + $this->setNextResponse(200, ['Date' => $time->format(\DATE_RFC2822), 'Cache-Control' => 'public, max-age=10']); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); @@ -623,7 +623,7 @@ public function testDegradationWhenCacheLocked() public function testHitsCachedResponseWithSMaxAgeDirective() { $time = \DateTime::createFromFormat('U', time() - 5); - $this->setNextResponse(200, ['Date' => $time->format(DATE_RFC2822), 'Cache-Control' => 's-maxage=10, max-age=0']); + $this->setNextResponse(200, ['Date' => $time->format(\DATE_RFC2822), 'Cache-Control' => 's-maxage=10, max-age=0']); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); @@ -691,7 +691,7 @@ public function testAssignsDefaultTtlWhenResponseHasNoFreshnessInformationAndAft $this->assertCount(1, $values); $tmp = unserialize($values[0]); $time = \DateTime::createFromFormat('U', time() - 5); - $tmp[0][1]['date'] = $time->format(DATE_RFC2822); + $tmp[0][1]['date'] = $time->format(\DATE_RFC2822); $r = new \ReflectionObject($this->store); $m = $r->getMethod('save'); $m->setAccessible(true); @@ -741,7 +741,7 @@ public function testAssignsDefaultTtlWhenResponseHasNoFreshnessInformationAndAft $this->assertCount(1, $values); $tmp = unserialize($values[0]); $time = \DateTime::createFromFormat('U', time() - 5); - $tmp[0][1]['date'] = $time->format(DATE_RFC2822); + $tmp[0][1]['date'] = $time->format(\DATE_RFC2822); $r = new \ReflectionObject($this->store); $m = $r->getMethod('save'); $m->setAccessible(true); @@ -783,7 +783,7 @@ public function testDoesNotAssignDefaultTtlWhenResponseHasMustRevalidateDirectiv public function testFetchesFullResponseWhenCacheStaleAndNoValidatorsPresent() { $time = \DateTime::createFromFormat('U', time() + 5); - $this->setNextResponse(200, ['Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822)]); + $this->setNextResponse(200, ['Cache-Control' => 'public', 'Expires' => $time->format(\DATE_RFC2822)]); // build initial request $this->request('GET', '/'); @@ -801,7 +801,7 @@ public function testFetchesFullResponseWhenCacheStaleAndNoValidatorsPresent() $this->assertCount(1, $values); $tmp = unserialize($values[0]); $time = \DateTime::createFromFormat('U', time()); - $tmp[0][1]['expires'] = $time->format(DATE_RFC2822); + $tmp[0][1]['expires'] = $time->format(\DATE_RFC2822); $r = new \ReflectionObject($this->store); $m = $r->getMethod('save'); $m->setAccessible(true); @@ -825,8 +825,8 @@ public function testValidatesCachedResponsesWithLastModifiedAndNoFreshnessInform $time = \DateTime::createFromFormat('U', time()); $this->setNextResponse(200, [], 'Hello World', function ($request, $response) use ($time) { $response->headers->set('Cache-Control', 'public'); - $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); - if ($time->format(DATE_RFC2822) == $request->headers->get('IF_MODIFIED_SINCE')) { + $response->headers->set('Last-Modified', $time->format(\DATE_RFC2822)); + if ($time->format(\DATE_RFC2822) == $request->headers->get('IF_MODIFIED_SINCE')) { $response->setStatusCode(304); $response->setContent(''); } @@ -912,7 +912,7 @@ public function testServesResponseWhileFreshAndRevalidatesWithLastModifiedInform $this->setNextResponse(200, [], 'Hello World', function (Request $request, Response $response) use ($time) { $response->setSharedMaxAge(10); - $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); + $response->headers->set('Last-Modified', $time->format(\DATE_RFC2822)); }); // prime the cache @@ -929,7 +929,7 @@ public function testServesResponseWhileFreshAndRevalidatesWithLastModifiedInform sleep(15); // expire the cache $this->setNextResponse(304, [], '', function (Request $request, Response $response) use ($time) { - $this->assertEquals($time->format(DATE_RFC2822), $request->headers->get('IF_MODIFIED_SINCE')); + $this->assertEquals($time->format(\DATE_RFC2822), $request->headers->get('IF_MODIFIED_SINCE')); }); $this->request('GET', '/'); @@ -945,7 +945,7 @@ public function testReplacesCachedResponsesWhenValidationResultsInNon304Response $time = \DateTime::createFromFormat('U', time()); $count = 0; $this->setNextResponse(200, [], 'Hello World', function ($request, $response) use ($time, &$count) { - $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); + $response->headers->set('Last-Modified', $time->format(\DATE_RFC2822)); $response->headers->set('Cache-Control', 'public'); switch (++$count) { case 1: @@ -1017,14 +1017,14 @@ public function testSendsNoContentWhenFresh() $time = \DateTime::createFromFormat('U', time()); $this->setNextResponse(200, [], 'Hello World', function ($request, $response) use ($time) { $response->headers->set('Cache-Control', 'public, max-age=10'); - $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); + $response->headers->set('Last-Modified', $time->format(\DATE_RFC2822)); }); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals('Hello World', $this->response->getContent()); - $this->request('GET', '/', ['HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822)]); + $this->request('GET', '/', ['HTTP_IF_MODIFIED_SINCE' => $time->format(\DATE_RFC2822)]); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(304, $this->response->getStatusCode()); $this->assertEquals('', $this->response->getContent()); @@ -1425,7 +1425,7 @@ public function testEsiCacheRemoveValidationHeadersIfEmbeddedResponses() 'headers' => [ 'Surrogate-Control' => 'content="ESI/1.0"', 'ETag' => 'hey', - 'Last-Modified' => $time->format(DATE_RFC2822), + 'Last-Modified' => $time->format(\DATE_RFC2822), ], ], [ @@ -1453,7 +1453,7 @@ public function testEsiCacheRemoveValidationHeadersIfEmbeddedResponsesAndHeadReq 'headers' => [ 'Surrogate-Control' => 'content="ESI/1.0"', 'ETag' => 'hey', - 'Last-Modified' => $time->format(DATE_RFC2822), + 'Last-Modified' => $time->format(\DATE_RFC2822), ], ], [ diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpClientKernelTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpClientKernelTest.php new file mode 100644 index 000000000000..2b904bf9a2ca --- /dev/null +++ b/src/Symfony/Component/HttpKernel/Tests/HttpClientKernelTest.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Tests; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\HttpClientKernel; +use Symfony\Contracts\HttpClient\HttpClientInterface; +use Symfony\Contracts\HttpClient\ResponseInterface; + +class HttpClientKernelTest extends TestCase +{ + public function testHandlePassesMaxRedirectsHttpClientOption() + { + $request = new Request(); + $request->attributes->set('http_client_options', ['max_redirects' => 50]); + + $response = $this->getMockBuilder(ResponseInterface::class)->getMock(); + $response->expects($this->once())->method('getStatusCode')->willReturn(200); + + $client = $this->getMockBuilder(HttpClientInterface::class)->getMock(); + $client + ->expects($this->once()) + ->method('request') + ->willReturnCallback(function (string $method, string $uri, array $options) use ($request, $response) { + $this->assertSame($request->getMethod(), $method); + $this->assertSame($request->getUri(), $uri); + $this->assertArrayHasKey('max_redirects', $options); + $this->assertSame(50, $options['max_redirects']); + + return $response; + }); + + $kernel = new HttpClientKernel($client); + $kernel->handle($request); + } +} diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpKernelBrowserTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpKernelBrowserTest.php index fdcfc2666751..4d4fe5ae7230 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpKernelBrowserTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpKernelBrowserTest.php @@ -100,8 +100,8 @@ public function testUploadedFile() $client = new HttpKernelBrowser($kernel); $files = [ - ['tmp_name' => $source, 'name' => 'original', 'type' => 'mime/original', 'size' => null, 'error' => UPLOAD_ERR_OK], - new UploadedFile($source, 'original', 'mime/original', UPLOAD_ERR_OK, true), + ['tmp_name' => $source, 'name' => 'original', 'type' => 'mime/original', 'size' => null, 'error' => \UPLOAD_ERR_OK], + new UploadedFile($source, 'original', 'mime/original', \UPLOAD_ERR_OK, true), ]; $file = null; @@ -130,7 +130,7 @@ public function testUploadedFileWhenNoFileSelected() $kernel = new TestHttpKernel(); $client = new HttpKernelBrowser($kernel); - $file = ['tmp_name' => '', 'name' => '', 'type' => '', 'size' => 0, 'error' => UPLOAD_ERR_NO_FILE]; + $file = ['tmp_name' => '', 'name' => '', 'type' => '', 'size' => 0, 'error' => \UPLOAD_ERR_NO_FILE]; $client->request('POST', '/', [], ['foo' => $file]); @@ -149,18 +149,18 @@ public function testUploadedFileWhenSizeExceedsUploadMaxFileSize() $file = $this ->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') - ->setConstructorArgs([$source, 'original', 'mime/original', UPLOAD_ERR_OK, true]) + ->setConstructorArgs([$source, 'original', 'mime/original', \UPLOAD_ERR_OK, true]) ->setMethods(['getSize', 'getClientSize']) ->getMock() ; /* should be modified when the getClientSize will be removed */ $file->expects($this->any()) ->method('getSize') - ->willReturn(INF) + ->willReturn(\INF) ; $file->expects($this->any()) ->method('getClientSize') - ->willReturn(PHP_INT_MAX) + ->willReturn(\PHP_INT_MAX) ; $client->request('POST', '/', [], [$file]); @@ -172,7 +172,7 @@ public function testUploadedFileWhenSizeExceedsUploadMaxFileSize() $file = $files[0]; $this->assertFalse($file->isValid()); - $this->assertEquals(UPLOAD_ERR_INI_SIZE, $file->getError()); + $this->assertEquals(\UPLOAD_ERR_INI_SIZE, $file->getError()); $this->assertEquals('mime/original', $file->getClientMimeType()); $this->assertEquals('original', $file->getClientOriginalName()); $this->assertEquals(0, $file->getSize()); diff --git a/src/Symfony/Component/HttpKernel/Tests/Log/LoggerTest.php b/src/Symfony/Component/HttpKernel/Tests/Log/LoggerTest.php index 5c7da4195711..607ab31cb8e4 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Log/LoggerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Log/LoggerTest.php @@ -59,7 +59,7 @@ public static function assertLogsMatch(array $expected, array $given) */ public function getLogs(): array { - return file($this->tmpFile, FILE_IGNORE_NEW_LINES); + return file($this->tmpFile, \FILE_IGNORE_NEW_LINES); } public function testImplements() @@ -186,7 +186,7 @@ public function testContextExceptionKeyCanBeExceptionOrOtherValues() public function testFormatter() { $this->logger = new Logger(LogLevel::DEBUG, $this->tmpFile, function ($level, $message, $context) { - return json_encode(['level' => $level, 'message' => $message, 'context' => $context]).PHP_EOL; + return json_encode(['level' => $level, 'message' => $message, 'context' => $context]).\PHP_EOL; }); $this->logger->error('An error', ['foo' => 'bar']); diff --git a/src/Symfony/Component/HttpKernel/Tests/Profiler/FileProfilerStorageTest.php b/src/Symfony/Component/HttpKernel/Tests/Profiler/FileProfilerStorageTest.php index 2df9a94884b6..a59d0cbe8e09 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Profiler/FileProfilerStorageTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Profiler/FileProfilerStorageTest.php @@ -354,7 +354,7 @@ public function testReadLineFromFile() $h = tmpfile(); fwrite($h, "line1\n\n\nline2\n"); - fseek($h, 0, SEEK_END); + fseek($h, 0, \SEEK_END); $this->assertEquals('line2', $r->invoke($this->storage, $h)); $this->assertEquals('line1', $r->invoke($this->storage, $h)); diff --git a/src/Symfony/Component/HttpKernel/UriSigner.php b/src/Symfony/Component/HttpKernel/UriSigner.php index df08dd69fce1..4f823966eedf 100644 --- a/src/Symfony/Component/HttpKernel/UriSigner.php +++ b/src/Symfony/Component/HttpKernel/UriSigner.php @@ -95,7 +95,7 @@ private function computeHash(string $uri): string private function buildUrl(array $url, array $params = []): string { - ksort($params, SORT_STRING); + ksort($params, \SORT_STRING); $url['query'] = http_build_query($params, '', '&'); $scheme = isset($url['scheme']) ? $url['scheme'].'://' : ''; diff --git a/src/Symfony/Component/HttpKernel/composer.json b/src/Symfony/Component/HttpKernel/composer.json index c016af236929..d29435754f72 100644 --- a/src/Symfony/Component/HttpKernel/composer.json +++ b/src/Symfony/Component/HttpKernel/composer.json @@ -20,6 +20,7 @@ "symfony/deprecation-contracts": "^2.1", "symfony/error-handler": "^4.4|^5.0", "symfony/event-dispatcher": "^5.0", + "symfony/http-client-contracts": "^1.1|^2", "symfony/http-foundation": "^4.4|^5.0", "symfony/polyfill-ctype": "^1.8", "symfony/polyfill-php73": "^1.9", diff --git a/src/Symfony/Component/Intl/Collator/Collator.php b/src/Symfony/Component/Intl/Collator/Collator.php index ff0d258e1d41..a43a4f69bf0e 100644 --- a/src/Symfony/Component/Intl/Collator/Collator.php +++ b/src/Symfony/Component/Intl/Collator/Collator.php @@ -109,9 +109,9 @@ public static function create(?string $locale) public function asort(array &$array, int $sortFlag = self::SORT_REGULAR) { $intlToPlainFlagMap = [ - self::SORT_REGULAR => SORT_REGULAR, - self::SORT_NUMERIC => SORT_NUMERIC, - self::SORT_STRING => SORT_STRING, + self::SORT_REGULAR => \SORT_REGULAR, + self::SORT_NUMERIC => \SORT_NUMERIC, + self::SORT_STRING => \SORT_STRING, ]; $plainSortFlag = isset($intlToPlainFlagMap[$sortFlag]) ? $intlToPlainFlagMap[$sortFlag] : self::SORT_REGULAR; diff --git a/src/Symfony/Component/Intl/Data/Bundle/Writer/JsonBundleWriter.php b/src/Symfony/Component/Intl/Data/Bundle/Writer/JsonBundleWriter.php index 0e114f38447c..4ecd4b93adb1 100644 --- a/src/Symfony/Component/Intl/Data/Bundle/Writer/JsonBundleWriter.php +++ b/src/Symfony/Component/Intl/Data/Bundle/Writer/JsonBundleWriter.php @@ -35,7 +35,7 @@ public function write(string $path, string $locale, $data) } }); - $contents = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)."\n"; + $contents = json_encode($data, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE)."\n"; file_put_contents($path.'/'.$locale.'.json', $contents); } diff --git a/src/Symfony/Component/Intl/Data/Generator/LocaleDataGenerator.php b/src/Symfony/Component/Intl/Data/Generator/LocaleDataGenerator.php index f6e9f67779f3..e234df4093e9 100644 --- a/src/Symfony/Component/Intl/Data/Generator/LocaleDataGenerator.php +++ b/src/Symfony/Component/Intl/Data/Generator/LocaleDataGenerator.php @@ -67,7 +67,7 @@ protected function preGenerate() // Write parents locale file for the Translation component file_put_contents( __DIR__.'/../../../Translation/Resources/data/parents.json', - json_encode($this->localeParents, JSON_PRETTY_PRINT).PHP_EOL + json_encode($this->localeParents, \JSON_PRETTY_PRINT).\PHP_EOL ); } diff --git a/src/Symfony/Component/Intl/Data/Util/LocaleScanner.php b/src/Symfony/Component/Intl/Data/Util/LocaleScanner.php index 7123d5bd32ad..ff189bc98bf8 100644 --- a/src/Symfony/Component/Intl/Data/Util/LocaleScanner.php +++ b/src/Symfony/Component/Intl/Data/Util/LocaleScanner.php @@ -40,7 +40,7 @@ class LocaleScanner */ public function scanLocales(string $sourceDir): array { - $locales = glob($sourceDir.'/*.txt', GLOB_NOSORT); + $locales = glob($sourceDir.'/*.txt', \GLOB_NOSORT); // Remove file extension and sort array_walk($locales, function (&$locale) { $locale = basename($locale, '.txt'); }); diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/Transformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/Transformer.php index 1a9a3eff3fee..235132394609 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/Transformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/Transformer.php @@ -60,6 +60,6 @@ abstract public function extractDateOptions(string $matched, int $length): array */ protected function padLeft(string $value, int $length): string { - return str_pad($value, $length, '0', STR_PAD_LEFT); + return str_pad($value, $length, '0', \STR_PAD_LEFT); } } diff --git a/src/Symfony/Component/Intl/Intl.php b/src/Symfony/Component/Intl/Intl.php index eb3bd582a8b5..4f8d4a76ac62 100644 --- a/src/Symfony/Component/Intl/Intl.php +++ b/src/Symfony/Component/Intl/Intl.php @@ -85,7 +85,7 @@ public static function getIcuVersion(): ?string if (!self::isExtensionLoaded()) { self::$icuVersion = self::getIcuStubVersion(); } elseif (\defined('INTL_ICU_VERSION')) { - self::$icuVersion = INTL_ICU_VERSION; + self::$icuVersion = \INTL_ICU_VERSION; } else { try { $reflector = new \ReflectionExtension('intl'); diff --git a/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php b/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php index 6d48949ef994..40223dc86da6 100644 --- a/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php +++ b/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php @@ -201,9 +201,9 @@ abstract class NumberFormatter * @see https://php.net/round */ private static $phpRoundingMap = [ - self::ROUND_HALFDOWN => PHP_ROUND_HALF_DOWN, - self::ROUND_HALFEVEN => PHP_ROUND_HALF_EVEN, - self::ROUND_HALFUP => PHP_ROUND_HALF_UP, + self::ROUND_HALFDOWN => \PHP_ROUND_HALF_DOWN, + self::ROUND_HALFEVEN => \PHP_ROUND_HALF_EVEN, + self::ROUND_HALFUP => \PHP_ROUND_HALF_UP, ]; /** @@ -354,7 +354,11 @@ public function format($value, int $type = self::TYPE_DEFAULT) { // The original NumberFormatter does not support this format type if (self::TYPE_CURRENCY === $type) { - trigger_error(__METHOD__.'(): Unsupported format type '.$type, E_USER_WARNING); + if (\PHP_VERSION_ID >= 80000) { + throw new \ValueError(sprintf('The format type must be a NumberFormatter::TYPE_* constant (%s given).', $type)); + } + + trigger_error(__METHOD__.'(): Unsupported format type '.$type, \E_USER_WARNING); return false; } @@ -508,7 +512,11 @@ public function parseCurrency(string $value, string &$currency, int &$position = public function parse(string $value, int $type = self::TYPE_DOUBLE, int &$position = 0) { if (self::TYPE_DEFAULT === $type || self::TYPE_CURRENCY === $type) { - trigger_error(__METHOD__.'(): Unsupported format type '.$type, E_USER_WARNING); + if (\PHP_VERSION_ID >= 80000) { + throw new \ValueError(sprintf('The format type must be a NumberFormatter::TYPE_* constant (%d given).', $type)); + } + + trigger_error(__METHOD__.'(): Unsupported format type '.$type, \E_USER_WARNING); return false; } @@ -683,7 +691,7 @@ private function roundCurrency(float $value, string $currency): float // Swiss rounding if (0 < $roundingIncrement && 0 < $fractionDigits) { - $roundingFactor = $roundingIncrement / pow(10, $fractionDigits); + $roundingFactor = $roundingIncrement / 10 ** $fractionDigits; $value = round($value / $roundingFactor) * $roundingFactor; } @@ -705,7 +713,7 @@ private function round($value, int $precision) if (isset(self::$phpRoundingMap[$roundingModeAttribute])) { $value = round($value, $precision, self::$phpRoundingMap[$roundingModeAttribute]); } elseif (isset(self::$customRoundingList[$roundingModeAttribute])) { - $roundingCoef = pow(10, $precision); + $roundingCoef = 10 ** $precision; $value *= $roundingCoef; $value = (float) (string) $value; diff --git a/src/Symfony/Component/Intl/Resources/bin/common.php b/src/Symfony/Component/Intl/Resources/bin/common.php index 5a93e40487cc..1ed762fee432 100644 --- a/src/Symfony/Component/Intl/Resources/bin/common.php +++ b/src/Symfony/Component/Intl/Resources/bin/common.php @@ -68,7 +68,7 @@ function get_icu_version_from_genrb($genrb) return $matches[1]; } -error_reporting(E_ALL); +error_reporting(\E_ALL); set_error_handler(function ($type, $msg, $file, $line) { throw new \ErrorException($msg, 0, $type, $file, $line); diff --git a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/BundleEntryReaderTest.php b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/BundleEntryReaderTest.php index 738b0d6fcebc..482999c60dd5 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/BundleEntryReaderTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/BundleEntryReaderTest.php @@ -144,7 +144,10 @@ public function testFallbackIfLocaleDoesNotExist() [self::RES_DIR, 'en_GB'], [self::RES_DIR, 'en'] ) - ->willReturnOnConsecutiveCalls(self::$data, self::$fallbackData); + ->willReturnOnConsecutiveCalls( + $this->throwException(new ResourceBundleNotFoundException()), + self::$fallbackData + ); $this->assertSame('Lah', $this->reader->readEntry(self::RES_DIR, 'en_GB', ['Entries', 'Bam'])); } @@ -283,7 +286,7 @@ public function testFailIfEntryFoundNeitherInParentNorChild() [self::RES_DIR, 'en_GB'], [self::RES_DIR, 'en'] ) - ->willReturnOnConsecutiveCalls(['Foo' => 'Baz'], ['Foo' => 'Baz']); + ->willReturnOnConsecutiveCalls(['Foo' => 'Baz'], ['Foo' => 'Bar']); $this->reader->readEntry(self::RES_DIR, 'en_GB', ['Foo', 'Bar'], true); } diff --git a/src/Symfony/Component/Intl/Tests/NumberFormatter/AbstractNumberFormatterTest.php b/src/Symfony/Component/Intl/Tests/NumberFormatter/AbstractNumberFormatterTest.php index 2d75509011e3..73c845180a34 100644 --- a/src/Symfony/Component/Intl/Tests/NumberFormatter/AbstractNumberFormatterTest.php +++ b/src/Symfony/Component/Intl/Tests/NumberFormatter/AbstractNumberFormatterTest.php @@ -324,7 +324,9 @@ public function formatTypeDoubleWithCurrencyStyleProvider() */ public function testFormatTypeCurrency($formatter, $value) { - if (method_exists($this, 'expectWarning')) { + if (\PHP_VERSION_ID >= 80000) { + $this->expectException(\ValueError::class); + } elseif (method_exists($this, 'expectWarning')) { $this->expectWarning(); } else { $this->expectException(Warning::class); @@ -338,6 +340,10 @@ public function testFormatTypeCurrency($formatter, $value) */ public function testFormatTypeCurrencyReturn($formatter, $value) { + if (\PHP_VERSION_ID >= 80000) { + $this->expectException(\ValueError::class); + } + $this->assertFalse(@$formatter->format($value, NumberFormatter::TYPE_CURRENCY)); } @@ -377,13 +383,11 @@ public function testFormatFractionDigits($value, $expected, $fractionDigits = nu public function formatFractionDigitsProvider() { - return [ - [1.123, '1.123', null, 0], - [1.123, '1', 0, 0], - [1.123, '1.1', 1, 1], - [1.123, '1.12', 2, 2], - [1.123, '1.123', -1, 0], - ]; + yield [1.123, '1.123', null, 0]; + yield [1.123, '1', 0, 0]; + yield [1.123, '1.1', 1, 1]; + yield [1.123, '1.12', 2, 2]; + yield [1.123, '1.123', -1, 0]; } /** @@ -409,13 +413,11 @@ public function testFormatGroupingUsed($value, $expected, $groupingUsed = null, public function formatGroupingUsedProvider() { - return [ - [1000, '1,000', null, 1], - [1000, '1000', 0, 0], - [1000, '1,000', 1, 1], - [1000, '1,000', 2, 1], - [1000, '1,000', -1, 1], - ]; + yield [1000, '1,000', null, 1]; + yield [1000, '1000', 0, 0]; + yield [1000, '1,000', 1, 1]; + yield [1000, '1,000', 2, 1]; + yield [1000, '1,000', -1, 1]; } /** @@ -703,7 +705,9 @@ public function parseProvider() public function testParseTypeDefault() { - if (method_exists($this, 'expectWarning')) { + if (\PHP_VERSION_ID >= 80000) { + $this->expectException(\ValueError::class); + } elseif (method_exists($this, 'expectWarning')) { $this->expectWarning(); } else { $this->expectException(Warning::class); @@ -827,7 +831,9 @@ public function parseTypeDoubleProvider() public function testParseTypeCurrency() { - if (method_exists($this, 'expectWarning')) { + if (\PHP_VERSION_ID >= 80000) { + $this->expectException(\ValueError::class); + } elseif (method_exists($this, 'expectWarning')) { $this->expectWarning(); } else { $this->expectException(Warning::class); diff --git a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Adapter.php b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Adapter.php index 39f5cbb81381..3106ba3ce4aa 100644 --- a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Adapter.php +++ b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Adapter.php @@ -72,7 +72,7 @@ public function escape(string $subject, string $ignore = '', int $flags = 0) $value = ldap_escape($subject, $ignore, $flags); // Per RFC 4514, leading/trailing spaces should be encoded in DNs, as well as carriage returns. - if ((int) $flags & LDAP_ESCAPE_DN) { + if ((int) $flags & \LDAP_ESCAPE_DN) { if (!empty($value) && ' ' === $value[0]) { $value = '\\20'.substr($value, 1); } diff --git a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Connection.php b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Connection.php index 407783ba1585..feaf22319fee 100644 --- a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Connection.php +++ b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Connection.php @@ -50,6 +50,8 @@ public function isBound() /** * {@inheritdoc} + * + * @param string $password WARNING: When the LDAP server allows unauthenticated binds, a blank $password will always be valid */ public function bind(string $dn = null, string $password = null) { diff --git a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Query.php b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Query.php index b9c1748b0f85..070ef4d775b2 100644 --- a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Query.php +++ b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Query.php @@ -193,14 +193,14 @@ private function resetPagination() // // This is not supported in PHP < 7.2, so these versions will remain broken. $ctl = []; - ldap_get_option($con, LDAP_OPT_SERVER_CONTROLS, $ctl); + ldap_get_option($con, \LDAP_OPT_SERVER_CONTROLS, $ctl); if (!empty($ctl)) { foreach ($ctl as $idx => $info) { if (static::PAGINATION_OID == $info['oid']) { unset($ctl[$idx]); } } - ldap_set_option($con, LDAP_OPT_SERVER_CONTROLS, $ctl); + ldap_set_option($con, \LDAP_OPT_SERVER_CONTROLS, $ctl); } } } diff --git a/src/Symfony/Component/Ldap/Adapter/ExtLdap/UpdateOperation.php b/src/Symfony/Component/Ldap/Adapter/ExtLdap/UpdateOperation.php index ca3e5decd948..4ef536efc689 100644 --- a/src/Symfony/Component/Ldap/Adapter/ExtLdap/UpdateOperation.php +++ b/src/Symfony/Component/Ldap/Adapter/ExtLdap/UpdateOperation.php @@ -20,10 +20,10 @@ class UpdateOperation private $attribute; private $validOperationTypes = [ - LDAP_MODIFY_BATCH_ADD, - LDAP_MODIFY_BATCH_REMOVE, - LDAP_MODIFY_BATCH_REMOVE_ALL, - LDAP_MODIFY_BATCH_REPLACE, + \LDAP_MODIFY_BATCH_ADD, + \LDAP_MODIFY_BATCH_REMOVE, + \LDAP_MODIFY_BATCH_REMOVE_ALL, + \LDAP_MODIFY_BATCH_REPLACE, ]; /** @@ -37,7 +37,7 @@ public function __construct(int $operationType, string $attribute, ?array $value if (!\in_array($operationType, $this->validOperationTypes, true)) { throw new UpdateOperationException(sprintf('"%s" is not a valid modification type.', $operationType)); } - if (LDAP_MODIFY_BATCH_REMOVE_ALL === $operationType && null !== $values) { + if (\LDAP_MODIFY_BATCH_REMOVE_ALL === $operationType && null !== $values) { throw new UpdateOperationException(sprintf('$values must be null for LDAP_MODIFY_BATCH_REMOVE_ALL operation, "%s" given.', get_debug_type($values))); } diff --git a/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/AdapterTest.php b/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/AdapterTest.php index 4c04d031ac1e..d17b47b1fadd 100644 --- a/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/AdapterTest.php +++ b/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/AdapterTest.php @@ -153,7 +153,7 @@ public function testLdapPagination() $this->assertEquals(\count($fully_paged_query->getResources()), 1); $this->assertEquals(\count($paged_query->getResources()), 5); - if (PHP_MAJOR_VERSION > 7 || (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION >= 2)) { + if (\PHP_MAJOR_VERSION > 7 || (\PHP_MAJOR_VERSION == 7 && \PHP_MINOR_VERSION >= 2)) { // This last query is to ensure that we haven't botched the state of our connection // by not resetting pagination properly. extldap <= PHP 7.1 do not implement the necessary // bits to work around an implementation flaw, so we simply can't guarantee this to work there. diff --git a/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/LdapManagerTest.php b/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/LdapManagerTest.php index ae45097c066e..e23e8018547b 100644 --- a/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/LdapManagerTest.php +++ b/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/LdapManagerTest.php @@ -272,7 +272,7 @@ public function testLdapApplyOperationsRemoveAllWithArrayError() $this->expectException(UpdateOperationException::class); - $entryManager->applyOperations($entry->getDn(), [new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE_ALL, 'mail', [])]); + $entryManager->applyOperations($entry->getDn(), [new UpdateOperation(\LDAP_MODIFY_BATCH_REMOVE_ALL, 'mail', [])]); } public function testLdapApplyOperationsWithWrongConstantError() @@ -295,8 +295,8 @@ public function testApplyOperationsAddRemoveAttributeValues() $entry = $result[0]; $entryManager->applyOperations($entry->getDn(), [ - new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot@example.org', 'fabpot2@example.org']), - new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot3@example.org', 'fabpot4@example.org']), + new UpdateOperation(\LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot@example.org', 'fabpot2@example.org']), + new UpdateOperation(\LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot3@example.org', 'fabpot4@example.org']), ]); $result = $this->executeSearchQuery(1); @@ -305,8 +305,8 @@ public function testApplyOperationsAddRemoveAttributeValues() $this->assertCount(6, $newEntry->getAttribute('mail')); $entryManager->applyOperations($entry->getDn(), [ - new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE, 'mail', ['fabpot@example.org', 'fabpot2@example.org']), - new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE, 'mail', ['fabpot3@example.org', 'fabpot4@example.org']), + new UpdateOperation(\LDAP_MODIFY_BATCH_REMOVE, 'mail', ['fabpot@example.org', 'fabpot2@example.org']), + new UpdateOperation(\LDAP_MODIFY_BATCH_REMOVE, 'mail', ['fabpot3@example.org', 'fabpot4@example.org']), ]); $result = $this->executeSearchQuery(1); @@ -318,13 +318,13 @@ public function testApplyOperationsAddRemoveAttributeValues() public function testUpdateOperationsWithIterator() { $iteratorAdd = new \ArrayIterator([ - new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot@example.org', 'fabpot2@example.org']), - new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot3@example.org', 'fabpot4@example.org']), + new UpdateOperation(\LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot@example.org', 'fabpot2@example.org']), + new UpdateOperation(\LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot3@example.org', 'fabpot4@example.org']), ]); $iteratorRemove = new \ArrayIterator([ - new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE, 'mail', ['fabpot@example.org', 'fabpot2@example.org']), - new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE, 'mail', ['fabpot3@example.org', 'fabpot4@example.org']), + new UpdateOperation(\LDAP_MODIFY_BATCH_REMOVE, 'mail', ['fabpot@example.org', 'fabpot2@example.org']), + new UpdateOperation(\LDAP_MODIFY_BATCH_REMOVE, 'mail', ['fabpot3@example.org', 'fabpot4@example.org']), ]); $entryManager = $this->adapter->getEntryManager(); @@ -350,8 +350,8 @@ public function testUpdateOperationsWithIterator() public function testUpdateOperationsThrowsExceptionWhenAddedDuplicatedValue() { $duplicateIterator = new \ArrayIterator([ - new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot@example.org']), - new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot@example.org']), + new UpdateOperation(\LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot@example.org']), + new UpdateOperation(\LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot@example.org']), ]); $entryManager = $this->adapter->getEntryManager(); diff --git a/src/Symfony/Component/Lock/Store/FlockStore.php b/src/Symfony/Component/Lock/Store/FlockStore.php index b2a8bc20d502..4f2fca8b508d 100644 --- a/src/Symfony/Component/Lock/Store/FlockStore.php +++ b/src/Symfony/Component/Lock/Store/FlockStore.php @@ -95,7 +95,7 @@ private function lock(Key $key, bool $blocking) // On Windows, even if PHP doc says the contrary, LOCK_NB works, see // https://bugs.php.net/54129 - if (!flock($handle, LOCK_EX | ($blocking ? 0 : LOCK_NB))) { + if (!flock($handle, \LOCK_EX | ($blocking ? 0 : \LOCK_NB))) { fclose($handle); throw new LockConflictedException(); } @@ -123,7 +123,7 @@ public function delete(Key $key) $handle = $key->getState(__CLASS__); - flock($handle, LOCK_UN | LOCK_NB); + flock($handle, \LOCK_UN | \LOCK_NB); fclose($handle); $key->removeState(__CLASS__); diff --git a/src/Symfony/Component/Lock/Store/MongoDbStore.php b/src/Symfony/Component/Lock/Store/MongoDbStore.php index 76a010fa3005..5959c5c16b4c 100644 --- a/src/Symfony/Component/Lock/Store/MongoDbStore.php +++ b/src/Symfony/Component/Lock/Store/MongoDbStore.php @@ -217,7 +217,7 @@ public function save(Key $key) throw new LockAcquiringException('Failed to acquire lock.', 0, $e); } - if ($this->options['gcProbablity'] > 0.0 && (1.0 === $this->options['gcProbablity'] || (random_int(0, PHP_INT_MAX) / PHP_INT_MAX) <= $this->options['gcProbablity'])) { + if ($this->options['gcProbablity'] > 0.0 && (1.0 === $this->options['gcProbablity'] || (random_int(0, \PHP_INT_MAX) / \PHP_INT_MAX) <= $this->options['gcProbablity'])) { $this->createTtlIndex(); } diff --git a/src/Symfony/Component/Lock/Store/PdoStore.php b/src/Symfony/Component/Lock/Store/PdoStore.php index cec9a2a97c1b..51c1f27cb9d8 100644 --- a/src/Symfony/Component/Lock/Store/PdoStore.php +++ b/src/Symfony/Component/Lock/Store/PdoStore.php @@ -15,6 +15,7 @@ use Doctrine\DBAL\DBALException; use Doctrine\DBAL\Driver\Result; use Doctrine\DBAL\DriverManager; +use Doctrine\DBAL\Exception; use Doctrine\DBAL\Schema\Schema; use Symfony\Component\Lock\Exception\InvalidArgumentException; use Symfony\Component\Lock\Exception\InvalidTtlException; @@ -126,7 +127,7 @@ public function save(Key $key) try { $stmt->execute(); - } catch (DBALException $e) { + } catch (DBALException | Exception $e) { // the lock is already acquired. It could be us. Let's try to put off. $this->putOffExpiration($key, $this->initialTtl); } catch (\PDOException $e) { @@ -134,7 +135,7 @@ public function save(Key $key) $this->putOffExpiration($key, $this->initialTtl); } - if ($this->gcProbability > 0 && (1.0 === $this->gcProbability || (random_int(0, PHP_INT_MAX) / PHP_INT_MAX) <= $this->gcProbability)) { + if ($this->gcProbability > 0 && (1.0 === $this->gcProbability || (random_int(0, \PHP_INT_MAX) / \PHP_INT_MAX) <= $this->gcProbability)) { $this->prune(); } @@ -240,6 +241,7 @@ private function getConnection(): object * * @throws \PDOException When the table already exists * @throws DBALException When the table already exists + * @throws Exception When the table already exists * @throws \DomainException When an unsupported PDO driver is used */ public function createTable(): void diff --git a/src/Symfony/Component/Lock/Store/RetryTillSaveStore.php b/src/Symfony/Component/Lock/Store/RetryTillSaveStore.php index fdb1df65acb8..c73ac06f3c1e 100644 --- a/src/Symfony/Component/Lock/Store/RetryTillSaveStore.php +++ b/src/Symfony/Component/Lock/Store/RetryTillSaveStore.php @@ -37,7 +37,7 @@ class RetryTillSaveStore implements BlockingStoreInterface, LoggerAwareInterface * @param int $retrySleep Duration in ms between 2 retry * @param int $retryCount Maximum amount of retry */ - public function __construct(PersistingStoreInterface $decorated, int $retrySleep = 100, int $retryCount = PHP_INT_MAX) + public function __construct(PersistingStoreInterface $decorated, int $retrySleep = 100, int $retryCount = \PHP_INT_MAX) { $this->decorated = $decorated; $this->retrySleep = $retrySleep; diff --git a/src/Symfony/Component/Lock/Tests/Store/BlockingStoreTestTrait.php b/src/Symfony/Component/Lock/Tests/Store/BlockingStoreTestTrait.php index 55d8d34c868d..7bcf05a8df8c 100644 --- a/src/Symfony/Component/Lock/Tests/Store/BlockingStoreTestTrait.php +++ b/src/Symfony/Component/Lock/Tests/Store/BlockingStoreTestTrait.php @@ -50,11 +50,11 @@ public function testBlockingLocks() $parentPID = posix_getpid(); // Block SIGHUP signal - pcntl_sigprocmask(SIG_BLOCK, [SIGHUP]); + pcntl_sigprocmask(\SIG_BLOCK, [\SIGHUP]); if ($childPID = pcntl_fork()) { // Wait the start of the child - pcntl_sigwaitinfo([SIGHUP], $info); + pcntl_sigwaitinfo([\SIGHUP], $info); $store = $this->getStore(); try { @@ -66,7 +66,7 @@ public function testBlockingLocks() } // send the ready signal to the child - posix_kill($childPID, SIGHUP); + posix_kill($childPID, \SIGHUP); // This call should be blocked by the child #1 try { @@ -82,23 +82,23 @@ public function testBlockingLocks() } } else { // Block SIGHUP signal - pcntl_sigprocmask(SIG_BLOCK, [SIGHUP]); + pcntl_sigprocmask(\SIG_BLOCK, [\SIGHUP]); try { $store = $this->getStore(); $store->save($key); // send the ready signal to the parent - posix_kill($parentPID, SIGHUP); + posix_kill($parentPID, \SIGHUP); // Wait for the parent to be ready - pcntl_sigwaitinfo([SIGHUP], $info); + pcntl_sigwaitinfo([\SIGHUP], $info); // Wait ClockDelay to let parent assert to finish usleep($clockDelay); $store->delete($key); exit(0); } catch (\Throwable $e) { - posix_kill($parentPID, SIGHUP); + posix_kill($parentPID, \SIGHUP); exit(1); } } diff --git a/src/Symfony/Component/Lock/Tests/Store/SemaphoreStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/SemaphoreStoreTest.php index cf537a4c2490..0611e2802c07 100644 --- a/src/Symfony/Component/Lock/Tests/Store/SemaphoreStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/SemaphoreStoreTest.php @@ -47,22 +47,22 @@ public function testResourceRemoval() private function getOpenedSemaphores() { - if ('Darwin' === PHP_OS) { - $lines = explode(PHP_EOL, trim(shell_exec('ipcs -s'))); + if ('Darwin' === \PHP_OS) { + $lines = explode(\PHP_EOL, trim(shell_exec('ipcs -s'))); if (-1 === $start = array_search('Semaphores:', $lines)) { - throw new \Exception('Failed to extract list of opened semaphores. Expected a Semaphore list, got '.implode(PHP_EOL, $lines)); + throw new \Exception('Failed to extract list of opened semaphores. Expected a Semaphore list, got '.implode(\PHP_EOL, $lines)); } return \count(\array_slice($lines, ++$start)); } - $lines = explode(PHP_EOL, trim(shell_exec('LC_ALL=C ipcs -su'))); + $lines = explode(\PHP_EOL, trim(shell_exec('LC_ALL=C ipcs -su'))); if ('------ Semaphore Status --------' !== $lines[0]) { - throw new \Exception('Failed to extract list of opened semaphores. Expected a Semaphore status, got '.implode(PHP_EOL, $lines)); + throw new \Exception('Failed to extract list of opened semaphores. Expected a Semaphore status, got '.implode(\PHP_EOL, $lines)); } list($key, $value) = explode(' = ', $lines[1]); if ('used arrays' !== $key) { - throw new \Exception('Failed to extract list of opened semaphores. Expected a "used arrays" key, got '.implode(PHP_EOL, $lines)); + throw new \Exception('Failed to extract list of opened semaphores. Expected a "used arrays" key, got '.implode(\PHP_EOL, $lines)); } return (int) $value; diff --git a/src/Symfony/Component/Mailer/Bridge/Mailgun/Tests/Transport/MailgunApiTransportTest.php b/src/Symfony/Component/Mailer/Bridge/Mailgun/Tests/Transport/MailgunApiTransportTest.php index fddd9154d1be..67f0c7b935bc 100644 --- a/src/Symfony/Component/Mailer/Bridge/Mailgun/Tests/Transport/MailgunApiTransportTest.php +++ b/src/Symfony/Component/Mailer/Bridge/Mailgun/Tests/Transport/MailgunApiTransportTest.php @@ -180,6 +180,35 @@ public function testSendThrowsForErrorResponse() $transport->send($mail); } + public function testSendThrowsForErrorResponseWithContentTypeTextHtml() + { + $client = new MockHttpClient(function (string $method, string $url, array $options): ResponseInterface { + $this->assertSame('POST', $method); + $this->assertSame('https://api.mailgun.net:8984/v3/symfony/messages', $url); + $this->assertStringContainsStringIgnoringCase('Authorization: Basic YXBpOkFDQ0VTU19LRVk=', $options['headers'][2] ?? $options['request_headers'][1]); + + // NOTE: Mailgun API does this even if "Accept" request header value is "application/json". + return new MockResponse('Forbidden', [ + 'http_code' => 401, + 'response_headers' => [ + 'content-type' => 'text/html', + ], + ]); + }); + $transport = new MailgunApiTransport('ACCESS_KEY', 'symfony', 'us', $client); + $transport->setPort(8984); + + $mail = new Email(); + $mail->subject('Hello!') + ->to(new Address('saif.gmati@symfony.com', 'Saif Eddin')) + ->from(new Address('fabpot@symfony.com', 'Fabien')) + ->text('Hello There!'); + + $this->expectException(HttpTransportException::class); + $this->expectExceptionMessage('Unable to send an email: Forbidden (code 401).'); + $transport->send($mail); + } + public function testTagAndMetadataHeaders() { $json = json_encode(['foo' => 'bar']); diff --git a/src/Symfony/Component/Mailer/Bridge/Mailgun/Transport/MailgunApiTransport.php b/src/Symfony/Component/Mailer/Bridge/Mailgun/Transport/MailgunApiTransport.php index 636a218de15a..33d0fb1ff52c 100644 --- a/src/Symfony/Component/Mailer/Bridge/Mailgun/Transport/MailgunApiTransport.php +++ b/src/Symfony/Component/Mailer/Bridge/Mailgun/Transport/MailgunApiTransport.php @@ -64,15 +64,17 @@ protected function doSendApi(SentMessage $sentMessage, Email $email, Envelope $e 'body' => $body->bodyToIterable(), ]); - $result = $response->toArray(false); if (200 !== $response->getStatusCode()) { if ('application/json' === $response->getHeaders(false)['content-type'][0]) { + $result = $response->toArray(false); throw new HttpTransportException('Unable to send an email: '.$result['message'].sprintf(' (code %d).', $response->getStatusCode()), $response); } throw new HttpTransportException('Unable to send an email: '.$response->getContent(false).sprintf(' (code %d).', $response->getStatusCode()), $response); } + // The assumption here is that all 200 responses are "application/json", so it's safe to call "toArray". + $result = $response->toArray(false); $sentMessage->setMessageId($result['id']); return $response; @@ -135,7 +137,7 @@ private function getPayload(Email $email, Envelope $envelope): array } else { // fallback to prefix with "h:" to not break BC $headerName = 'h:'.$name; - @trigger_error(sprintf('Not prefixing the Mailgun header name with "h:" is deprecated since Symfony 5.1. Use header name "%s" instead.', $headerName), E_USER_DEPRECATED); + @trigger_error(sprintf('Not prefixing the Mailgun header name with "h:" is deprecated since Symfony 5.1. Use header name "%s" instead.', $headerName), \E_USER_DEPRECATED); } $payload[$headerName] = $header->getBodyAsString(); diff --git a/src/Symfony/Component/Mailer/Transport/Smtp/EsmtpTransport.php b/src/Symfony/Component/Mailer/Transport/Smtp/EsmtpTransport.php index afa522ae97e1..adfcb55eaa3f 100644 --- a/src/Symfony/Component/Mailer/Transport/Smtp/EsmtpTransport.php +++ b/src/Symfony/Component/Mailer/Transport/Smtp/EsmtpTransport.php @@ -166,7 +166,11 @@ private function handleAuth(array $modes): void return; } catch (TransportExceptionInterface $e) { - $this->executeCommand("RSET\r\n", [250]); + try { + $this->executeCommand("RSET\r\n", [250]); + } catch (TransportExceptionInterface $_) { + // ignore this exception as it probably means that the server error was final + } // keep the error message, but tries the other authenticators $errors[$authenticator->getAuthKeyword()] = $e; diff --git a/src/Symfony/Component/Mailer/Transport/Smtp/EsmtpTransportFactory.php b/src/Symfony/Component/Mailer/Transport/Smtp/EsmtpTransportFactory.php index aab222b55b68..da56a0a0c955 100644 --- a/src/Symfony/Component/Mailer/Transport/Smtp/EsmtpTransportFactory.php +++ b/src/Symfony/Component/Mailer/Transport/Smtp/EsmtpTransportFactory.php @@ -29,7 +29,7 @@ public function create(Dsn $dsn): TransportInterface $transport = new EsmtpTransport($host, $port, $tls, $this->dispatcher, $this->logger); - if ('' !== $dsn->getOption('verify_peer') && !filter_var($dsn->getOption('verify_peer', true), FILTER_VALIDATE_BOOLEAN)) { + if ('' !== $dsn->getOption('verify_peer') && !filter_var($dsn->getOption('verify_peer', true), \FILTER_VALIDATE_BOOLEAN)) { /** @var SocketStream $stream */ $stream = $transport->getStream(); $streamOptions = $stream->getStreamOptions(); diff --git a/src/Symfony/Component/Mailer/Transport/Smtp/SmtpTransport.php b/src/Symfony/Component/Mailer/Transport/Smtp/SmtpTransport.php index 26f2057f941a..365bcd1f8ba9 100644 --- a/src/Symfony/Component/Mailer/Transport/Smtp/SmtpTransport.php +++ b/src/Symfony/Component/Mailer/Transport/Smtp/SmtpTransport.php @@ -103,9 +103,9 @@ public function setPingThreshold(int $seconds): self public function setLocalDomain(string $domain): self { if ('' !== $domain && '[' !== $domain[0]) { - if (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + if (filter_var($domain, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) { $domain = '['.$domain.']'; - } elseif (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { + } elseif (filter_var($domain, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) { $domain = '[IPv6:'.$domain.']'; } } diff --git a/src/Symfony/Component/Mailer/Transport/Smtp/Stream/SocketStream.php b/src/Symfony/Component/Mailer/Transport/Smtp/Stream/SocketStream.php index 41e8c368e1e5..3ff44105d133 100644 --- a/src/Symfony/Component/Mailer/Transport/Smtp/Stream/SocketStream.php +++ b/src/Symfony/Component/Mailer/Transport/Smtp/Stream/SocketStream.php @@ -131,7 +131,7 @@ public function initialize(): void $options = array_merge($options, $this->streamContextOptions); } // do it unconditionnally as it will be used by STARTTLS as well if supported - $options['ssl']['crypto_method'] = $options['ssl']['crypto_method'] ?? STREAM_CRYPTO_METHOD_TLS_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; + $options['ssl']['crypto_method'] = $options['ssl']['crypto_method'] ?? \STREAM_CRYPTO_METHOD_TLS_CLIENT | \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; $streamContext = stream_context_create($options); $timeout = $this->getTimeout(); @@ -139,7 +139,7 @@ public function initialize(): void throw new TransportException(sprintf('Connection could not be established with host "%s": ', $this->url).$msg); }); try { - $this->stream = stream_socket_client($this->url, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $streamContext); + $this->stream = stream_socket_client($this->url, $errno, $errstr, $timeout, \STREAM_CLIENT_CONNECT, $streamContext); } finally { restore_error_handler(); } diff --git a/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Transport/Connection.php b/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Transport/Connection.php index da72a795dab1..96f8d17eb2b6 100644 --- a/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Transport/Connection.php +++ b/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Transport/Connection.php @@ -318,6 +318,7 @@ public function send(string $body, array $headers, int $delay = 0, ?string $mess if (self::isFifoQueue($this->configuration['queue_name'])) { $parameters['MessageGroupId'] = null !== $messageGroupId ? $messageGroupId : __METHOD__; $parameters['MessageDeduplicationId'] = null !== $messageDeduplicationId ? $messageDeduplicationId : sha1(json_encode(['body' => $body, 'headers' => $headers])); + unset($parameters['DelaySeconds']); } $this->client->sendMessage($parameters); diff --git a/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpReceiverTest.php b/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpReceiverTest.php index a674c60b4709..9116a3682e1c 100644 --- a/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpReceiverTest.php +++ b/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpReceiverTest.php @@ -67,7 +67,7 @@ public function testItThrowsATransportExceptionIfItCannotRejectMessage() $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); $connection->method('getQueueNames')->willReturn(['queueName']); $connection->method('get')->with('queueName')->willReturn($amqpEnvelope); - $connection->method('nack')->with($amqpEnvelope, 'queueName', AMQP_NOPARAM)->willThrowException(new \AMQPException()); + $connection->method('nack')->with($amqpEnvelope, 'queueName', \AMQP_NOPARAM)->willThrowException(new \AMQPException()); $receiver = new AmqpReceiver($connection, $serializer); $receiver->reject(new Envelope(new \stdClass(), [new AmqpReceivedStamp($amqpEnvelope, 'queueName')])); diff --git a/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpSenderTest.php b/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpSenderTest.php index ff83cd1c0c0e..47f47eeb7b43 100644 --- a/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpSenderTest.php +++ b/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpSenderTest.php @@ -79,7 +79,7 @@ public function testContentTypeHeaderIsMovedToAttribute() $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); unset($encoded['headers']['Content-Type']); - $stamp = new AmqpStamp(null, AMQP_NOPARAM, ['content_type' => 'application/json']); + $stamp = new AmqpStamp(null, \AMQP_NOPARAM, ['content_type' => 'application/json']); $connection->expects($this->once())->method('publish')->with($encoded['body'], $encoded['headers'], 0, $stamp); $sender = new AmqpSender($connection, $serializer); @@ -88,7 +88,7 @@ public function testContentTypeHeaderIsMovedToAttribute() public function testContentTypeHeaderDoesNotOverwriteAttribute() { - $envelope = (new Envelope(new DummyMessage('Oy')))->with($stamp = new AmqpStamp('rk', AMQP_NOPARAM, ['content_type' => 'custom'])); + $envelope = (new Envelope(new DummyMessage('Oy')))->with($stamp = new AmqpStamp('rk', \AMQP_NOPARAM, ['content_type' => 'custom'])); $encoded = ['body' => '...', 'headers' => ['type' => DummyMessage::class, 'Content-Type' => 'application/json']]; $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); diff --git a/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpStampTest.php b/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpStampTest.php index 20427b7adbc0..16bcf027f2ae 100644 --- a/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpStampTest.php +++ b/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpStampTest.php @@ -23,15 +23,15 @@ public function testRoutingKeyOnly() { $stamp = new AmqpStamp('routing_key'); $this->assertSame('routing_key', $stamp->getRoutingKey()); - $this->assertSame(AMQP_NOPARAM, $stamp->getFlags()); + $this->assertSame(\AMQP_NOPARAM, $stamp->getFlags()); $this->assertSame([], $stamp->getAttributes()); } public function testFlagsAndAttributes() { - $stamp = new AmqpStamp(null, AMQP_DURABLE, ['delivery_mode' => 'unknown']); + $stamp = new AmqpStamp(null, \AMQP_DURABLE, ['delivery_mode' => 'unknown']); $this->assertNull($stamp->getRoutingKey()); - $this->assertSame(AMQP_DURABLE, $stamp->getFlags()); + $this->assertSame(\AMQP_DURABLE, $stamp->getFlags()); $this->assertSame(['delivery_mode' => 'unknown'], $stamp->getAttributes()); } @@ -49,7 +49,7 @@ public function testCreateFromAmqpEnvelope() $this->assertSame($amqpEnvelope->getDeliveryMode(), $stamp->getAttributes()['delivery_mode']); $this->assertSame($amqpEnvelope->getPriority(), $stamp->getAttributes()['priority']); $this->assertSame($amqpEnvelope->getAppId(), $stamp->getAttributes()['app_id']); - $this->assertSame(AMQP_NOPARAM, $stamp->getFlags()); + $this->assertSame(\AMQP_NOPARAM, $stamp->getFlags()); } public function testCreateFromAmqpEnvelopeWithPreviousStamp() @@ -60,7 +60,7 @@ public function testCreateFromAmqpEnvelopeWithPreviousStamp() $amqpEnvelope->method('getPriority')->willReturn(5); $amqpEnvelope->method('getAppId')->willReturn('appid'); - $previousStamp = new AmqpStamp('otherroutingkey', AMQP_MANDATORY, ['priority' => 8]); + $previousStamp = new AmqpStamp('otherroutingkey', \AMQP_MANDATORY, ['priority' => 8]); $stamp = AmqpStamp::createFromAmqpEnvelope($amqpEnvelope, $previousStamp); @@ -68,6 +68,6 @@ public function testCreateFromAmqpEnvelopeWithPreviousStamp() $this->assertSame($amqpEnvelope->getDeliveryMode(), $stamp->getAttributes()['delivery_mode']); $this->assertSame(8, $stamp->getAttributes()['priority']); $this->assertSame($amqpEnvelope->getAppId(), $stamp->getAttributes()['app_id']); - $this->assertSame(AMQP_MANDATORY, $stamp->getFlags()); + $this->assertSame(\AMQP_MANDATORY, $stamp->getFlags()); } } diff --git a/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/ConnectionTest.php b/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/ConnectionTest.php index 81b8e45d858f..81f317f36e33 100644 --- a/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/ConnectionTest.php +++ b/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/ConnectionTest.php @@ -266,7 +266,7 @@ public function testItSetupsTheConnectionWithDefaults() ); $amqpExchange->expects($this->once())->method('declareExchange'); - $amqpExchange->expects($this->once())->method('publish')->with('body', null, AMQP_NOPARAM, ['headers' => [], 'delivery_mode' => 2]); + $amqpExchange->expects($this->once())->method('publish')->with('body', null, \AMQP_NOPARAM, ['headers' => [], 'delivery_mode' => 2]); $amqpQueue->expects($this->once())->method('declareQueue'); $amqpQueue->expects($this->once())->method('bind')->with(self::DEFAULT_EXCHANGE_NAME, null); @@ -289,7 +289,7 @@ public function testItSetupsTheConnection() $factory->method('createQueue')->will($this->onConsecutiveCalls($amqpQueue0, $amqpQueue1)); $amqpExchange->expects($this->once())->method('declareExchange'); - $amqpExchange->expects($this->once())->method('publish')->with('body', 'routing_key', AMQP_NOPARAM, ['headers' => [], 'delivery_mode' => 2]); + $amqpExchange->expects($this->once())->method('publish')->with('body', 'routing_key', \AMQP_NOPARAM, ['headers' => [], 'delivery_mode' => 2]); $amqpQueue0->expects($this->once())->method('declareQueue'); $amqpQueue0->expects($this->exactly(2))->method('bind')->withConsecutive( [self::DEFAULT_EXCHANGE_NAME, 'binding_key0'], @@ -326,7 +326,7 @@ public function testBindingArguments() $factory->method('createQueue')->willReturn($amqpQueue); $amqpExchange->expects($this->once())->method('declareExchange'); - $amqpExchange->expects($this->once())->method('publish')->with('body', null, AMQP_NOPARAM, ['headers' => [], 'delivery_mode' => 2]); + $amqpExchange->expects($this->once())->method('publish')->with('body', null, \AMQP_NOPARAM, ['headers' => [], 'delivery_mode' => 2]); $amqpQueue->expects($this->once())->method('declareQueue'); $amqpQueue->expects($this->exactly(1))->method('bind')->withConsecutive( [self::DEFAULT_EXCHANGE_NAME, null, ['x-match' => 'all']] @@ -439,7 +439,7 @@ public function testItDelaysTheMessage() $delayQueue->expects($this->once())->method('declareQueue'); $delayQueue->expects($this->once())->method('bind')->with('delays', 'delay_messages__5000'); - $delayExchange->expects($this->once())->method('publish')->with('{}', 'delay_messages__5000', AMQP_NOPARAM, ['headers' => ['x-some-headers' => 'foo'], 'delivery_mode' => 2]); + $delayExchange->expects($this->once())->method('publish')->with('{}', 'delay_messages__5000', \AMQP_NOPARAM, ['headers' => ['x-some-headers' => 'foo'], 'delivery_mode' => 2]); $connection = Connection::fromDsn('amqp://localhost', [], $factory); $connection->publish('{}', ['x-some-headers' => 'foo'], 5000); @@ -481,14 +481,14 @@ public function testItDelaysTheMessageWithADifferentRoutingKeyAndTTLs() $delayQueue->expects($this->once())->method('declareQueue'); $delayQueue->expects($this->once())->method('bind')->with('delays', 'delay_messages__120000'); - $delayExchange->expects($this->once())->method('publish')->with('{}', 'delay_messages__120000', AMQP_NOPARAM, ['headers' => [], 'delivery_mode' => 2]); + $delayExchange->expects($this->once())->method('publish')->with('{}', 'delay_messages__120000', \AMQP_NOPARAM, ['headers' => [], 'delivery_mode' => 2]); $connection->publish('{}', [], 120000); } public function testObfuscatePasswordInDsn() { $this->expectException('AMQPException'); - $this->expectExceptionMessage('Could not connect to the AMQP server. Please verify the provided DSN. ({"host":"localhost","port":5672,"vhost":"\/","login":"user","password":"********"})'); + $this->expectExceptionMessage('Could not connect to the AMQP server. Please verify the provided DSN. ({"host":"localhost","port":5672,"vhost":"/","login":"user","password":"********"})'); $factory = new TestAmqpFactory( $amqpConnection = $this->createMock(\AMQPConnection::class), $amqpChannel = $this->createMock(\AMQPChannel::class), @@ -513,10 +513,10 @@ public function testAmqpStampHeadersAreUsed() $amqpExchange = $this->createMock(\AMQPExchange::class) ); - $amqpExchange->expects($this->once())->method('publish')->with('body', null, AMQP_NOPARAM, ['headers' => ['Foo' => 'X', 'Bar' => 'Y'], 'delivery_mode' => 2]); + $amqpExchange->expects($this->once())->method('publish')->with('body', null, \AMQP_NOPARAM, ['headers' => ['Foo' => 'X', 'Bar' => 'Y'], 'delivery_mode' => 2]); $connection = Connection::fromDsn('amqp://localhost', [], $factory); - $connection->publish('body', ['Foo' => 'X'], 0, new AmqpStamp(null, AMQP_NOPARAM, ['headers' => ['Bar' => 'Y']])); + $connection->publish('body', ['Foo' => 'X'], 0, new AmqpStamp(null, \AMQP_NOPARAM, ['headers' => ['Bar' => 'Y']])); } public function testAmqpStampDelireryModeIsUsed() @@ -528,10 +528,10 @@ public function testAmqpStampDelireryModeIsUsed() $amqpExchange = $this->createMock(\AMQPExchange::class) ); - $amqpExchange->expects($this->once())->method('publish')->with('body', null, AMQP_NOPARAM, ['headers' => [], 'delivery_mode' => 1]); + $amqpExchange->expects($this->once())->method('publish')->with('body', null, \AMQP_NOPARAM, ['headers' => [], 'delivery_mode' => 1]); $connection = Connection::fromDsn('amqp://localhost', [], $factory); - $connection->publish('body', [], 0, new AmqpStamp(null, AMQP_NOPARAM, ['delivery_mode' => 1])); + $connection->publish('body', [], 0, new AmqpStamp(null, \AMQP_NOPARAM, ['delivery_mode' => 1])); } public function testItCanPublishWithTheDefaultRoutingKey() @@ -600,7 +600,7 @@ public function testItDelaysTheMessageWithTheInitialSuppliedRoutingKeyAsArgument $delayQueue->expects($this->once())->method('declareQueue'); $delayQueue->expects($this->once())->method('bind')->with('delays', 'delay_messages_routing_key_120000'); - $delayExchange->expects($this->once())->method('publish')->with('{}', 'delay_messages_routing_key_120000', AMQP_NOPARAM, ['headers' => [], 'delivery_mode' => 2]); + $delayExchange->expects($this->once())->method('publish')->with('{}', 'delay_messages_routing_key_120000', \AMQP_NOPARAM, ['headers' => [], 'delivery_mode' => 2]); $connection->publish('{}', [], 120000, new AmqpStamp('routing_key')); } @@ -616,12 +616,12 @@ public function testItCanPublishWithCustomFlagsAndAttributes() $amqpExchange->expects($this->once())->method('publish')->with( 'body', 'routing_key', - AMQP_IMMEDIATE, + \AMQP_IMMEDIATE, ['delivery_mode' => 2, 'headers' => ['type' => DummyMessage::class]] ); $connection = Connection::fromDsn('amqp://localhost', [], $factory); - $connection->publish('body', ['type' => DummyMessage::class], 0, new AmqpStamp('routing_key', AMQP_IMMEDIATE, ['delivery_mode' => 2])); + $connection->publish('body', ['type' => DummyMessage::class], 0, new AmqpStamp('routing_key', \AMQP_IMMEDIATE, ['delivery_mode' => 2])); } } diff --git a/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/AmqpReceiver.php b/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/AmqpReceiver.php index a5c89ef13861..009e7be8d55b 100644 --- a/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/AmqpReceiver.php +++ b/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/AmqpReceiver.php @@ -120,7 +120,7 @@ public function getMessageCount(): int private function rejectAmqpEnvelope(\AMQPEnvelope $amqpEnvelope, string $queueName): void { try { - $this->connection->nack($amqpEnvelope, $queueName, AMQP_NOPARAM); + $this->connection->nack($amqpEnvelope, $queueName, \AMQP_NOPARAM); } catch (\AMQPException $exception) { throw new TransportException($exception->getMessage(), 0, $exception); } diff --git a/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/AmqpStamp.php b/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/AmqpStamp.php index 9e3f63e0a204..7d013974cc3e 100644 --- a/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/AmqpStamp.php +++ b/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/AmqpStamp.php @@ -23,7 +23,7 @@ final class AmqpStamp implements NonSendableStampInterface private $flags; private $attributes; - public function __construct(string $routingKey = null, int $flags = AMQP_NOPARAM, array $attributes = []) + public function __construct(string $routingKey = null, int $flags = \AMQP_NOPARAM, array $attributes = []) { $this->routingKey = $routingKey; $this->flags = $flags; @@ -62,14 +62,14 @@ public static function createFromAmqpEnvelope(\AMQPEnvelope $amqpEnvelope, self $attr['type'] = $attr['type'] ?? $amqpEnvelope->getType(); $attr['reply_to'] = $attr['reply_to'] ?? $amqpEnvelope->getReplyTo(); - return new self($previousStamp->routingKey ?? $amqpEnvelope->getRoutingKey(), $previousStamp->flags ?? AMQP_NOPARAM, $attr); + return new self($previousStamp->routingKey ?? $amqpEnvelope->getRoutingKey(), $previousStamp->flags ?? \AMQP_NOPARAM, $attr); } public static function createWithAttributes(array $attributes, self $previousStamp = null): self { return new self( $previousStamp->routingKey ?? null, - $previousStamp->flags ?? AMQP_NOPARAM, + $previousStamp->flags ?? \AMQP_NOPARAM, array_merge($previousStamp->attributes ?? [], $attributes) ); } diff --git a/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/Connection.php b/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/Connection.php index 97d2f7672f3b..1789e89b7ac8 100644 --- a/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/Connection.php +++ b/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/Connection.php @@ -321,7 +321,7 @@ private function publishOnExchange(\AMQPExchange $exchange, string $body, string $exchange->publish( $body, $routingKey, - $amqpStamp ? $amqpStamp->getFlags() : AMQP_NOPARAM, + $amqpStamp ? $amqpStamp->getFlags() : \AMQP_NOPARAM, $attributes ); } @@ -342,8 +342,8 @@ private function getDelayExchange(): \AMQPExchange if (null === $this->amqpDelayExchange) { $this->amqpDelayExchange = $this->amqpFactory->createExchange($this->channel()); $this->amqpDelayExchange->setName($this->connectionOptions['delay']['exchange_name']); - $this->amqpDelayExchange->setType(AMQP_EX_TYPE_DIRECT); - $this->amqpDelayExchange->setFlags(AMQP_DURABLE); + $this->amqpDelayExchange->setType(\AMQP_EX_TYPE_DIRECT); + $this->amqpDelayExchange->setFlags(\AMQP_DURABLE); } return $this->amqpDelayExchange; @@ -366,7 +366,7 @@ private function createDelayQueue(int $delay, ?string $routingKey): \AMQPQueue [$delay, $this->exchangeOptions['name'], $routingKey ?? ''], $this->connectionOptions['delay']['queue_name_pattern'] )); - $queue->setFlags(AMQP_DURABLE); + $queue->setFlags(\AMQP_DURABLE); $queue->setArguments([ 'x-message-ttl' => $delay, // delete the delay queue 10 seconds after the message expires @@ -426,7 +426,7 @@ public function ack(\AMQPEnvelope $message, string $queueName): bool return $this->queue($queueName)->ack($message->getDeliveryTag()); } - public function nack(\AMQPEnvelope $message, string $queueName, int $flags = AMQP_NOPARAM): bool + public function nack(\AMQPEnvelope $message, string $queueName, int $flags = \AMQP_NOPARAM): bool { return $this->queue($queueName)->nack($message->getDeliveryTag(), $flags); } @@ -470,7 +470,7 @@ public function channel(): \AMQPChannel $credentials['password'] = '********'; unset($credentials['delay']); - throw new \AMQPException(sprintf('Could not connect to the AMQP server. Please verify the provided DSN. (%s).', json_encode($credentials)), 0, $e); + throw new \AMQPException(sprintf('Could not connect to the AMQP server. Please verify the provided DSN. (%s).', json_encode($credentials, \JSON_UNESCAPED_SLASHES)), 0, $e); } $this->amqpChannel = $this->amqpFactory->createChannel($connection); @@ -489,7 +489,7 @@ public function queue(string $queueName): \AMQPQueue $amqpQueue = $this->amqpFactory->createQueue($this->channel()); $amqpQueue->setName($queueName); - $amqpQueue->setFlags($queueConfig['flags'] ?? AMQP_DURABLE); + $amqpQueue->setFlags($queueConfig['flags'] ?? \AMQP_DURABLE); if (isset($queueConfig['arguments'])) { $amqpQueue->setArguments($queueConfig['arguments']); @@ -506,8 +506,8 @@ public function exchange(): \AMQPExchange if (null === $this->amqpExchange) { $this->amqpExchange = $this->amqpFactory->createExchange($this->channel()); $this->amqpExchange->setName($this->exchangeOptions['name']); - $this->amqpExchange->setType($this->exchangeOptions['type'] ?? AMQP_EX_TYPE_FANOUT); - $this->amqpExchange->setFlags($this->exchangeOptions['flags'] ?? AMQP_DURABLE); + $this->amqpExchange->setType($this->exchangeOptions['type'] ?? \AMQP_EX_TYPE_FANOUT); + $this->amqpExchange->setFlags($this->exchangeOptions['flags'] ?? \AMQP_DURABLE); if (isset($this->exchangeOptions['arguments'])) { $this->amqpExchange->setArguments($this->exchangeOptions['arguments']); diff --git a/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/ConnectionTest.php b/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/ConnectionTest.php index d5a63582cbe6..a65b2b886253 100644 --- a/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/ConnectionTest.php +++ b/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/ConnectionTest.php @@ -13,6 +13,7 @@ use Doctrine\DBAL\Abstraction\Result; use Doctrine\DBAL\DBALException; +use Doctrine\DBAL\Exception; use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Query\QueryBuilder; use Doctrine\DBAL\Schema\AbstractSchemaManager; @@ -88,7 +89,12 @@ public function testItThrowsATransportExceptionIfItCannotAcknowledgeMessage() { $this->expectException('Symfony\Component\Messenger\Exception\TransportException'); $driverConnection = $this->getDBALConnectionMock(); - $driverConnection->method('delete')->willThrowException(new DBALException()); + + if (class_exists(Exception::class)) { + $driverConnection->method('delete')->willThrowException(new Exception()); + } else { + $driverConnection->method('delete')->willThrowException(new DBALException()); + } $connection = new Connection([], $driverConnection); $connection->ack('dummy_id'); @@ -98,7 +104,12 @@ public function testItThrowsATransportExceptionIfItCannotRejectMessage() { $this->expectException('Symfony\Component\Messenger\Exception\TransportException'); $driverConnection = $this->getDBALConnectionMock(); - $driverConnection->method('delete')->willThrowException(new DBALException()); + + if (class_exists(Exception::class)) { + $driverConnection->method('delete')->willThrowException(new Exception()); + } else { + $driverConnection->method('delete')->willThrowException(new DBALException()); + } $connection = new Connection([], $driverConnection); $connection->reject('dummy_id'); diff --git a/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/Connection.php b/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/Connection.php index 37f06cfa18c0..83c681dd9546 100644 --- a/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/Connection.php +++ b/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/Connection.php @@ -14,6 +14,7 @@ use Doctrine\DBAL\Connection as DBALConnection; use Doctrine\DBAL\DBALException; use Doctrine\DBAL\Driver\Result; +use Doctrine\DBAL\Exception; use Doctrine\DBAL\Exception\TableNotFoundException; use Doctrine\DBAL\Query\QueryBuilder; use Doctrine\DBAL\Schema\Comparator; @@ -98,7 +99,7 @@ public static function buildConfiguration(string $dsn, array $options = []): arr $configuration = ['connection' => $components['host']]; $configuration += $query + $options + static::DEFAULT_OPTIONS; - $configuration['auto_setup'] = filter_var($configuration['auto_setup'], FILTER_VALIDATE_BOOLEAN); + $configuration['auto_setup'] = filter_var($configuration['auto_setup'], \FILTER_VALIDATE_BOOLEAN); // check for extra keys in options $optionsExtraKeys = array_diff(array_keys($options), array_keys(static::DEFAULT_OPTIONS)); @@ -121,6 +122,7 @@ public static function buildConfiguration(string $dsn, array $options = []): arr * @return string The inserted id * * @throws \Doctrine\DBAL\DBALException + * @throws \Doctrine\DBAL\Exception */ public function send(string $body, array $headers, int $delay = 0): string { @@ -220,7 +222,7 @@ public function ack(string $id): bool { try { return $this->driverConnection->delete($this->configuration['table_name'], ['id' => $id]) > 0; - } catch (DBALException $exception) { + } catch (DBALException | Exception $exception) { throw new TransportException($exception->getMessage(), 0, $exception); } } @@ -229,7 +231,7 @@ public function reject(string $id): bool { try { return $this->driverConnection->delete($this->configuration['table_name'], ['id' => $id]) > 0; - } catch (DBALException $exception) { + } catch (DBALException | Exception $exception) { throw new TransportException($exception->getMessage(), 0, $exception); } } diff --git a/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/DoctrineReceiver.php b/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/DoctrineReceiver.php index 872e0c927806..ca00b52a5bc6 100644 --- a/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/DoctrineReceiver.php +++ b/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/DoctrineReceiver.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Messenger\Bridge\Doctrine\Transport; use Doctrine\DBAL\DBALException; +use Doctrine\DBAL\Exception; use Doctrine\DBAL\Exception\RetryableException; use Symfony\Component\Messenger\Envelope; use Symfony\Component\Messenger\Exception\LogicException; @@ -58,7 +59,7 @@ public function get(): iterable } return []; - } catch (DBALException $exception) { + } catch (DBALException | Exception $exception) { throw new TransportException($exception->getMessage(), 0, $exception); } @@ -76,7 +77,7 @@ public function ack(Envelope $envelope): void { try { $this->connection->ack($this->findDoctrineReceivedStamp($envelope)->getId()); - } catch (DBALException $exception) { + } catch (DBALException | Exception $exception) { throw new TransportException($exception->getMessage(), 0, $exception); } } @@ -88,7 +89,7 @@ public function reject(Envelope $envelope): void { try { $this->connection->reject($this->findDoctrineReceivedStamp($envelope)->getId()); - } catch (DBALException $exception) { + } catch (DBALException | Exception $exception) { throw new TransportException($exception->getMessage(), 0, $exception); } } @@ -100,7 +101,7 @@ public function getMessageCount(): int { try { return $this->connection->getMessageCount(); - } catch (DBALException $exception) { + } catch (DBALException | Exception $exception) { throw new TransportException($exception->getMessage(), 0, $exception); } } @@ -112,7 +113,7 @@ public function all(int $limit = null): iterable { try { $doctrineEnvelopes = $this->connection->findAll($limit); - } catch (DBALException $exception) { + } catch (DBALException | Exception $exception) { throw new TransportException($exception->getMessage(), 0, $exception); } @@ -128,7 +129,7 @@ public function find($id): ?Envelope { try { $doctrineEnvelope = $this->connection->find($id); - } catch (DBALException $exception) { + } catch (DBALException | Exception $exception) { throw new TransportException($exception->getMessage(), 0, $exception); } diff --git a/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/DoctrineSender.php b/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/DoctrineSender.php index db46afd2b30d..f5612f30f040 100644 --- a/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/DoctrineSender.php +++ b/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/DoctrineSender.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Messenger\Bridge\Doctrine\Transport; use Doctrine\DBAL\DBALException; +use Doctrine\DBAL\Exception; use Symfony\Component\Messenger\Envelope; use Symfony\Component\Messenger\Exception\TransportException; use Symfony\Component\Messenger\Stamp\DelayStamp; @@ -47,7 +48,7 @@ public function send(Envelope $envelope): Envelope try { $id = $this->connection->send($encodedMessage['body'], $encodedMessage['headers'] ?? [], $delay); - } catch (DBALException $exception) { + } catch (DBALException | Exception $exception) { throw new TransportException($exception->getMessage(), 0, $exception); } diff --git a/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/PostgreSqlConnection.php b/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/PostgreSqlConnection.php index 225f0b880111..79a1dd68ba41 100644 --- a/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/PostgreSqlConnection.php +++ b/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/PostgreSqlConnection.php @@ -109,6 +109,7 @@ public function getExtraSetupSqlForTable(Table $createdTable): array private function getTriggerSql(): array { return [ + 'BEGIN;', sprintf('LOCK TABLE %s;', $this->configuration['table_name']), // create trigger function sprintf(<<<'SQL' @@ -123,6 +124,7 @@ private function getTriggerSql(): array // register trigger sprintf('DROP TRIGGER IF EXISTS notify_trigger ON %s;', $this->configuration['table_name']), sprintf('CREATE TRIGGER notify_trigger AFTER INSERT ON %1$s FOR EACH ROW EXECUTE PROCEDURE notify_%1$s();', $this->configuration['table_name']), + 'COMMIT;', ]; } diff --git a/src/Symfony/Component/Messenger/Bridge/Redis/Transport/Connection.php b/src/Symfony/Component/Messenger/Bridge/Redis/Transport/Connection.php index d47fae96082c..b0a4279ea17b 100644 --- a/src/Symfony/Component/Messenger/Bridge/Redis/Transport/Connection.php +++ b/src/Symfony/Component/Messenger/Bridge/Redis/Transport/Connection.php @@ -112,43 +112,43 @@ public static function fromDsn(string $dsn, array $redisOptions = [], \Redis $re $autoSetup = null; if (\array_key_exists('auto_setup', $redisOptions)) { - $autoSetup = filter_var($redisOptions['auto_setup'], FILTER_VALIDATE_BOOLEAN); + $autoSetup = filter_var($redisOptions['auto_setup'], \FILTER_VALIDATE_BOOLEAN); unset($redisOptions['auto_setup']); } $maxEntries = null; if (\array_key_exists('stream_max_entries', $redisOptions)) { - $maxEntries = filter_var($redisOptions['stream_max_entries'], FILTER_VALIDATE_INT); + $maxEntries = filter_var($redisOptions['stream_max_entries'], \FILTER_VALIDATE_INT); unset($redisOptions['stream_max_entries']); } $deleteAfterAck = null; if (\array_key_exists('delete_after_ack', $redisOptions)) { - $deleteAfterAck = filter_var($redisOptions['delete_after_ack'], FILTER_VALIDATE_BOOLEAN); + $deleteAfterAck = filter_var($redisOptions['delete_after_ack'], \FILTER_VALIDATE_BOOLEAN); unset($redisOptions['delete_after_ack']); } $dbIndex = null; if (\array_key_exists('dbindex', $redisOptions)) { - $dbIndex = filter_var($redisOptions['dbindex'], FILTER_VALIDATE_INT); + $dbIndex = filter_var($redisOptions['dbindex'], \FILTER_VALIDATE_INT); unset($redisOptions['dbindex']); } $tls = false; if (\array_key_exists('tls', $redisOptions)) { - $tls = filter_var($redisOptions['tls'], FILTER_VALIDATE_BOOLEAN); + $tls = filter_var($redisOptions['tls'], \FILTER_VALIDATE_BOOLEAN); unset($redisOptions['tls']); } $redeliverTimeout = null; if (\array_key_exists('redeliver_timeout', $redisOptions)) { - $redeliverTimeout = filter_var($redisOptions['redeliver_timeout'], FILTER_VALIDATE_INT); + $redeliverTimeout = filter_var($redisOptions['redeliver_timeout'], \FILTER_VALIDATE_INT); unset($redisOptions['redeliver_timeout']); } $claimInterval = null; if (\array_key_exists('claim_interval', $redisOptions)) { - $claimInterval = filter_var($redisOptions['claim_interval'], FILTER_VALIDATE_INT); + $claimInterval = filter_var($redisOptions['claim_interval'], \FILTER_VALIDATE_INT); unset($redisOptions['claim_interval']); } diff --git a/src/Symfony/Component/Messenger/EventListener/StopWorkerOnSigtermSignalListener.php b/src/Symfony/Component/Messenger/EventListener/StopWorkerOnSigtermSignalListener.php index 9054b1917671..70b05b18b0ac 100644 --- a/src/Symfony/Component/Messenger/EventListener/StopWorkerOnSigtermSignalListener.php +++ b/src/Symfony/Component/Messenger/EventListener/StopWorkerOnSigtermSignalListener.php @@ -21,7 +21,7 @@ class StopWorkerOnSigtermSignalListener implements EventSubscriberInterface { public function onWorkerStarted(WorkerStartedEvent $event): void { - pcntl_signal(SIGTERM, static function () use ($event) { + pcntl_signal(\SIGTERM, static function () use ($event) { $event->getWorker()->stop(); }); } diff --git a/src/Symfony/Component/Messenger/Retry/MultiplierRetryStrategy.php b/src/Symfony/Component/Messenger/Retry/MultiplierRetryStrategy.php index cf72f8614f6c..8f5c1cdc3f3d 100644 --- a/src/Symfony/Component/Messenger/Retry/MultiplierRetryStrategy.php +++ b/src/Symfony/Component/Messenger/Retry/MultiplierRetryStrategy.php @@ -80,7 +80,7 @@ public function getWaitingTime(Envelope $message, \Throwable $throwable = null): { $retries = RedeliveryStamp::getRetryCountFromEnvelope($message); - $delay = $this->delayMilliseconds * pow($this->multiplier, $retries); + $delay = $this->delayMilliseconds * $this->multiplier ** $retries; if ($delay > $this->maxDelayMilliseconds && 0 !== $this->maxDelayMilliseconds) { return $this->maxDelayMilliseconds; diff --git a/src/Symfony/Component/Messenger/Tests/Command/DebugCommandTest.php b/src/Symfony/Component/Messenger/Tests/Command/DebugCommandTest.php index 54c52d66227f..92d6b855d513 100644 --- a/src/Symfony/Component/Messenger/Tests/Command/DebugCommandTest.php +++ b/src/Symfony/Component/Messenger/Tests/Command/DebugCommandTest.php @@ -30,7 +30,7 @@ class DebugCommandTest extends TestCase { protected function setUp(): void { - putenv('COLUMNS='.(119 + \strlen(PHP_EOL))); + putenv('COLUMNS='.(119 + \strlen(\PHP_EOL))); } protected function tearDown(): void diff --git a/src/Symfony/Component/Messenger/TraceableMessageBus.php b/src/Symfony/Component/Messenger/TraceableMessageBus.php index ed4807199aa2..39edaa8c5b03 100644 --- a/src/Symfony/Component/Messenger/TraceableMessageBus.php +++ b/src/Symfony/Component/Messenger/TraceableMessageBus.php @@ -60,7 +60,7 @@ public function reset() private function getCaller(): array { - $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 8); + $trace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 8); $file = $trace[1]['file']; $line = $trace[1]['line']; diff --git a/src/Symfony/Component/Mime/Crypto/SMimeEncrypter.php b/src/Symfony/Component/Mime/Crypto/SMimeEncrypter.php index d6961a6e81bf..9081860d80fb 100644 --- a/src/Symfony/Component/Mime/Crypto/SMimeEncrypter.php +++ b/src/Symfony/Component/Mime/Crypto/SMimeEncrypter.php @@ -38,7 +38,7 @@ public function __construct($certificate, int $cipher = null) $this->certs = $this->normalizeFilePath($certificate); } - $this->cipher = $cipher ?? OPENSSL_CIPHER_AES_256_CBC; + $this->cipher = $cipher ?? \OPENSSL_CIPHER_AES_256_CBC; } public function encrypt(Message $message): Message diff --git a/src/Symfony/Component/Mime/Crypto/SMimeSigner.php b/src/Symfony/Component/Mime/Crypto/SMimeSigner.php index 1b555375ce90..5b94a454e83a 100644 --- a/src/Symfony/Component/Mime/Crypto/SMimeSigner.php +++ b/src/Symfony/Component/Mime/Crypto/SMimeSigner.php @@ -45,7 +45,7 @@ public function __construct(string $certificate, string $privateKey, string $pri $this->signPrivateKey = $this->normalizeFilePath($privateKey); } - $this->signOptions = $signOptions ?? PKCS7_DETACHED; + $this->signOptions = $signOptions ?? \PKCS7_DETACHED; $this->extraCerts = $extraCerts ? realpath($extraCerts) : null; } diff --git a/src/Symfony/Component/Mime/Encoder/Base64ContentEncoder.php b/src/Symfony/Component/Mime/Encoder/Base64ContentEncoder.php index 881eaab77b5e..440868af70c5 100644 --- a/src/Symfony/Component/Mime/Encoder/Base64ContentEncoder.php +++ b/src/Symfony/Component/Mime/Encoder/Base64ContentEncoder.php @@ -24,7 +24,7 @@ public function encodeByteStream($stream, int $maxLineLength = 0): iterable throw new \TypeError(sprintf('Method "%s" takes a stream as a first argument.', __METHOD__)); } - $filter = stream_filter_append($stream, 'convert.base64-encode', STREAM_FILTER_READ, [ + $filter = stream_filter_append($stream, 'convert.base64-encode', \STREAM_FILTER_READ, [ 'line-length' => 0 >= $maxLineLength || 76 < $maxLineLength ? 76 : $maxLineLength, 'line-break-chars' => "\r\n", ]); diff --git a/src/Symfony/Component/Mime/Encoder/IdnAddressEncoder.php b/src/Symfony/Component/Mime/Encoder/IdnAddressEncoder.php index cdd5d4cade81..69ab8872ec11 100644 --- a/src/Symfony/Component/Mime/Encoder/IdnAddressEncoder.php +++ b/src/Symfony/Component/Mime/Encoder/IdnAddressEncoder.php @@ -43,7 +43,7 @@ public function encodeString(string $address): string } if (preg_match('/[^\x00-\x7F]/', $domain)) { - $address = sprintf('%s@%s', $local, idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46)); + $address = sprintf('%s@%s', $local, idn_to_ascii($domain, 0, \INTL_IDNA_VARIANT_UTS46)); } } diff --git a/src/Symfony/Component/Mime/FileinfoMimeTypeGuesser.php b/src/Symfony/Component/Mime/FileinfoMimeTypeGuesser.php index 3028159858d1..c6c7559af100 100644 --- a/src/Symfony/Component/Mime/FileinfoMimeTypeGuesser.php +++ b/src/Symfony/Component/Mime/FileinfoMimeTypeGuesser.php @@ -54,7 +54,7 @@ public function guessMimeType(string $path): ?string throw new LogicException(sprintf('The "%s" guesser is not supported.', __CLASS__)); } - if (false === $finfo = new \finfo(FILEINFO_MIME_TYPE, $this->magicFile)) { + if (false === $finfo = new \finfo(\FILEINFO_MIME_TYPE, $this->magicFile)) { return null; } $mimeType = $finfo->file($path); diff --git a/src/Symfony/Component/Mime/Header/AbstractHeader.php b/src/Symfony/Component/Mime/Header/AbstractHeader.php index 548c192692dd..e93b87aeb72d 100644 --- a/src/Symfony/Component/Mime/Header/AbstractHeader.php +++ b/src/Symfony/Component/Mime/Header/AbstractHeader.php @@ -220,7 +220,7 @@ protected function getTokenAsEncodedWord(string $token, int $firstLineOffset = 0 */ protected function generateTokenLines(string $token): array { - return preg_split('~(\r\n)~', $token, -1, PREG_SPLIT_DELIM_CAPTURE); + return preg_split('~(\r\n)~', $token, -1, \PREG_SPLIT_DELIM_CAPTURE); } /** diff --git a/src/Symfony/Component/Mime/Part/Multipart/FormDataPart.php b/src/Symfony/Component/Mime/Part/Multipart/FormDataPart.php index 76c48e46f73f..9e3c9a2a852a 100644 --- a/src/Symfony/Component/Mime/Part/Multipart/FormDataPart.php +++ b/src/Symfony/Component/Mime/Part/Multipart/FormDataPart.php @@ -40,7 +40,7 @@ public function __construct(array $fields = []) $this->fields[$name] = $value; } // HTTP does not support \r\n in header values - $this->getHeaders()->setMaxLineLength(PHP_INT_MAX); + $this->getHeaders()->setMaxLineLength(\PHP_INT_MAX); } public function getMediaSubtype(): string @@ -95,7 +95,7 @@ private function configurePart(string $name, TextPart $part): TextPart $part->setDisposition('form-data'); $part->setName($name); // HTTP does not support \r\n in header values - $part->getHeaders()->setMaxLineLength(PHP_INT_MAX); + $part->getHeaders()->setMaxLineLength(\PHP_INT_MAX); $r->setValue($part, '8bit'); return $part; diff --git a/src/Symfony/Component/Mime/Part/TextPart.php b/src/Symfony/Component/Mime/Part/TextPart.php index 72c7d4f69596..2a12fab6113a 100644 --- a/src/Symfony/Component/Mime/Part/TextPart.php +++ b/src/Symfony/Component/Mime/Part/TextPart.php @@ -47,7 +47,7 @@ public function __construct($body, ?string $charset = 'utf-8', $subtype = 'plain $this->body = $body; $this->charset = $charset; $this->subtype = $subtype; - $this->seekable = \is_resource($body) ? stream_get_meta_data($body)['seekable'] && 0 === fseek($body, 0, SEEK_CUR) : null; + $this->seekable = \is_resource($body) ? stream_get_meta_data($body)['seekable'] && 0 === fseek($body, 0, \SEEK_CUR) : null; if (null === $encoding) { $this->encoding = $this->chooseEncoding(); diff --git a/src/Symfony/Component/Mime/Tests/Crypto/SMimeSignerTest.php b/src/Symfony/Component/Mime/Tests/Crypto/SMimeSignerTest.php index 5522bc6f55cd..ed13d046836c 100644 --- a/src/Symfony/Component/Mime/Tests/Crypto/SMimeSignerTest.php +++ b/src/Symfony/Component/Mime/Tests/Crypto/SMimeSignerTest.php @@ -143,7 +143,7 @@ public function testSignedMessageExtraCerts() $this->samplesDir.'sign.key', null, $this->samplesDir.'intermediate.crt', - PKCS7_DETACHED + \PKCS7_DETACHED ); $signedMessage = $signer->sign($message); diff --git a/src/Symfony/Component/Mime/Tests/Part/Multipart/FormDataPartTest.php b/src/Symfony/Component/Mime/Tests/Part/Multipart/FormDataPartTest.php index 6f81224c6644..417417f054d4 100644 --- a/src/Symfony/Component/Mime/Tests/Part/Multipart/FormDataPartTest.php +++ b/src/Symfony/Component/Mime/Tests/Part/Multipart/FormDataPartTest.php @@ -35,14 +35,14 @@ public function testConstructor() $t = new TextPart($content, 'utf-8', 'plain', '8bit'); $t->setDisposition('form-data'); $t->setName('foo'); - $t->getHeaders()->setMaxLineLength(PHP_INT_MAX); + $t->getHeaders()->setMaxLineLength(\PHP_INT_MAX); $b->setDisposition('form-data'); $b->setName('bar'); - $b->getHeaders()->setMaxLineLength(PHP_INT_MAX); + $b->getHeaders()->setMaxLineLength(\PHP_INT_MAX); $r->setValue($b, '8bit'); $c->setDisposition('form-data'); $c->setName('baz'); - $c->getHeaders()->setMaxLineLength(PHP_INT_MAX); + $c->getHeaders()->setMaxLineLength(\PHP_INT_MAX); $r->setValue($c, '8bit'); $this->assertEquals([$t, $b, $c], $f->getParts()); } diff --git a/src/Symfony/Component/Notifier/Bridge/Firebase/FirebaseTransport.php b/src/Symfony/Component/Notifier/Bridge/Firebase/FirebaseTransport.php index 5a3509c63eee..e25ed2f597b5 100644 --- a/src/Symfony/Component/Notifier/Bridge/Firebase/FirebaseTransport.php +++ b/src/Symfony/Component/Notifier/Bridge/Firebase/FirebaseTransport.php @@ -73,7 +73,7 @@ protected function doSend(MessageInterface $message): void 'json' => array_filter($options), ]); - $contentType = $response->getHeaders(false)['Content-Type'] ?? ''; + $contentType = $response->getHeaders(false)['content-type'][0] ?? ''; $jsonContents = 0 === strpos($contentType, 'application/json') ? $response->toArray(false) : null; if (200 !== $response->getStatusCode()) { diff --git a/src/Symfony/Component/Notifier/Bridge/OvhCloud/OvhCloudTransport.php b/src/Symfony/Component/Notifier/Bridge/OvhCloud/OvhCloudTransport.php index 74ef58b2c8e5..4d737019c332 100644 --- a/src/Symfony/Component/Notifier/Bridge/OvhCloud/OvhCloudTransport.php +++ b/src/Symfony/Component/Notifier/Bridge/OvhCloud/OvhCloudTransport.php @@ -76,7 +76,7 @@ protected function doSend(MessageInterface $message): void $headers['X-Ovh-Application'] = $this->applicationKey; $headers['X-Ovh-Timestamp'] = $now; - $toSign = $this->applicationSecret.'+'.$this->consumerKey.'+POST+'.$endpoint.'+'.json_encode($content, JSON_UNESCAPED_SLASHES).'+'.$now; + $toSign = $this->applicationSecret.'+'.$this->consumerKey.'+POST+'.$endpoint.'+'.json_encode($content, \JSON_UNESCAPED_SLASHES).'+'.$now; $headers['X-Ovh-Consumer'] = $this->consumerKey; $headers['X-Ovh-Signature'] = '$1$'.sha1($toSign); diff --git a/src/Symfony/Component/OptionsResolver/OptionsResolver.php b/src/Symfony/Component/OptionsResolver/OptionsResolver.php index a7883d2f4e83..bc2e3e1654f4 100644 --- a/src/Symfony/Component/OptionsResolver/OptionsResolver.php +++ b/src/Symfony/Component/OptionsResolver/OptionsResolver.php @@ -1067,7 +1067,7 @@ public function offsetGet($option, bool $triggerDeprecation = true) // Check whether the option is deprecated // and it is provided by the user or is being called from a lazy evaluation - if ($triggerDeprecation && isset($this->deprecated[$option]) && (isset($this->given[$option]) || ($this->calling && \is_string($this->deprecated[$option])))) { + if ($triggerDeprecation && isset($this->deprecated[$option]) && (isset($this->given[$option]) || ($this->calling && \is_string($this->deprecated[$option]['message'])))) { $deprecation = $this->deprecated[$option]; $message = $this->deprecated[$option]['message']; diff --git a/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php b/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php index 4083e5ee6a32..8e550b02a753 100644 --- a/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php +++ b/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php @@ -524,7 +524,9 @@ public function testDeprecationMessages(\Closure $configureOptions, array $optio { $count = 0; error_clear_last(); - set_error_handler(function () use (&$count) { + set_error_handler(function (int $type) use (&$count) { + $this->assertSame(\E_USER_DEPRECATED, $type); + ++$count; return false; @@ -555,7 +557,7 @@ function (OptionsResolver $resolver) { }, ['foo' => 'baz'], [ - 'type' => E_USER_DEPRECATED, + 'type' => \E_USER_DEPRECATED, 'message' => 'Since vendor/package 1.1: The option "foo" is deprecated.', ], 1, @@ -573,7 +575,7 @@ function (OptionsResolver $resolver) { }, ['foo' => 'baz'], [ - 'type' => E_USER_DEPRECATED, + 'type' => \E_USER_DEPRECATED, 'message' => 'Since vendor/package 1.1: The option "foo" is deprecated, use "bar" option instead.', ], 2, @@ -593,7 +595,7 @@ function (OptionsResolver $resolver) { }, [], [ - 'type' => E_USER_DEPRECATED, + 'type' => \E_USER_DEPRECATED, 'message' => 'Since vendor/package 1.1: The option "foo" is deprecated.', ], 1, @@ -615,7 +617,7 @@ function (OptionsResolver $resolver) { }, ['foo' => new \stdClass()], [ - 'type' => E_USER_DEPRECATED, + 'type' => \E_USER_DEPRECATED, 'message' => 'Since vendor/package 1.1: Passing an instance of "stdClass" to option "foo" is deprecated, pass its FQCN instead.', ], 1, @@ -651,7 +653,7 @@ function (OptionsResolver $resolver) { }, ['foo' => null], // It triggers a deprecation [ - 'type' => E_USER_DEPRECATED, + 'type' => \E_USER_DEPRECATED, 'message' => 'Since vendor/package 1.1: Passing a value different than true or false is deprecated.', ], 1, @@ -687,7 +689,7 @@ function (OptionsResolver $resolver) { }, ['widget' => 'single_text', 'date_format' => 2], [ - 'type' => E_USER_DEPRECATED, + 'type' => \E_USER_DEPRECATED, 'message' => 'Since vendor/package 1.1: Using the "date_format" option when the "widget" option is set to "single_text" is deprecated.', ], 1, @@ -713,7 +715,7 @@ function (OptionsResolver $resolver) { }, ['foo' => 'baz'], // It triggers a deprecation [ - 'type' => E_USER_DEPRECATED, + 'type' => \E_USER_DEPRECATED, 'message' => 'Since vendor/package 1.1: The option "foo" is deprecated.', ], 4, diff --git a/src/Symfony/Component/Process/ExecutableFinder.php b/src/Symfony/Component/Process/ExecutableFinder.php index aa52cf367d84..feee4ad49b73 100644 --- a/src/Symfony/Component/Process/ExecutableFinder.php +++ b/src/Symfony/Component/Process/ExecutableFinder.php @@ -49,7 +49,7 @@ public function addSuffix(string $suffix) public function find(string $name, string $default = null, array $extraDirs = []) { if (ini_get('open_basedir')) { - $searchPath = array_merge(explode(PATH_SEPARATOR, ini_get('open_basedir')), $extraDirs); + $searchPath = array_merge(explode(\PATH_SEPARATOR, ini_get('open_basedir')), $extraDirs); $dirs = []; foreach ($searchPath as $path) { // Silencing against https://bugs.php.net/69240 @@ -63,7 +63,7 @@ public function find(string $name, string $default = null, array $extraDirs = [] } } else { $dirs = array_merge( - explode(PATH_SEPARATOR, getenv('PATH') ?: getenv('Path')), + explode(\PATH_SEPARATOR, getenv('PATH') ?: getenv('Path')), $extraDirs ); } @@ -71,7 +71,7 @@ public function find(string $name, string $default = null, array $extraDirs = [] $suffixes = ['']; if ('\\' === \DIRECTORY_SEPARATOR) { $pathExt = getenv('PATHEXT'); - $suffixes = array_merge($pathExt ? explode(PATH_SEPARATOR, $pathExt) : $this->suffixes, $suffixes); + $suffixes = array_merge($pathExt ? explode(\PATH_SEPARATOR, $pathExt) : $this->suffixes, $suffixes); } foreach ($suffixes as $suffix) { foreach ($dirs as $dir) { diff --git a/src/Symfony/Component/Process/PhpExecutableFinder.php b/src/Symfony/Component/Process/PhpExecutableFinder.php index c09d49a2c236..e4f03f76f1c9 100644 --- a/src/Symfony/Component/Process/PhpExecutableFinder.php +++ b/src/Symfony/Component/Process/PhpExecutableFinder.php @@ -36,7 +36,7 @@ public function find(bool $includeArgs = true) if ($php = getenv('PHP_BINARY')) { if (!is_executable($php)) { $command = '\\' === \DIRECTORY_SEPARATOR ? 'where' : 'command -v'; - if ($php = strtok(exec($command.' '.escapeshellarg($php)), PHP_EOL)) { + if ($php = strtok(exec($command.' '.escapeshellarg($php)), \PHP_EOL)) { if (!is_executable($php)) { return false; } @@ -52,8 +52,8 @@ public function find(bool $includeArgs = true) $args = $includeArgs && $args ? ' '.implode(' ', $args) : ''; // PHP_BINARY return the current sapi executable - if (PHP_BINARY && \in_array(\PHP_SAPI, ['cgi-fcgi', 'cli', 'cli-server', 'phpdbg'], true)) { - return PHP_BINARY.$args; + if (\PHP_BINARY && \in_array(\PHP_SAPI, ['cgi-fcgi', 'cli', 'cli-server', 'phpdbg'], true)) { + return \PHP_BINARY.$args; } if ($php = getenv('PHP_PATH')) { @@ -70,11 +70,11 @@ public function find(bool $includeArgs = true) } } - if (@is_executable($php = PHP_BINDIR.('\\' === \DIRECTORY_SEPARATOR ? '\\php.exe' : '/php'))) { + if (@is_executable($php = \PHP_BINDIR.('\\' === \DIRECTORY_SEPARATOR ? '\\php.exe' : '/php'))) { return $php; } - $dirs = [PHP_BINDIR]; + $dirs = [\PHP_BINDIR]; if ('\\' === \DIRECTORY_SEPARATOR) { $dirs[] = 'C:\xampp\php\\'; } diff --git a/src/Symfony/Component/Process/Pipes/WindowsPipes.php b/src/Symfony/Component/Process/Pipes/WindowsPipes.php index 5ebd5ff3c552..b22171dd4ad3 100644 --- a/src/Symfony/Component/Process/Pipes/WindowsPipes.php +++ b/src/Symfony/Component/Process/Pipes/WindowsPipes.php @@ -62,17 +62,17 @@ public function __construct($input, bool $haveReadSupport) restore_error_handler(); throw new RuntimeException('A temporary file could not be opened to write the process output: '.$lastError); } - if (!flock($h, LOCK_EX | LOCK_NB)) { + if (!flock($h, \LOCK_EX | \LOCK_NB)) { continue 2; } if (isset($this->lockHandles[$pipe])) { - flock($this->lockHandles[$pipe], LOCK_UN); + flock($this->lockHandles[$pipe], \LOCK_UN); fclose($this->lockHandles[$pipe]); } $this->lockHandles[$pipe] = $h; if (!fclose(fopen($file, 'w')) || !$h = fopen($file, 'r')) { - flock($this->lockHandles[$pipe], LOCK_UN); + flock($this->lockHandles[$pipe], \LOCK_UN); fclose($this->lockHandles[$pipe]); unset($this->lockHandles[$pipe]); continue 2; @@ -152,7 +152,7 @@ public function readAndWrite(bool $blocking, bool $close = false): array if ($close) { ftruncate($fileHandle, 0); fclose($fileHandle); - flock($this->lockHandles[$type], LOCK_UN); + flock($this->lockHandles[$type], \LOCK_UN); fclose($this->lockHandles[$type]); unset($this->fileHandles[$type], $this->lockHandles[$type]); } @@ -186,7 +186,7 @@ public function close() foreach ($this->fileHandles as $type => $handle) { ftruncate($handle, 0); fclose($handle); - flock($this->lockHandles[$type], LOCK_UN); + flock($this->lockHandles[$type], \LOCK_UN); fclose($this->lockHandles[$type]); } $this->fileHandles = $this->lockHandles = []; diff --git a/src/Symfony/Component/Process/Process.php b/src/Symfony/Component/Process/Process.php index e1efb9ccc80e..e984e04eef65 100644 --- a/src/Symfony/Component/Process/Process.php +++ b/src/Symfony/Component/Process/Process.php @@ -934,7 +934,7 @@ public function addOutput(string $line) { $this->lastOutputTime = microtime(true); - fseek($this->stdout, 0, SEEK_END); + fseek($this->stdout, 0, \SEEK_END); fwrite($this->stdout, $line); fseek($this->stdout, $this->incrementalOutputOffset); } @@ -948,7 +948,7 @@ public function addErrorOutput(string $line) { $this->lastOutputTime = microtime(true); - fseek($this->stderr, 0, SEEK_END); + fseek($this->stderr, 0, \SEEK_END); fwrite($this->stderr, $line); fseek($this->stderr, $this->incrementalErrorOutputOffset); } @@ -1343,7 +1343,7 @@ protected function isSigchildEnabled() } ob_start(); - phpinfo(INFO_GENERAL); + phpinfo(\INFO_GENERAL); return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild'); } diff --git a/src/Symfony/Component/Process/Tests/ErrorProcessInitiator.php b/src/Symfony/Component/Process/Tests/ErrorProcessInitiator.php index c37aeb5c8ffd..37c1e65846fd 100755 --- a/src/Symfony/Component/Process/Tests/ErrorProcessInitiator.php +++ b/src/Symfony/Component/Process/Tests/ErrorProcessInitiator.php @@ -25,12 +25,12 @@ while (false === strpos($process->getOutput(), 'ready')) { usleep(1000); } - $process->signal(SIGSTOP); + $process->signal(\SIGSTOP); $process->wait(); return $process->getExitCode(); } catch (ProcessTimedOutException $t) { - echo $t->getMessage().PHP_EOL; + echo $t->getMessage().\PHP_EOL; return 1; } diff --git a/src/Symfony/Component/Process/Tests/ExecutableFinderTest.php b/src/Symfony/Component/Process/Tests/ExecutableFinderTest.php index 2a0278f8e045..83f263ff3507 100644 --- a/src/Symfony/Component/Process/Tests/ExecutableFinderTest.php +++ b/src/Symfony/Component/Process/Tests/ExecutableFinderTest.php @@ -41,12 +41,12 @@ public function testFind() $this->markTestSkipped('Cannot test when open_basedir is set'); } - $this->setPath(\dirname(PHP_BINARY)); + $this->setPath(\dirname(\PHP_BINARY)); $finder = new ExecutableFinder(); $result = $finder->find($this->getPhpBinaryName()); - $this->assertSamePath(PHP_BINARY, $result); + $this->assertSamePath(\PHP_BINARY, $result); } public function testFindWithDefault() @@ -88,12 +88,12 @@ public function testFindWithExtraDirs() $this->setPath(''); - $extraDirs = [\dirname(PHP_BINARY)]; + $extraDirs = [\dirname(\PHP_BINARY)]; $finder = new ExecutableFinder(); $result = $finder->find($this->getPhpBinaryName(), null, $extraDirs); - $this->assertSamePath(PHP_BINARY, $result); + $this->assertSamePath(\PHP_BINARY, $result); } public function testFindWithOpenBaseDir() @@ -106,12 +106,12 @@ public function testFindWithOpenBaseDir() $this->markTestSkipped('Cannot test when open_basedir is set'); } - $this->iniSet('open_basedir', \dirname(PHP_BINARY).PATH_SEPARATOR.'/'); + $this->iniSet('open_basedir', \dirname(\PHP_BINARY).\PATH_SEPARATOR.'/'); $finder = new ExecutableFinder(); $result = $finder->find($this->getPhpBinaryName()); - $this->assertSamePath(PHP_BINARY, $result); + $this->assertSamePath(\PHP_BINARY, $result); } public function testFindProcessInOpenBasedir() @@ -124,12 +124,12 @@ public function testFindProcessInOpenBasedir() } $this->setPath(''); - $this->iniSet('open_basedir', PHP_BINARY.PATH_SEPARATOR.'/'); + $this->iniSet('open_basedir', \PHP_BINARY.\PATH_SEPARATOR.'/'); $finder = new ExecutableFinder(); $result = $finder->find($this->getPhpBinaryName(), false); - $this->assertSamePath(PHP_BINARY, $result); + $this->assertSamePath(\PHP_BINARY, $result); } public function testFindBatchExecutableOnWindows() @@ -170,6 +170,6 @@ private function assertSamePath($expected, $tested) private function getPhpBinaryName() { - return basename(PHP_BINARY, '\\' === \DIRECTORY_SEPARATOR ? '.exe' : ''); + return basename(\PHP_BINARY, '\\' === \DIRECTORY_SEPARATOR ? '.exe' : ''); } } diff --git a/src/Symfony/Component/Process/Tests/NonStopableProcess.php b/src/Symfony/Component/Process/Tests/NonStopableProcess.php index 5643259657d5..c695f544d29b 100644 --- a/src/Symfony/Component/Process/Tests/NonStopableProcess.php +++ b/src/Symfony/Component/Process/Tests/NonStopableProcess.php @@ -19,10 +19,10 @@ function handleSignal($signal) { switch ($signal) { - case SIGTERM: + case \SIGTERM: $name = 'SIGTERM'; break; - case SIGINT: + case \SIGINT: $name = 'SIGINT'; break; default: @@ -33,8 +33,8 @@ function handleSignal($signal) echo "signal $name\n"; } -pcntl_signal(SIGTERM, 'handleSignal'); -pcntl_signal(SIGINT, 'handleSignal'); +pcntl_signal(\SIGTERM, 'handleSignal'); +pcntl_signal(\SIGINT, 'handleSignal'); echo 'received '; diff --git a/src/Symfony/Component/Process/Tests/PhpExecutableFinderTest.php b/src/Symfony/Component/Process/Tests/PhpExecutableFinderTest.php index b87782526a1c..cf3ffb55efb7 100644 --- a/src/Symfony/Component/Process/Tests/PhpExecutableFinderTest.php +++ b/src/Symfony/Component/Process/Tests/PhpExecutableFinderTest.php @@ -26,7 +26,7 @@ public function testFind() { $f = new PhpExecutableFinder(); - $current = PHP_BINARY; + $current = \PHP_BINARY; $args = 'phpdbg' === \PHP_SAPI ? ' -qrr' : ''; $this->assertEquals($current.$args, $f->find(), '::find() returns the executable PHP'); @@ -50,7 +50,7 @@ public function testFindArguments() public function testNotExitsBinaryFile() { $f = new PhpExecutableFinder(); - $phpBinaryEnv = PHP_BINARY; + $phpBinaryEnv = \PHP_BINARY; putenv('PHP_BINARY=/usr/local/php/bin/php-invalid'); $this->assertFalse($f->find(), '::find() returns false because of not exist file'); diff --git a/src/Symfony/Component/Process/Tests/PhpProcessTest.php b/src/Symfony/Component/Process/Tests/PhpProcessTest.php index 5f1e5e670062..111dc4c76b0b 100644 --- a/src/Symfony/Component/Process/Tests/PhpProcessTest.php +++ b/src/Symfony/Component/Process/Tests/PhpProcessTest.php @@ -45,7 +45,7 @@ public function testCommandLine() $process->wait(); $this->assertStringContainsString($commandLine, $process->getCommandLine(), '::getCommandLine() returns the command line of PHP after wait'); - $this->assertSame(PHP_VERSION.\PHP_SAPI, $process->getOutput()); + $this->assertSame(\PHP_VERSION.\PHP_SAPI, $process->getOutput()); } public function testPassingPhpExplicitly() diff --git a/src/Symfony/Component/Process/Tests/PipeStdinInStdoutStdErrStreamSelect.php b/src/Symfony/Component/Process/Tests/PipeStdinInStdoutStdErrStreamSelect.php index 2e7716de7f4c..a206d2b8e058 100644 --- a/src/Symfony/Component/Process/Tests/PipeStdinInStdoutStdErrStreamSelect.php +++ b/src/Symfony/Component/Process/Tests/PipeStdinInStdoutStdErrStreamSelect.php @@ -14,12 +14,12 @@ define('ERR_READ_FAILED', 3); define('ERR_WRITE_FAILED', 4); -$read = [STDIN]; -$write = [STDOUT, STDERR]; +$read = [\STDIN]; +$write = [\STDOUT, \STDERR]; -stream_set_blocking(STDIN, 0); -stream_set_blocking(STDOUT, 0); -stream_set_blocking(STDERR, 0); +stream_set_blocking(\STDIN, 0); +stream_set_blocking(\STDOUT, 0); +stream_set_blocking(\STDERR, 0); $out = $err = ''; while ($read || $write) { @@ -34,37 +34,37 @@ exit(ERR_TIMEOUT); } - if (in_array(STDOUT, $w) && strlen($out) > 0) { - $written = fwrite(STDOUT, (string) $out, 32768); + if (in_array(\STDOUT, $w) && strlen($out) > 0) { + $written = fwrite(\STDOUT, (string) $out, 32768); if (false === $written) { exit(ERR_WRITE_FAILED); } $out = (string) substr($out, $written); } if (null === $read && '' === $out) { - $write = array_diff($write, [STDOUT]); + $write = array_diff($write, [\STDOUT]); } - if (in_array(STDERR, $w) && strlen($err) > 0) { - $written = fwrite(STDERR, (string) $err, 32768); + if (in_array(\STDERR, $w) && strlen($err) > 0) { + $written = fwrite(\STDERR, (string) $err, 32768); if (false === $written) { exit(ERR_WRITE_FAILED); } $err = (string) substr($err, $written); } if (null === $read && '' === $err) { - $write = array_diff($write, [STDERR]); + $write = array_diff($write, [\STDERR]); } if ($r) { - $str = fread(STDIN, 32768); + $str = fread(\STDIN, 32768); if (false !== $str) { $out .= $str; $err .= $str; } - if (false === $str || feof(STDIN)) { + if (false === $str || feof(\STDIN)) { $read = null; - if (!feof(STDIN)) { + if (!feof(\STDIN)) { exit(ERR_READ_FAILED); } } diff --git a/src/Symfony/Component/Process/Tests/ProcessTest.php b/src/Symfony/Component/Process/Tests/ProcessTest.php index 0f4d15f226cd..6b525d26846f 100644 --- a/src/Symfony/Component/Process/Tests/ProcessTest.php +++ b/src/Symfony/Component/Process/Tests/ProcessTest.php @@ -35,7 +35,7 @@ public static function setUpBeforeClass(): void self::$phpBin = getenv('SYMFONY_PROCESS_PHP_TEST_BINARY') ?: ('phpdbg' === \PHP_SAPI ? 'php' : $phpBin->find()); ob_start(); - phpinfo(INFO_GENERAL); + phpinfo(\INFO_GENERAL); self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild'); } @@ -68,12 +68,12 @@ public function testThatProcessDoesNotThrowWarningDuringRun() if ('\\' === \DIRECTORY_SEPARATOR) { $this->markTestSkipped('This test is transient on Windows'); } - @trigger_error('Test Error', E_USER_NOTICE); + @trigger_error('Test Error', \E_USER_NOTICE); $process = $this->getProcessForCode('sleep(3)'); $process->run(); $actualError = error_get_last(); $this->assertEquals('Test Error', $actualError['message']); - $this->assertEquals(E_USER_NOTICE, $actualError['type']); + $this->assertEquals(\E_USER_NOTICE, $actualError['type']); } public function testNegativeTimeoutFromConstructor() @@ -196,7 +196,7 @@ public function testCallbacksAreExecutedWithStart() $process->wait(); - $this->assertSame('foo'.PHP_EOL, $data); + $this->assertSame('foo'.\PHP_EOL, $data); } /** @@ -401,7 +401,7 @@ public function testIncrementalOutput($getOutput, $getIncrementalOutput, $uri) $p = $this->getProcessForCode('file_put_contents($s = \''.$uri.'\', \'foo\'); flock(fopen('.var_export($lock, true).', \'r\'), LOCK_EX); file_put_contents($s, \'bar\');'); $h = fopen($lock, 'w'); - flock($h, LOCK_EX); + flock($h, \LOCK_EX); $p->start(); @@ -413,7 +413,7 @@ public function testIncrementalOutput($getOutput, $getIncrementalOutput, $uri) $this->assertSame($s, $p->$getIncrementalOutput()); $this->assertSame('', $p->$getIncrementalOutput()); - flock($h, LOCK_UN); + flock($h, \LOCK_UN); } fclose($h); @@ -536,7 +536,7 @@ public function testMustRun() $process = $this->getProcess('echo foo'); $this->assertSame($process, $process->mustRun()); - $this->assertEquals('foo'.PHP_EOL, $process->getOutput()); + $this->assertEquals('foo'.\PHP_EOL, $process->getOutput()); } public function testSuccessfulMustRunHasCorrectExitCode() @@ -899,7 +899,7 @@ public function testSignal() while (false === strpos($process->getOutput(), 'Caught')) { usleep(1000); } - $process->signal(SIGUSR1); + $process->signal(\SIGUSR1); $process->wait(); $this->assertEquals('Caught SIGUSR1', $process->getOutput()); @@ -912,7 +912,7 @@ public function testExitCodeIsAvailableAfterSignal() { $process = $this->getProcess('sleep 4'); $process->start(); - $process->signal(SIGKILL); + $process->signal(\SIGKILL); while ($process->isRunning()) { usleep(10000); @@ -1370,7 +1370,7 @@ public function testSetBadEnv() $process->run(); - $this->assertSame('hello'.PHP_EOL, $process->getOutput()); + $this->assertSame('hello'.\PHP_EOL, $process->getOutput()); $this->assertSame('', $process->getErrorOutput()); } diff --git a/src/Symfony/Component/Process/Tests/SignalListener.php b/src/Symfony/Component/Process/Tests/SignalListener.php index 9e30ce3bbbbc..618be74050f9 100644 --- a/src/Symfony/Component/Process/Tests/SignalListener.php +++ b/src/Symfony/Component/Process/Tests/SignalListener.php @@ -9,7 +9,7 @@ * file that was distributed with this source code. */ -pcntl_signal(SIGUSR1, function () { echo 'SIGUSR1'; exit; }); +pcntl_signal(\SIGUSR1, function () { echo 'SIGUSR1'; exit; }); echo 'Caught '; diff --git a/src/Symfony/Component/PropertyAccess/PropertyAccessor.php b/src/Symfony/Component/PropertyAccess/PropertyAccessor.php index af7331d52b7b..44bf21d74113 100644 --- a/src/Symfony/Component/PropertyAccess/PropertyAccessor.php +++ b/src/Symfony/Component/PropertyAccess/PropertyAccessor.php @@ -676,7 +676,7 @@ public static function createCache(string $namespace, int $defaultLifetime, stri } $apcu = new ApcuAdapter($namespace, $defaultLifetime / 5, $version); - if ('cli' === \PHP_SAPI && !filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN)) { + if ('cli' === \PHP_SAPI && !filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN)) { $apcu->setLogger(new NullLogger()); } elseif (null !== $logger) { $apcu->setLogger($logger); diff --git a/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php b/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php index 10fa47288273..8c207cffc97f 100644 --- a/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php +++ b/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php @@ -130,18 +130,6 @@ public function getProperties(string $class, array $context = []): ?array */ public function getTypes(string $class, string $property, array $context = []): ?array { - if (\PHP_VERSION_ID >= 70400) { - try { - $reflectionProperty = new \ReflectionProperty($class, $property); - $type = $reflectionProperty->getType(); - if (null !== $type) { - return $this->extractFromReflectionType($type, $reflectionProperty->getDeclaringClass()); - } - } catch (\ReflectionException $e) { - // noop - } - } - if ($fromMutator = $this->extractFromMutator($class, $property)) { return $fromMutator; } @@ -161,6 +149,18 @@ public function getTypes(string $class, string $property, array $context = []): return $fromDefaultValue; } + if (\PHP_VERSION_ID >= 70400) { + try { + $reflectionProperty = new \ReflectionProperty($class, $property); + $type = $reflectionProperty->getType(); + if (null !== $type) { + return $this->extractFromReflectionType($type, $reflectionProperty->getDeclaringClass()); + } + } catch (\ReflectionException $e) { + // noop + } + } + return null; } diff --git a/src/Symfony/Component/PropertyInfo/Tests/Extractor/ReflectionExtractorTest.php b/src/Symfony/Component/PropertyInfo/Tests/Extractor/ReflectionExtractorTest.php index 353a41b829c9..a2d2db5b8000 100644 --- a/src/Symfony/Component/PropertyInfo/Tests/Extractor/ReflectionExtractorTest.php +++ b/src/Symfony/Component/PropertyInfo/Tests/Extractor/ReflectionExtractorTest.php @@ -414,6 +414,7 @@ public function testTypedProperties(): void { $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, Dummy::class)], $this->extractor->getTypes(Php74Dummy::class, 'dummy')); $this->assertEquals([new Type(Type::BUILTIN_TYPE_BOOL, true)], $this->extractor->getTypes(Php74Dummy::class, 'nullableBoolProp')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING))], $this->extractor->getTypes(Php74Dummy::class, 'stringCollection')); } /** diff --git a/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Php74Dummy.php b/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Php74Dummy.php index 9d3146442d1e..ffc4f4cd3762 100644 --- a/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Php74Dummy.php +++ b/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Php74Dummy.php @@ -18,4 +18,14 @@ class Php74Dummy { public Dummy $dummy; private ?bool $nullableBoolProp; + /** @var string[] */ + private array $stringCollection; + + public function addStringCollection(string $string): void + { + } + + public function removeStringCollection(string $string): void + { + } } diff --git a/src/Symfony/Component/Routing/Annotation/Route.php b/src/Symfony/Component/Routing/Annotation/Route.php index 9d74fdd2f785..43e185e6cf36 100644 --- a/src/Symfony/Component/Routing/Annotation/Route.php +++ b/src/Symfony/Component/Routing/Annotation/Route.php @@ -65,12 +65,12 @@ public function __construct(array $data) } if (isset($data['utf8'])) { - $data['options']['utf8'] = filter_var($data['utf8'], FILTER_VALIDATE_BOOLEAN) ?: false; + $data['options']['utf8'] = filter_var($data['utf8'], \FILTER_VALIDATE_BOOLEAN) ?: false; unset($data['utf8']); } if (isset($data['stateless'])) { - $data['defaults']['_stateless'] = filter_var($data['stateless'], FILTER_VALIDATE_BOOLEAN) ?: false; + $data['defaults']['_stateless'] = filter_var($data['stateless'], \FILTER_VALIDATE_BOOLEAN) ?: false; unset($data['stateless']); } diff --git a/src/Symfony/Component/Routing/Generator/UrlGenerator.php b/src/Symfony/Component/Routing/Generator/UrlGenerator.php index 5473e856e110..b2768f7f533a 100644 --- a/src/Symfony/Component/Routing/Generator/UrlGenerator.php +++ b/src/Symfony/Component/Routing/Generator/UrlGenerator.php @@ -302,7 +302,7 @@ protected function doGenerate(array $variables, array $defaults, array $requirem unset($extra['_fragment']); } - if ($extra && $query = http_build_query($extra, '', '&', PHP_QUERY_RFC3986)) { + if ($extra && $query = http_build_query($extra, '', '&', \PHP_QUERY_RFC3986)) { $url .= '?'.strtr($query, self::QUERY_FRAGMENT_DECODED); } diff --git a/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php b/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php index 52c72f6c252e..540ba0be328f 100644 --- a/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php +++ b/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php @@ -75,7 +75,7 @@ public function load($file, string $type = null) */ public function supports($resource, string $type = null) { - return \is_string($resource) && 'php' === pathinfo($resource, PATHINFO_EXTENSION) && (!$type || 'annotation' === $type); + return \is_string($resource) && 'php' === pathinfo($resource, \PATHINFO_EXTENSION) && (!$type || 'annotation' === $type); } /** @@ -89,11 +89,11 @@ protected function findClass(string $file) $namespace = false; $tokens = token_get_all(file_get_contents($file)); - if (1 === \count($tokens) && T_INLINE_HTML === $tokens[0][0]) { + if (1 === \count($tokens) && \T_INLINE_HTML === $tokens[0][0]) { throw new \InvalidArgumentException(sprintf('The file "%s" does not contain PHP code. Did you forgot to add the " true, T_STRING => true]; + $nsTokens = [\T_NS_SEPARATOR => true, \T_STRING => true]; if (\defined('T_NAME_QUALIFIED')) { $nsTokens[T_NAME_QUALIFIED] = true; } @@ -105,7 +105,7 @@ protected function findClass(string $file) continue; } - if (true === $class && T_STRING === $token[0]) { + if (true === $class && \T_STRING === $token[0]) { return $namespace.'\\'.$token[1]; } @@ -117,7 +117,7 @@ protected function findClass(string $file) $token = $tokens[$i]; } - if (T_CLASS === $token[0]) { + if (\T_CLASS === $token[0]) { // Skip usage of ::class constant and anonymous classes $skipClassToken = false; for ($j = $i - 1; $j > 0; --$j) { @@ -125,10 +125,10 @@ protected function findClass(string $file) break; } - if (T_DOUBLE_COLON === $tokens[$j][0] || T_NEW === $tokens[$j][0]) { + if (\T_DOUBLE_COLON === $tokens[$j][0] || \T_NEW === $tokens[$j][0]) { $skipClassToken = true; break; - } elseif (!\in_array($tokens[$j][0], [T_WHITESPACE, T_DOC_COMMENT, T_COMMENT])) { + } elseif (!\in_array($tokens[$j][0], [\T_WHITESPACE, \T_DOC_COMMENT, \T_COMMENT])) { break; } } @@ -138,7 +138,7 @@ protected function findClass(string $file) } } - if (T_NAMESPACE === $token[0]) { + if (\T_NAMESPACE === $token[0]) { $namespace = true; } } diff --git a/src/Symfony/Component/Routing/Loader/PhpFileLoader.php b/src/Symfony/Component/Routing/Loader/PhpFileLoader.php index 04d9df61956c..e000c5a0ebae 100644 --- a/src/Symfony/Component/Routing/Loader/PhpFileLoader.php +++ b/src/Symfony/Component/Routing/Loader/PhpFileLoader.php @@ -64,7 +64,7 @@ public function load($file, string $type = null) */ public function supports($resource, string $type = null) { - return \is_string($resource) && 'php' === pathinfo($resource, PATHINFO_EXTENSION) && (!$type || 'php' === $type); + return \is_string($resource) && 'php' === pathinfo($resource, \PATHINFO_EXTENSION) && (!$type || 'php' === $type); } protected function callConfigurator(callable $result, string $path, string $file): RouteCollection diff --git a/src/Symfony/Component/Routing/Loader/XmlFileLoader.php b/src/Symfony/Component/Routing/Loader/XmlFileLoader.php index 4599ee75b5a7..e64089fb30a9 100644 --- a/src/Symfony/Component/Routing/Loader/XmlFileLoader.php +++ b/src/Symfony/Component/Routing/Loader/XmlFileLoader.php @@ -98,7 +98,7 @@ protected function parseNode(RouteCollection $collection, \DOMElement $node, str */ public function supports($resource, string $type = null) { - return \is_string($resource) && 'xml' === pathinfo($resource, PATHINFO_EXTENSION) && (!$type || 'xml' === $type); + return \is_string($resource) && 'xml' === pathinfo($resource, \PATHINFO_EXTENSION) && (!$type || 'xml' === $type); } /** @@ -115,8 +115,8 @@ protected function parseRoute(RouteCollection $collection, \DOMElement $node, st throw new \InvalidArgumentException(sprintf('The element in file "%s" must have an "id" attribute.', $path)); } - $schemes = preg_split('/[\s,\|]++/', $node->getAttribute('schemes'), -1, PREG_SPLIT_NO_EMPTY); - $methods = preg_split('/[\s,\|]++/', $node->getAttribute('methods'), -1, PREG_SPLIT_NO_EMPTY); + $schemes = preg_split('/[\s,\|]++/', $node->getAttribute('schemes'), -1, \PREG_SPLIT_NO_EMPTY); + $methods = preg_split('/[\s,\|]++/', $node->getAttribute('methods'), -1, \PREG_SPLIT_NO_EMPTY); list($defaults, $requirements, $options, $condition, $paths, /* $prefixes */, $hosts) = $this->parseConfigs($node, $path); @@ -158,8 +158,8 @@ protected function parseImport(RouteCollection $collection, \DOMElement $node, s $type = $node->getAttribute('type'); $prefix = $node->getAttribute('prefix'); - $schemes = $node->hasAttribute('schemes') ? preg_split('/[\s,\|]++/', $node->getAttribute('schemes'), -1, PREG_SPLIT_NO_EMPTY) : null; - $methods = $node->hasAttribute('methods') ? preg_split('/[\s,\|]++/', $node->getAttribute('methods'), -1, PREG_SPLIT_NO_EMPTY) : null; + $schemes = $node->hasAttribute('schemes') ? preg_split('/[\s,\|]++/', $node->getAttribute('schemes'), -1, \PREG_SPLIT_NO_EMPTY) : null; + $methods = $node->hasAttribute('methods') ? preg_split('/[\s,\|]++/', $node->getAttribute('methods'), -1, \PREG_SPLIT_NO_EMPTY) : null; $trailingSlashOnRoot = $node->hasAttribute('trailing-slash-on-root') ? XmlUtils::phpize($node->getAttribute('trailing-slash-on-root')) : true; $namePrefix = $node->getAttribute('name-prefix') ?: null; diff --git a/src/Symfony/Component/Routing/Loader/YamlFileLoader.php b/src/Symfony/Component/Routing/Loader/YamlFileLoader.php index cd137eea78be..8bce201c2fe4 100644 --- a/src/Symfony/Component/Routing/Loader/YamlFileLoader.php +++ b/src/Symfony/Component/Routing/Loader/YamlFileLoader.php @@ -101,7 +101,7 @@ public function load($file, string $type = null) */ public function supports($resource, string $type = null) { - return \is_string($resource) && \in_array(pathinfo($resource, PATHINFO_EXTENSION), ['yml', 'yaml'], true) && (!$type || 'yaml' === $type); + return \is_string($resource) && \in_array(pathinfo($resource, \PATHINFO_EXTENSION), ['yml', 'yaml'], true) && (!$type || 'yaml' === $type); } /** diff --git a/src/Symfony/Component/Routing/RouteCompiler.php b/src/Symfony/Component/Routing/RouteCompiler.php index fd09f6ae3c63..618757d9ff2d 100644 --- a/src/Symfony/Component/Routing/RouteCompiler.php +++ b/src/Symfony/Component/Routing/RouteCompiler.php @@ -122,7 +122,7 @@ private static function compilePattern(Route $route, string $pattern, bool $isHo // Match all variables enclosed in "{}" and iterate over them. But we only want to match the innermost variable // in case of nested "{}", e.g. {foo{bar}}. This in ensured because \w does not match "{" or "}" itself. - preg_match_all('#\{(!)?(\w+)\}#', $pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); + preg_match_all('#\{(!)?(\w+)\}#', $pattern, $matches, \PREG_OFFSET_CAPTURE | \PREG_SET_ORDER); foreach ($matches as $match) { $important = $match[1][1] >= 0; $varName = $match[2][0]; @@ -210,7 +210,7 @@ private static function compilePattern(Route $route, string $pattern, bool $isHo } // find the first optional token - $firstOptional = PHP_INT_MAX; + $firstOptional = \PHP_INT_MAX; if (!$isHost) { for ($i = \count($tokens) - 1; $i >= 0; --$i) { $token = $tokens[$i]; diff --git a/src/Symfony/Component/Routing/Router.php b/src/Symfony/Component/Routing/Router.php index 031749b3606f..b5360c4b741d 100644 --- a/src/Symfony/Component/Routing/Router.php +++ b/src/Symfony/Component/Routing/Router.php @@ -373,7 +373,7 @@ private function getConfigCacheFactory(): ConfigCacheFactoryInterface private static function getCompiledRoutes(string $path): array { - if ([] === self::$cache && \function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) || filter_var(ini_get('opcache.enable_cli'), FILTER_VALIDATE_BOOLEAN))) { + if ([] === self::$cache && \function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) || filter_var(ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOLEAN))) { self::$cache = null; } diff --git a/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php b/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php index 841430cec5bf..d07891bf7729 100644 --- a/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php +++ b/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php @@ -153,7 +153,7 @@ private function getEncoderConfigFromAlgorithm(array $config): array case 'bcrypt': $config['algorithm'] = 'native'; - $config['native_algorithm'] = PASSWORD_BCRYPT; + $config['native_algorithm'] = \PASSWORD_BCRYPT; return $this->getEncoderConfigFromAlgorithm($config); @@ -181,7 +181,7 @@ private function getEncoderConfigFromAlgorithm(array $config): array $config['algorithm'] = 'sodium'; } elseif (\defined('PASSWORD_ARGON2I')) { $config['algorithm'] = 'native'; - $config['native_algorithm'] = PASSWORD_ARGON2I; + $config['native_algorithm'] = \PASSWORD_ARGON2I; } else { throw new LogicException(sprintf('Algorithm "argon2i" is not available. Either use %s"auto" or upgrade to PHP 7.2+ instead.', \defined('SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13') ? '"argon2id", ' : '')); } @@ -193,7 +193,7 @@ private function getEncoderConfigFromAlgorithm(array $config): array $config['algorithm'] = 'sodium'; } elseif (\defined('PASSWORD_ARGON2ID')) { $config['algorithm'] = 'native'; - $config['native_algorithm'] = PASSWORD_ARGON2ID; + $config['native_algorithm'] = \PASSWORD_ARGON2ID; } else { throw new LogicException(sprintf('Algorithm "argon2id" is not available. Either use %s"auto", upgrade to PHP 7.3+ or use libsodium 1.0.15+ instead.', \defined('PASSWORD_ARGON2I') || $hasSodium ? '"argon2i", ' : '')); } diff --git a/src/Symfony/Component/Security/Core/Encoder/NativePasswordEncoder.php b/src/Symfony/Component/Security/Core/Encoder/NativePasswordEncoder.php index b678801f5efd..83b7f3f1e89b 100644 --- a/src/Symfony/Component/Security/Core/Encoder/NativePasswordEncoder.php +++ b/src/Symfony/Component/Security/Core/Encoder/NativePasswordEncoder.php @@ -24,7 +24,7 @@ final class NativePasswordEncoder implements PasswordEncoderInterface, SelfSalti { private const MAX_PASSWORD_LENGTH = 4096; - private $algo = PASSWORD_BCRYPT; + private $algo = \PASSWORD_BCRYPT; private $options; /** @@ -33,8 +33,8 @@ final class NativePasswordEncoder implements PasswordEncoderInterface, SelfSalti public function __construct(int $opsLimit = null, int $memLimit = null, int $cost = null, string $algo = null) { $cost = $cost ?? 13; - $opsLimit = $opsLimit ?? max(4, \defined('SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE') ? SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE : 4); - $memLimit = $memLimit ?? max(64 * 1024 * 1024, \defined('SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE') ? SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE : 64 * 1024 * 1024); + $opsLimit = $opsLimit ?? max(4, \defined('SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE') ? \SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE : 4); + $memLimit = $memLimit ?? max(64 * 1024 * 1024, \defined('SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE') ? \SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE : 64 * 1024 * 1024); if (3 > $opsLimit) { throw new \InvalidArgumentException('$opsLimit must be 3 or greater.'); @@ -48,14 +48,14 @@ public function __construct(int $opsLimit = null, int $memLimit = null, int $cos throw new \InvalidArgumentException('$cost must be in the range of 4-31.'); } - $algos = [1 => PASSWORD_BCRYPT, '2y' => PASSWORD_BCRYPT]; + $algos = [1 => \PASSWORD_BCRYPT, '2y' => \PASSWORD_BCRYPT]; if (\defined('PASSWORD_ARGON2I')) { - $this->algo = $algos[2] = $algos['argon2i'] = (string) PASSWORD_ARGON2I; + $this->algo = $algos[2] = $algos['argon2i'] = (string) \PASSWORD_ARGON2I; } if (\defined('PASSWORD_ARGON2ID')) { - $this->algo = $algos[3] = $algos['argon2id'] = (string) PASSWORD_ARGON2ID; + $this->algo = $algos[3] = $algos['argon2id'] = (string) \PASSWORD_ARGON2ID; } if (null !== $algo) { @@ -75,7 +75,7 @@ public function __construct(int $opsLimit = null, int $memLimit = null, int $cos */ public function encodePassword(string $raw, ?string $salt): string { - if (\strlen($raw) > self::MAX_PASSWORD_LENGTH || ((string) PASSWORD_BCRYPT === $this->algo && 72 < \strlen($raw))) { + if (\strlen($raw) > self::MAX_PASSWORD_LENGTH || ((string) \PASSWORD_BCRYPT === $this->algo && 72 < \strlen($raw))) { throw new BadCredentialsException('Invalid password.'); } @@ -102,7 +102,7 @@ public function isPasswordValid(string $encoded, string $raw, ?string $salt): bo return (72 >= \strlen($raw) || 0 !== strpos($encoded, '$2')) && password_verify($raw, $encoded); } - if (\extension_loaded('sodium') && version_compare(SODIUM_LIBRARY_VERSION, '1.0.14', '>=')) { + if (\extension_loaded('sodium') && version_compare(\SODIUM_LIBRARY_VERSION, '1.0.14', '>=')) { return sodium_crypto_pwhash_str_verify($encoded, $raw); } diff --git a/src/Symfony/Component/Security/Core/Encoder/SodiumPasswordEncoder.php b/src/Symfony/Component/Security/Core/Encoder/SodiumPasswordEncoder.php index e6d7e5dbd061..53c6660014a7 100644 --- a/src/Symfony/Component/Security/Core/Encoder/SodiumPasswordEncoder.php +++ b/src/Symfony/Component/Security/Core/Encoder/SodiumPasswordEncoder.php @@ -34,8 +34,8 @@ public function __construct(int $opsLimit = null, int $memLimit = null) throw new LogicException('Libsodium is not available. You should either install the sodium extension, upgrade to PHP 7.2+ or use a different encoder.'); } - $this->opsLimit = $opsLimit ?? max(4, \defined('SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE') ? SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE : 4); - $this->memLimit = $memLimit ?? max(64 * 1024 * 1024, \defined('SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE') ? SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE : 64 * 1024 * 1024); + $this->opsLimit = $opsLimit ?? max(4, \defined('SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE') ? \SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE : 4); + $this->memLimit = $memLimit ?? max(64 * 1024 * 1024, \defined('SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE') ? \SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE : 64 * 1024 * 1024); if (3 > $this->opsLimit) { throw new \InvalidArgumentException('$opsLimit must be 3 or greater.'); @@ -48,7 +48,7 @@ public function __construct(int $opsLimit = null, int $memLimit = null) public static function isSupported(): bool { - return version_compare(\extension_loaded('sodium') ? SODIUM_LIBRARY_VERSION : phpversion('libsodium'), '1.0.14', '>='); + return version_compare(\extension_loaded('sodium') ? \SODIUM_LIBRARY_VERSION : phpversion('libsodium'), '1.0.14', '>='); } /** diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.php index e77307d65dfc..eb2dc498b445 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.php @@ -150,9 +150,9 @@ public function testMigrateFrom() $this->assertInstanceOf(MigratingPasswordEncoder::class, $encoder); $this->assertTrue($encoder->isPasswordValid((new SodiumPasswordEncoder())->encodePassword('foo', null), 'foo', null)); - $this->assertTrue($encoder->isPasswordValid((new NativePasswordEncoder(null, null, null, PASSWORD_BCRYPT))->encodePassword('foo', null), 'foo', null)); + $this->assertTrue($encoder->isPasswordValid((new NativePasswordEncoder(null, null, null, \PASSWORD_BCRYPT))->encodePassword('foo', null), 'foo', null)); $this->assertTrue($encoder->isPasswordValid($digest->encodePassword('foo', null), 'foo', null)); - $this->assertStringStartsWith(SODIUM_CRYPTO_PWHASH_STRPREFIX, $encoder->encodePassword('foo', null)); + $this->assertStringStartsWith(\SODIUM_CRYPTO_PWHASH_STRPREFIX, $encoder->encodePassword('foo', null)); } public function testDefaultMigratingEncoders() diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/NativePasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/NativePasswordEncoderTest.php index 9388e9c2c53c..7ee256f04075 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/NativePasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/NativePasswordEncoderTest.php @@ -67,7 +67,7 @@ public function testNonArgonValidation() public function testConfiguredAlgorithm() { - $encoder = new NativePasswordEncoder(null, null, null, PASSWORD_BCRYPT); + $encoder = new NativePasswordEncoder(null, null, null, \PASSWORD_BCRYPT); $result = $encoder->encodePassword('password', null); $this->assertTrue($encoder->isPasswordValid($result, 'password', null)); $this->assertStringStartsWith('$2', $result); @@ -84,7 +84,7 @@ public function testConfiguredAlgorithmWithLegacyConstValue() public function testCheckPasswordLength() { $encoder = new NativePasswordEncoder(null, null, 4); - $result = password_hash(str_repeat('a', 72), PASSWORD_BCRYPT, ['cost' => 4]); + $result = password_hash(str_repeat('a', 72), \PASSWORD_BCRYPT, ['cost' => 4]); $this->assertFalse($encoder->isPasswordValid($result, str_repeat('a', 73), 'salt')); $this->assertTrue($encoder->isPasswordValid($result, str_repeat('a', 72), 'salt')); diff --git a/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.php b/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.php index dd353515fea4..ead39789979b 100644 --- a/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.php +++ b/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.php @@ -47,11 +47,11 @@ public function testStoreTokenInClosedSessionWithExistingSessionId() { session_id('foobar'); - $this->assertSame(PHP_SESSION_NONE, session_status()); + $this->assertSame(\PHP_SESSION_NONE, session_status()); $this->storage->setToken('token_id', 'TOKEN'); - $this->assertSame(PHP_SESSION_ACTIVE, session_status()); + $this->assertSame(\PHP_SESSION_ACTIVE, session_status()); $this->assertSame([self::SESSION_NAMESPACE => ['token_id' => 'TOKEN']], $_SESSION); } diff --git a/src/Symfony/Component/Security/Csrf/TokenStorage/NativeSessionTokenStorage.php b/src/Symfony/Component/Security/Csrf/TokenStorage/NativeSessionTokenStorage.php index 75f03df7bbe0..2670072cfb39 100644 --- a/src/Symfony/Component/Security/Csrf/TokenStorage/NativeSessionTokenStorage.php +++ b/src/Symfony/Component/Security/Csrf/TokenStorage/NativeSessionTokenStorage.php @@ -112,7 +112,7 @@ public function clear() private function startSession() { - if (PHP_SESSION_NONE === session_status()) { + if (\PHP_SESSION_NONE === session_status()) { session_start(); } diff --git a/src/Symfony/Component/Security/Http/Firewall/ContextListener.php b/src/Symfony/Component/Security/Http/Firewall/ContextListener.php index 7cf19dbb8565..66b54d325b11 100644 --- a/src/Symfony/Component/Security/Http/Firewall/ContextListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/ContextListener.php @@ -96,7 +96,7 @@ public function authenticate(RequestEvent $event) if (null !== $session) { $usageIndexValue = $session instanceof Session ? $usageIndexReference = &$session->getUsageIndex() : 0; - $usageIndexReference = PHP_INT_MIN; + $usageIndexReference = \PHP_INT_MIN; $sessionId = $request->cookies->all()[$session->getName()] ?? null; $token = $session->get($this->sessionKey); @@ -104,7 +104,7 @@ public function authenticate(RequestEvent $event) if ($this->sessionTrackerEnabler && \in_array($sessionId, [true, $session->getId()], true)) { $usageIndexReference = $usageIndexValue; } else { - $usageIndexReference = $usageIndexReference - PHP_INT_MIN + $usageIndexValue; + $usageIndexReference = $usageIndexReference - \PHP_INT_MIN + $usageIndexValue; } } diff --git a/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php b/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php index dde4c01c499a..94056d9ef008 100644 --- a/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php @@ -195,6 +195,10 @@ private function handleLogoutException(ExceptionEvent $event, LogoutException $e private function startAuthentication(Request $request, AuthenticationException $authException): Response { if (null === $this->authenticationEntryPoint) { + if (null !== $this->logger) { + $this->logger->notice(sprintf('No Authentication entry point configured, returning a %s HTTP response. Configure "entry_point" on the firewall ("{firewall_name}") if you want to modify the response.', Response::HTTP_UNAUTHORIZED), ['firewall_name' => $this->providerKey]); + } + throw new HttpException(Response::HTTP_UNAUTHORIZED, $authException->getMessage(), $authException, [], $authException->getCode()); } diff --git a/src/Symfony/Component/Security/Http/HttpUtils.php b/src/Symfony/Component/Security/Http/HttpUtils.php index 70416b6e4214..9b96832bbbbd 100644 --- a/src/Symfony/Component/Security/Http/HttpUtils.php +++ b/src/Symfony/Component/Security/Http/HttpUtils.php @@ -167,7 +167,7 @@ public function generateUri(Request $request, string $path) // fortunately, they all are, so we have to remove entire query string $position = strpos($url, '?'); if (false !== $position) { - $fragment = parse_url($url, PHP_URL_FRAGMENT); + $fragment = parse_url($url, \PHP_URL_FRAGMENT); $url = substr($url, 0, $position); // fragment must be preserved if ($fragment) { diff --git a/src/Symfony/Component/Security/Http/Tests/Authenticator/Fixtures/PasswordUpgraderProvider.php b/src/Symfony/Component/Security/Http/Tests/Authenticator/Fixtures/PasswordUpgraderProvider.php new file mode 100644 index 000000000000..5836d8893ef7 --- /dev/null +++ b/src/Symfony/Component/Security/Http/Tests/Authenticator/Fixtures/PasswordUpgraderProvider.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Security\Http\Tests\Authenticator\Fixtures; + +use Symfony\Component\Security\Core\User\PasswordUpgraderInterface; +use Symfony\Component\Security\Core\User\UserProviderInterface; + +abstract class PasswordUpgraderProvider implements UserProviderInterface, PasswordUpgraderInterface +{ +} diff --git a/src/Symfony/Component/Security/Http/Tests/Authenticator/FormLoginAuthenticatorTest.php b/src/Symfony/Component/Security/Http/Tests/Authenticator/FormLoginAuthenticatorTest.php index a5449b0bcf8d..bf466e794a88 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authenticator/FormLoginAuthenticatorTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authenticator/FormLoginAuthenticatorTest.php @@ -16,7 +16,6 @@ use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\Security\Core\Exception\BadCredentialsException; use Symfony\Component\Security\Core\Security; -use Symfony\Component\Security\Core\User\PasswordUpgraderInterface; use Symfony\Component\Security\Core\User\User; use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface; @@ -25,6 +24,7 @@ use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge; use Symfony\Component\Security\Http\HttpUtils; +use Symfony\Component\Security\Http\Tests\Authenticator\Fixtures\PasswordUpgraderProvider; class FormLoginAuthenticatorTest extends TestCase { @@ -148,7 +148,7 @@ public function testUpgradePassword() $request = Request::create('/login_check', 'POST', ['_username' => 'wouter', '_password' => 's$cr$t']); $request->setSession($this->createSession()); - $this->userProvider = $this->createMock([UserProviderInterface::class, PasswordUpgraderInterface::class]); + $this->userProvider = $this->createMock(PasswordUpgraderProvider::class); $this->userProvider->expects($this->any())->method('loadUserByUsername')->willReturn(new User('test', 's$cr$t')); $this->setUpAuthenticator(); diff --git a/src/Symfony/Component/Security/Http/Tests/Authenticator/HttpBasicAuthenticatorTest.php b/src/Symfony/Component/Security/Http/Tests/Authenticator/HttpBasicAuthenticatorTest.php index a033ef57eb06..fa9e521738e5 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authenticator/HttpBasicAuthenticatorTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authenticator/HttpBasicAuthenticatorTest.php @@ -6,12 +6,12 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface; use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface; -use Symfony\Component\Security\Core\User\PasswordUpgraderInterface; use Symfony\Component\Security\Core\User\User; use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Http\Authenticator\HttpBasicAuthenticator; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge; use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials; +use Symfony\Component\Security\Http\Tests\Authenticator\Fixtures\PasswordUpgraderProvider; class HttpBasicAuthenticatorTest extends TestCase { @@ -77,7 +77,7 @@ public function testUpgradePassword() 'PHP_AUTH_PW' => 'ThePassword', ]); - $this->userProvider = $this->createMock([UserProviderInterface::class, PasswordUpgraderInterface::class]); + $this->userProvider = $this->createMock(PasswordUpgraderProvider::class); $this->userProvider->expects($this->any())->method('loadUserByUsername')->willReturn(new User('test', 's$cr$t')); $authenticator = new HttpBasicAuthenticator('test', $this->userProvider); diff --git a/src/Symfony/Component/Serializer/Encoder/JsonDecode.php b/src/Symfony/Component/Serializer/Encoder/JsonDecode.php index af268f75efcc..dda813d7aef2 100644 --- a/src/Symfony/Component/Serializer/Encoder/JsonDecode.php +++ b/src/Symfony/Component/Serializer/Encoder/JsonDecode.php @@ -84,11 +84,11 @@ public function decode(string $data, string $format, array $context = []) throw new NotEncodableValueException($e->getMessage(), 0, $e); } - if (\PHP_VERSION_ID >= 70300 && (JSON_THROW_ON_ERROR & $options)) { + if (\PHP_VERSION_ID >= 70300 && (\JSON_THROW_ON_ERROR & $options)) { return $decodedData; } - if (JSON_ERROR_NONE !== json_last_error()) { + if (\JSON_ERROR_NONE !== json_last_error()) { throw new NotEncodableValueException(json_last_error_msg()); } diff --git a/src/Symfony/Component/Serializer/Encoder/JsonEncode.php b/src/Symfony/Component/Serializer/Encoder/JsonEncode.php index 2349e8ed5bf4..93c359eaf7ae 100644 --- a/src/Symfony/Component/Serializer/Encoder/JsonEncode.php +++ b/src/Symfony/Component/Serializer/Encoder/JsonEncode.php @@ -46,11 +46,11 @@ public function encode($data, string $format, array $context = []) throw new NotEncodableValueException($e->getMessage(), 0, $e); } - if (\PHP_VERSION_ID >= 70300 && (JSON_THROW_ON_ERROR & $options)) { + if (\PHP_VERSION_ID >= 70300 && (\JSON_THROW_ON_ERROR & $options)) { return $encodedJson; } - if (JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($options & JSON_PARTIAL_OUTPUT_ON_ERROR))) { + if (\JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($options & \JSON_PARTIAL_OUTPUT_ON_ERROR))) { throw new NotEncodableValueException(json_last_error_msg()); } diff --git a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php index bd79694ef45a..9e4902c7cd75 100644 --- a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php +++ b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php @@ -57,9 +57,9 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa private $defaultContext = [ self::AS_COLLECTION => false, - self::DECODER_IGNORED_NODE_TYPES => [XML_PI_NODE, XML_COMMENT_NODE], + self::DECODER_IGNORED_NODE_TYPES => [\XML_PI_NODE, \XML_COMMENT_NODE], self::ENCODER_IGNORED_NODE_TYPES => [], - self::LOAD_OPTIONS => LIBXML_NONET | LIBXML_NOBLANKS, + self::LOAD_OPTIONS => \LIBXML_NONET | \LIBXML_NOBLANKS, self::REMOVE_EMPTY_TAGS => false, self::ROOT_NODE_NAME => 'response', self::TYPE_CAST_ATTRIBUTES => true, @@ -83,7 +83,7 @@ public function __construct(array $defaultContext = []) public function encode($data, string $format, array $context = []) { $encoderIgnoredNodeTypes = $context[self::ENCODER_IGNORED_NODE_TYPES] ?? $this->defaultContext[self::ENCODER_IGNORED_NODE_TYPES]; - $ignorePiNode = \in_array(XML_PI_NODE, $encoderIgnoredNodeTypes, true); + $ignorePiNode = \in_array(\XML_PI_NODE, $encoderIgnoredNodeTypes, true); if ($data instanceof \DOMDocument) { return $data->saveXML($ignorePiNode ? $data->documentElement : null); } @@ -115,7 +115,7 @@ public function decode(string $data, string $format, array $context = []) } $internalErrors = libxml_use_internal_errors(true); - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { $disableEntities = libxml_disable_entity_loader(true); } libxml_clear_errors(); @@ -124,7 +124,7 @@ public function decode(string $data, string $format, array $context = []) $dom->loadXML($data, $context[self::LOAD_OPTIONS] ?? $this->defaultContext[self::LOAD_OPTIONS]); libxml_use_internal_errors($internalErrors); - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { libxml_disable_entity_loader($disableEntities); } @@ -137,7 +137,7 @@ public function decode(string $data, string $format, array $context = []) $rootNode = null; $decoderIgnoredNodeTypes = $context[self::DECODER_IGNORED_NODE_TYPES] ?? $this->defaultContext[self::DECODER_IGNORED_NODE_TYPES]; foreach ($dom->childNodes as $child) { - if (XML_DOCUMENT_TYPE_NODE === $child->nodeType) { + if (\XML_DOCUMENT_TYPE_NODE === $child->nodeType) { throw new NotEncodableValueException('Document types are not allowed.'); } if (!$rootNode && !\in_array($child->nodeType, $decoderIgnoredNodeTypes, true)) { @@ -307,7 +307,7 @@ private function parseXmlAttributes(\DOMNode $node, array $context = []): array continue; } - if (false !== $val = filter_var($attr->nodeValue, FILTER_VALIDATE_INT)) { + if (false !== $val = filter_var($attr->nodeValue, \FILTER_VALIDATE_INT)) { $data['@'.$attr->nodeName] = $val; continue; @@ -330,7 +330,7 @@ private function parseXmlValue(\DOMNode $node, array $context = []) return $node->nodeValue; } - if (1 === $node->childNodes->length && \in_array($node->firstChild->nodeType, [XML_TEXT_NODE, XML_CDATA_SECTION_NODE])) { + if (1 === $node->childNodes->length && \in_array($node->firstChild->nodeType, [\XML_TEXT_NODE, \XML_CDATA_SECTION_NODE])) { return $node->firstChild->nodeValue; } @@ -384,7 +384,7 @@ private function buildXml(\DOMNode $parentNode, $data, string $xmlRootNodeName = } elseif ('#' === $key) { $append = $this->selectNodeType($parentNode, $data); } elseif ('#comment' === $key) { - if (!\in_array(XML_COMMENT_NODE, $encoderIgnoredNodeTypes, true)) { + if (!\in_array(\XML_COMMENT_NODE, $encoderIgnoredNodeTypes, true)) { $append = $this->appendComment($parentNode, $data); } } elseif (\is_array($data) && false === is_numeric($key)) { diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncodeTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncodeTest.php index 0ddaf79e956c..157b3999eac5 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncodeTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncodeTest.php @@ -45,7 +45,7 @@ public function encodeProvider() { return [ [[], '[]', []], - [[], '{}', ['json_encode_options' => JSON_FORCE_OBJECT]], + [[], '{}', ['json_encode_options' => \JSON_FORCE_OBJECT]], [new \ArrayObject(), '{}', []], [new \ArrayObject(['foo' => 'bar']), '{"foo":"bar"}', []], ]; diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php index 75187b9748ed..b74d10bfca93 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php @@ -48,7 +48,7 @@ public function testComplexObject() public function testOptions() { - $context = ['json_encode_options' => JSON_NUMERIC_CHECK]; + $context = ['json_encode_options' => \JSON_NUMERIC_CHECK]; $arr = []; $arr['foo'] = '3'; @@ -78,7 +78,7 @@ public function testEncodeNotUtf8WithoutPartialOnError() public function testEncodeNotUtf8WithPartialOnError() { - $context = ['json_encode_options' => JSON_PARTIAL_OUTPUT_ON_ERROR]; + $context = ['json_encode_options' => \JSON_PARTIAL_OUTPUT_ON_ERROR]; $arr = [ 'utf8' => 'Hello World!', @@ -88,16 +88,16 @@ public function testEncodeNotUtf8WithPartialOnError() $result = $this->encoder->encode($arr, 'json', $context); $jsonLastError = json_last_error(); - $this->assertSame(JSON_ERROR_UTF8, $jsonLastError); + $this->assertSame(\JSON_ERROR_UTF8, $jsonLastError); $this->assertEquals('{"utf8":"Hello World!","notUtf8":null}', $result); - $this->assertEquals('0', $this->serializer->serialize(NAN, 'json', $context)); + $this->assertEquals('0', $this->serializer->serialize(\NAN, 'json', $context)); } public function testDecodeFalseString() { $result = $this->encoder->decode('false', 'json'); - $this->assertSame(JSON_ERROR_NONE, json_last_error()); + $this->assertSame(\JSON_ERROR_NONE, json_last_error()); $this->assertFalse($result); } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php index 4150652502b3..c1bb517ab07f 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php @@ -580,7 +580,7 @@ public function testDecodePreserveComments() $this->encoder = new XmlEncoder([ XmlEncoder::ROOT_NODE_NAME => 'people', - XmlEncoder::DECODER_IGNORED_NODE_TYPES => [XML_PI_NODE], + XmlEncoder::DECODER_IGNORED_NODE_TYPES => [\XML_PI_NODE], ]); $serializer = new Serializer([new CustomNormalizer()], ['xml' => new XmlEncoder()]); $this->encoder->setSerializer($serializer); @@ -813,7 +813,7 @@ public function testEncodeWithoutPi() { $encoder = new XmlEncoder([ XmlEncoder::ROOT_NODE_NAME => 'response', - XmlEncoder::ENCODER_IGNORED_NODE_TYPES => [XML_PI_NODE], + XmlEncoder::ENCODER_IGNORED_NODE_TYPES => [\XML_PI_NODE], ]); $expected = ''; @@ -825,7 +825,7 @@ public function testEncodeWithoutComment() { $encoder = new XmlEncoder([ XmlEncoder::ROOT_NODE_NAME => 'response', - XmlEncoder::ENCODER_IGNORED_NODE_TYPES => [XML_COMMENT_NODE], + XmlEncoder::ENCODER_IGNORED_NODE_TYPES => [\XML_COMMENT_NODE], ]); $expected = <<<'XML' diff --git a/src/Symfony/Component/String/AbstractString.php b/src/Symfony/Component/String/AbstractString.php index 31e78d19d42d..c87f1506fb6f 100644 --- a/src/Symfony/Component/String/AbstractString.php +++ b/src/Symfony/Component/String/AbstractString.php @@ -29,15 +29,15 @@ */ abstract class AbstractString implements \Stringable, \JsonSerializable { - public const PREG_PATTERN_ORDER = PREG_PATTERN_ORDER; - public const PREG_SET_ORDER = PREG_SET_ORDER; - public const PREG_OFFSET_CAPTURE = PREG_OFFSET_CAPTURE; - public const PREG_UNMATCHED_AS_NULL = PREG_UNMATCHED_AS_NULL; + public const PREG_PATTERN_ORDER = \PREG_PATTERN_ORDER; + public const PREG_SET_ORDER = \PREG_SET_ORDER; + public const PREG_OFFSET_CAPTURE = \PREG_OFFSET_CAPTURE; + public const PREG_UNMATCHED_AS_NULL = \PREG_UNMATCHED_AS_NULL; public const PREG_SPLIT = 0; - public const PREG_SPLIT_NO_EMPTY = PREG_SPLIT_NO_EMPTY; - public const PREG_SPLIT_DELIM_CAPTURE = PREG_SPLIT_DELIM_CAPTURE; - public const PREG_SPLIT_OFFSET_CAPTURE = PREG_SPLIT_OFFSET_CAPTURE; + public const PREG_SPLIT_NO_EMPTY = \PREG_SPLIT_NO_EMPTY; + public const PREG_SPLIT_DELIM_CAPTURE = \PREG_SPLIT_DELIM_CAPTURE; + public const PREG_SPLIT_OFFSET_CAPTURE = \PREG_SPLIT_OFFSET_CAPTURE; protected $string = ''; protected $ignoreCase = false; @@ -99,7 +99,7 @@ public function after($needle, bool $includeNeedle = false, int $offset = 0): se { $str = clone $this; $str->string = ''; - $i = PHP_INT_MAX; + $i = \PHP_INT_MAX; foreach ((array) $needle as $n) { $n = (string) $n; @@ -111,7 +111,7 @@ public function after($needle, bool $includeNeedle = false, int $offset = 0): se } } - if (PHP_INT_MAX === $i) { + if (\PHP_INT_MAX === $i) { return $str; } @@ -168,7 +168,7 @@ public function before($needle, bool $includeNeedle = false, int $offset = 0): s { $str = clone $this; $str->string = ''; - $i = PHP_INT_MAX; + $i = \PHP_INT_MAX; foreach ((array) $needle as $n) { $n = (string) $n; @@ -180,7 +180,7 @@ public function before($needle, bool $includeNeedle = false, int $offset = 0): s } } - if (PHP_INT_MAX === $i) { + if (\PHP_INT_MAX === $i) { return $str; } @@ -360,7 +360,7 @@ public function indexOf($needle, int $offset = 0): ?int throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class)); } - $i = PHP_INT_MAX; + $i = \PHP_INT_MAX; foreach ($needle as $n) { $j = $this->indexOf((string) $n, $offset); @@ -370,7 +370,7 @@ public function indexOf($needle, int $offset = 0): ?int } } - return PHP_INT_MAX === $i ? null : $i; + return \PHP_INT_MAX === $i ? null : $i; } /** diff --git a/src/Symfony/Component/String/AbstractUnicodeString.php b/src/Symfony/Component/String/AbstractUnicodeString.php index 9605eacc8557..0725e1e515b8 100644 --- a/src/Symfony/Component/String/AbstractUnicodeString.php +++ b/src/Symfony/Component/String/AbstractUnicodeString.php @@ -137,15 +137,15 @@ public function ascii(array $rules = []): self } } elseif (!\function_exists('iconv')) { $s = preg_replace('/[^\x00-\x7F]/u', '?', $s); - } elseif (ICONV_IMPL === 'glibc') { - $s = iconv('UTF-8', 'ASCII//TRANSLIT', $s); } else { $s = @preg_replace_callback('/[^\x00-\x7F]/u', static function ($c) { - if ('' === $c = (string) iconv('UTF-8', 'ASCII//IGNORE//TRANSLIT', $c[0])) { + $c = (string) iconv('UTF-8', 'ASCII//TRANSLIT', $c[0]); + + if ('' === $c && '' === iconv('UTF-8', 'ASCII//TRANSLIT', '²')) { throw new \LogicException(sprintf('"%s" requires a translit-able iconv implementation, try installing "gnu-libiconv" if you\'re using Alpine Linux.', static::class)); } - return 1 < \strlen($c) ? ltrim($c, '\'`"^~') : (\strlen($c) ? $c : '?'); + return 1 < \strlen($c) ? ltrim($c, '\'`"^~') : ('' !== $c ? $c : '?'); }, $s); } } @@ -159,7 +159,7 @@ public function camel(): parent { $str = clone $this; $str->string = str_replace(' ', '', preg_replace_callback('/\b./u', static function ($m) use (&$i) { - return 1 === ++$i ? ('İ' === $m[0] ? 'i̇' : mb_strtolower($m[0], 'UTF-8')) : mb_convert_case($m[0], MB_CASE_TITLE, 'UTF-8'); + return 1 === ++$i ? ('İ' === $m[0] ? 'i̇' : mb_strtolower($m[0], 'UTF-8')) : mb_convert_case($m[0], \MB_CASE_TITLE, 'UTF-8'); }, preg_replace('/[^\pL0-9]++/u', ' ', $this->string))); return $str; @@ -178,7 +178,7 @@ public function codePointsAt(int $offset): array $codePoints = []; - foreach (preg_split('//u', $str->string, -1, PREG_SPLIT_NO_EMPTY) as $c) { + foreach (preg_split('//u', $str->string, -1, \PREG_SPLIT_NO_EMPTY) as $c) { $codePoints[] = mb_ord($c, 'UTF-8'); } @@ -223,7 +223,7 @@ public function lower(): parent public function match(string $regexp, int $flags = 0, int $offset = 0): array { - $match = ((PREG_PATTERN_ORDER | PREG_SET_ORDER) & $flags) ? 'preg_match_all' : 'preg_match'; + $match = ((\PREG_PATTERN_ORDER | \PREG_SET_ORDER) & $flags) ? 'preg_match_all' : 'preg_match'; if ($this->ignoreCase) { $regexp .= 'i'; @@ -232,7 +232,7 @@ public function match(string $regexp, int $flags = 0, int $offset = 0): array set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); }); try { - if (false === $match($regexp.'u', $this->string, $matches, $flags | PREG_UNMATCHED_AS_NULL, $offset)) { + if (false === $match($regexp.'u', $this->string, $matches, $flags | \PREG_UNMATCHED_AS_NULL, $offset)) { $lastError = preg_last_error(); foreach (get_defined_constants(true)['pcre'] as $k => $v) { @@ -274,7 +274,7 @@ public function padBoth(int $length, string $padStr = ' '): parent $pad = clone $this; $pad->string = $padStr; - return $this->pad($length, $pad, STR_PAD_BOTH); + return $this->pad($length, $pad, \STR_PAD_BOTH); } public function padEnd(int $length, string $padStr = ' '): parent @@ -286,7 +286,7 @@ public function padEnd(int $length, string $padStr = ' '): parent $pad = clone $this; $pad->string = $padStr; - return $this->pad($length, $pad, STR_PAD_RIGHT); + return $this->pad($length, $pad, \STR_PAD_RIGHT); } public function padStart(int $length, string $padStr = ' '): parent @@ -298,7 +298,7 @@ public function padStart(int $length, string $padStr = ' '): parent $pad = clone $this; $pad->string = $padStr; - return $this->pad($length, $pad, STR_PAD_LEFT); + return $this->pad($length, $pad, \STR_PAD_LEFT); } public function replaceMatches(string $fromRegexp, $to): parent @@ -355,7 +355,7 @@ public function replaceMatches(string $fromRegexp, $to): parent public function reverse(): parent { $str = clone $this; - $str->string = implode('', array_reverse(preg_split('/(\X)/u', $str->string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY))); + $str->string = implode('', array_reverse(preg_split('/(\X)/u', $str->string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY))); return $str; } @@ -375,7 +375,7 @@ public function title(bool $allWords = false): parent $limit = $allWords ? -1 : 1; $str->string = preg_replace_callback('/\b./u', static function (array $m): string { - return mb_convert_case($m[0], MB_CASE_TITLE, 'UTF-8'); + return mb_convert_case($m[0], \MB_CASE_TITLE, 'UTF-8'); }, $str->string, $limit); return $str; @@ -477,13 +477,13 @@ private function pad(int $len, self $pad, int $type): parent $len = $freeLen % $padLen; switch ($type) { - case STR_PAD_RIGHT: + case \STR_PAD_RIGHT: return $this->append(str_repeat($pad->string, $freeLen / $padLen).($len ? $pad->slice(0, $len) : '')); - case STR_PAD_LEFT: + case \STR_PAD_LEFT: return $this->prepend(str_repeat($pad->string, $freeLen / $padLen).($len ? $pad->slice(0, $len) : '')); - case STR_PAD_BOTH: + case \STR_PAD_BOTH: $freeLen /= 2; $rightLen = ceil($freeLen); @@ -507,7 +507,7 @@ private function wcswidth(string $string): int { $width = 0; - foreach (preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY) as $c) { + foreach (preg_split('//u', $string, -1, \PREG_SPLIT_NO_EMPTY) as $c) { $codePoint = mb_ord($c, 'UTF-8'); if (0 === $codePoint // NULL diff --git a/src/Symfony/Component/String/ByteString.php b/src/Symfony/Component/String/ByteString.php index 9fb741f58f6d..a7bcab5740a9 100644 --- a/src/Symfony/Component/String/ByteString.php +++ b/src/Symfony/Component/String/ByteString.php @@ -235,7 +235,7 @@ public function lower(): parent public function match(string $regexp, int $flags = 0, int $offset = 0): array { - $match = ((PREG_PATTERN_ORDER | PREG_SET_ORDER) & $flags) ? 'preg_match_all' : 'preg_match'; + $match = ((\PREG_PATTERN_ORDER | \PREG_SET_ORDER) & $flags) ? 'preg_match_all' : 'preg_match'; if ($this->ignoreCase) { $regexp .= 'i'; @@ -244,7 +244,7 @@ public function match(string $regexp, int $flags = 0, int $offset = 0): array set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); }); try { - if (false === $match($regexp, $this->string, $matches, $flags | PREG_UNMATCHED_AS_NULL, $offset)) { + if (false === $match($regexp, $this->string, $matches, $flags | \PREG_UNMATCHED_AS_NULL, $offset)) { $lastError = preg_last_error(); foreach (get_defined_constants(true)['pcre'] as $k => $v) { @@ -265,7 +265,7 @@ public function match(string $regexp, int $flags = 0, int $offset = 0): array public function padBoth(int $length, string $padStr = ' '): parent { $str = clone $this; - $str->string = str_pad($this->string, $length, $padStr, STR_PAD_BOTH); + $str->string = str_pad($this->string, $length, $padStr, \STR_PAD_BOTH); return $str; } @@ -273,7 +273,7 @@ public function padBoth(int $length, string $padStr = ' '): parent public function padEnd(int $length, string $padStr = ' '): parent { $str = clone $this; - $str->string = str_pad($this->string, $length, $padStr, STR_PAD_RIGHT); + $str->string = str_pad($this->string, $length, $padStr, \STR_PAD_RIGHT); return $str; } @@ -281,7 +281,7 @@ public function padEnd(int $length, string $padStr = ' '): parent public function padStart(int $length, string $padStr = ' '): parent { $str = clone $this; - $str->string = str_pad($this->string, $length, $padStr, STR_PAD_LEFT); + $str->string = str_pad($this->string, $length, $padStr, \STR_PAD_LEFT); return $str; } @@ -356,7 +356,7 @@ public function reverse(): parent public function slice(int $start = 0, int $length = null): parent { $str = clone $this; - $str->string = (string) substr($this->string, $start, $length ?? PHP_INT_MAX); + $str->string = (string) substr($this->string, $start, $length ?? \PHP_INT_MAX); return $str; } @@ -372,14 +372,14 @@ public function snake(): parent public function splice(string $replacement, int $start = 0, int $length = null): parent { $str = clone $this; - $str->string = substr_replace($this->string, $replacement, $start, $length ?? PHP_INT_MAX); + $str->string = substr_replace($this->string, $replacement, $start, $length ?? \PHP_INT_MAX); return $str; } public function split(string $delimiter, int $limit = null, int $flags = null): array { - if (1 > $limit = $limit ?? PHP_INT_MAX) { + if (1 > $limit = $limit ?? \PHP_INT_MAX) { throw new InvalidArgumentException('Split limit must be a positive integer.'); } diff --git a/src/Symfony/Component/String/CodePointString.php b/src/Symfony/Component/String/CodePointString.php index 9cc585fe140b..8ab9209413b5 100644 --- a/src/Symfony/Component/String/CodePointString.php +++ b/src/Symfony/Component/String/CodePointString.php @@ -65,7 +65,7 @@ public function chunk(int $length = 1): array $str = clone $this; $chunks = []; - foreach (preg_split($rx, $this->string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $chunk) { + foreach (preg_split($rx, $this->string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY) as $chunk) { $str->string = $chunk; $chunks[] = clone $str; } @@ -211,14 +211,14 @@ public function splice(string $replacement, int $start = 0, int $length = null): $str = clone $this; $start = $start ? \strlen(mb_substr($this->string, 0, $start, 'UTF-8')) : 0; $length = $length ? \strlen(mb_substr($this->string, $start, $length, 'UTF-8')) : $length; - $str->string = substr_replace($this->string, $replacement, $start, $length ?? PHP_INT_MAX); + $str->string = substr_replace($this->string, $replacement, $start, $length ?? \PHP_INT_MAX); return $str; } public function split(string $delimiter, int $limit = null, int $flags = null): array { - if (1 > $limit = $limit ?? PHP_INT_MAX) { + if (1 > $limit = $limit ?? \PHP_INT_MAX) { throw new InvalidArgumentException('Split limit must be a positive integer.'); } diff --git a/src/Symfony/Component/String/LazyString.php b/src/Symfony/Component/String/LazyString.php index 9b9c667cfb0f..b3801db7711f 100644 --- a/src/Symfony/Component/String/LazyString.php +++ b/src/Symfony/Component/String/LazyString.php @@ -113,7 +113,7 @@ public function __toString() if (\PHP_VERSION_ID < 70400) { // leverage the ErrorHandler component with graceful fallback when it's not available - return trigger_error($e, E_USER_ERROR); + return trigger_error($e, \E_USER_ERROR); } throw $e; diff --git a/src/Symfony/Component/String/Resources/WcswidthDataGenerator.php b/src/Symfony/Component/String/Resources/WcswidthDataGenerator.php index cd507350d6a8..69d32e292a99 100644 --- a/src/Symfony/Component/String/Resources/WcswidthDataGenerator.php +++ b/src/Symfony/Component/String/Resources/WcswidthDataGenerator.php @@ -46,7 +46,7 @@ private function writeWideWidthData(): void $version = $matches[1]; - if (!preg_match_all('/^([A-H\d]{4,})(?:\.\.([A-H\d]{4,}))?;[W|F]/m', $content, $matches, PREG_SET_ORDER)) { + if (!preg_match_all('/^([A-H\d]{4,})(?:\.\.([A-H\d]{4,}))?;[W|F]/m', $content, $matches, \PREG_SET_ORDER)) { throw new RuntimeException('The wide width pattern did not match anything.'); } @@ -61,7 +61,7 @@ private function writeZeroWidthData(): void $version = $matches[1]; - if (!preg_match_all('/^([A-H\d]{4,})(?:\.\.([A-H\d]{4,}))? *; (?:Me|Mn)/m', $content, $matches, PREG_SET_ORDER)) { + if (!preg_match_all('/^([A-H\d]{4,})(?:\.\.([A-H\d]{4,}))? *; (?:Me|Mn)/m', $content, $matches, \PREG_SET_ORDER)) { throw new RuntimeException('The zero width pattern did not match anything.'); } diff --git a/src/Symfony/Component/String/Resources/bin/update-data.php b/src/Symfony/Component/String/Resources/bin/update-data.php index 0fd5567f8887..3f66be2b7656 100644 --- a/src/Symfony/Component/String/Resources/bin/update-data.php +++ b/src/Symfony/Component/String/Resources/bin/update-data.php @@ -11,7 +11,7 @@ use Symfony\Component\String\Resources\WcswidthDataGenerator; -error_reporting(E_ALL); +error_reporting(\E_ALL); set_error_handler(static function (int $type, string $msg, string $file, int $line): void { throw new \ErrorException($msg, 0, $type, $file, $line); diff --git a/src/Symfony/Component/String/Tests/LazyStringTest.php b/src/Symfony/Component/String/Tests/LazyStringTest.php index a714537c98c6..f65f454b2bc7 100644 --- a/src/Symfony/Component/String/Tests/LazyStringTest.php +++ b/src/Symfony/Component/String/Tests/LazyStringTest.php @@ -105,7 +105,7 @@ public function testIsNotStringable() { $this->assertFalse(LazyString::isStringable(null)); $this->assertFalse(LazyString::isStringable([])); - $this->assertFalse(LazyString::isStringable(STDIN)); + $this->assertFalse(LazyString::isStringable(\STDIN)); $this->assertFalse(LazyString::isStringable(new \StdClass())); } } diff --git a/src/Symfony/Component/String/UnicodeString.php b/src/Symfony/Component/String/UnicodeString.php index 54df3c0397b2..81bf8ea56b60 100644 --- a/src/Symfony/Component/String/UnicodeString.php +++ b/src/Symfony/Component/String/UnicodeString.php @@ -74,7 +74,7 @@ public function chunk(int $length = 1): array $str = clone $this; $chunks = []; - foreach (preg_split($rx, $this->string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $chunk) { + foreach (preg_split($rx, $this->string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY) as $chunk) { $str->string = $chunk; $chunks[] = clone $str; } @@ -100,10 +100,10 @@ public function endsWith($suffix): bool } if ($this->ignoreCase) { - return 0 === mb_stripos(grapheme_extract($this->string, \strlen($suffix), GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix)), $suffix, 0, 'UTF-8'); + return 0 === mb_stripos(grapheme_extract($this->string, \strlen($suffix), \GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix)), $suffix, 0, 'UTF-8'); } - return $suffix === grapheme_extract($this->string, \strlen($suffix), GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix)); + return $suffix === grapheme_extract($this->string, \strlen($suffix), \GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix)); } public function equalsTo($string): bool @@ -143,7 +143,11 @@ public function indexOf($needle, int $offset = 0): ?int return null; } - $i = $this->ignoreCase ? grapheme_stripos($this->string, $needle, $offset) : grapheme_strpos($this->string, $needle, $offset); + try { + $i = $this->ignoreCase ? grapheme_stripos($this->string, $needle, $offset) : grapheme_strpos($this->string, $needle, $offset); + } catch (\ValueError $e) { + return null; + } return false === $i ? null : $i; } @@ -235,7 +239,7 @@ public function replace(string $from, string $to): AbstractString $result = ''; $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos'; - while (false !== $i = $indexOf($tail, $from)) { + while ('' !== $tail && false !== $i = $indexOf($tail, $from)) { $slice = grapheme_substr($tail, 0, $i); $result .= $slice.$to; $tail = substr($tail, \strlen($slice) + \strlen($from)); @@ -263,7 +267,11 @@ public function replaceMatches(string $fromRegexp, $to): AbstractString public function slice(int $start = 0, int $length = null): AbstractString { $str = clone $this; - $str->string = (string) grapheme_substr($this->string, $start, $length ?? PHP_INT_MAX); + try { + $str->string = (string) grapheme_substr($this->string, $start, $length ?? \PHP_INT_MAX); + } catch (\ValueError $e) { + $str->string = ''; + } return $str; } @@ -272,8 +280,8 @@ public function splice(string $replacement, int $start = 0, int $length = null): { $str = clone $this; $start = $start ? \strlen(grapheme_substr($this->string, 0, $start)) : 0; - $length = $length ? \strlen(grapheme_substr($this->string, $start, $length ?? PHP_INT_MAX)) : $length; - $str->string = substr_replace($this->string, $replacement, $start, $length ?? PHP_INT_MAX); + $length = $length ? \strlen(grapheme_substr($this->string, $start, $length ?? \PHP_INT_MAX)) : $length; + $str->string = substr_replace($this->string, $replacement, $start, $length ?? \PHP_INT_MAX); normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string); if (false === $str->string) { @@ -285,7 +293,7 @@ public function splice(string $replacement, int $start = 0, int $length = null): public function split(string $delimiter, int $limit = null, int $flags = null): array { - if (1 > $limit = $limit ?? PHP_INT_MAX) { + if (1 > $limit = $limit ?? \PHP_INT_MAX) { throw new InvalidArgumentException('Split limit must be a positive integer.'); } @@ -339,10 +347,10 @@ public function startsWith($prefix): bool } if ($this->ignoreCase) { - return 0 === mb_stripos(grapheme_extract($this->string, \strlen($prefix), GRAPHEME_EXTR_MAXBYTES), $prefix, 0, 'UTF-8'); + return 0 === mb_stripos(grapheme_extract($this->string, \strlen($prefix), \GRAPHEME_EXTR_MAXBYTES), $prefix, 0, 'UTF-8'); } - return $prefix === grapheme_extract($this->string, \strlen($prefix), GRAPHEME_EXTR_MAXBYTES); + return $prefix === grapheme_extract($this->string, \strlen($prefix), \GRAPHEME_EXTR_MAXBYTES); } public function __wakeup() diff --git a/src/Symfony/Component/Templating/Loader/FilesystemLoader.php b/src/Symfony/Component/Templating/Loader/FilesystemLoader.php index 66aa3ca77f7f..0a37d0693935 100644 --- a/src/Symfony/Component/Templating/Loader/FilesystemLoader.php +++ b/src/Symfony/Component/Templating/Loader/FilesystemLoader.php @@ -103,7 +103,7 @@ protected static function isAbsolutePath(string $file) && ':' == $file[1] && ('\\' == $file[2] || '/' == $file[2]) ) - || null !== parse_url($file, PHP_URL_SCHEME) + || null !== parse_url($file, \PHP_URL_SCHEME) ) { return true; } diff --git a/src/Symfony/Component/Templating/PhpEngine.php b/src/Symfony/Component/Templating/PhpEngine.php index 37d44ffda96c..ab6b7d30e303 100644 --- a/src/Symfony/Component/Templating/PhpEngine.php +++ b/src/Symfony/Component/Templating/PhpEngine.php @@ -138,7 +138,7 @@ protected function evaluate(Storage $template, array $parameters = []) // the view variable is exposed to the require file below $view = $this; if ($this->evalTemplate instanceof FileStorage) { - extract($this->evalParameters, EXTR_SKIP); + extract($this->evalParameters, \EXTR_SKIP); $this->evalParameters = null; ob_start(); @@ -148,7 +148,7 @@ protected function evaluate(Storage $template, array $parameters = []) return ob_get_clean(); } elseif ($this->evalTemplate instanceof StringStorage) { - extract($this->evalParameters, EXTR_SKIP); + extract($this->evalParameters, \EXTR_SKIP); $this->evalParameters = null; ob_start(); @@ -393,7 +393,7 @@ public function getGlobals() */ protected function initializeEscapers() { - $flags = ENT_QUOTES | ENT_SUBSTITUTE; + $flags = \ENT_QUOTES | \ENT_SUBSTITUTE; $this->escapers = [ 'html' => diff --git a/src/Symfony/Component/Translation/Command/XliffLintCommand.php b/src/Symfony/Component/Translation/Command/XliffLintCommand.php index 4376804296c7..dc2e9a9d936d 100644 --- a/src/Symfony/Component/Translation/Command/XliffLintCommand.php +++ b/src/Symfony/Component/Translation/Command/XliffLintCommand.php @@ -202,7 +202,7 @@ private function displayJson(SymfonyStyle $io, array $filesInfo) } }); - $io->writeln(json_encode($filesInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + $io->writeln(json_encode($filesInfo, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES)); return min($errors, 1); } diff --git a/src/Symfony/Component/Translation/Dumper/JsonFileDumper.php b/src/Symfony/Component/Translation/Dumper/JsonFileDumper.php index c6700ae153f1..34c0b5694293 100644 --- a/src/Symfony/Component/Translation/Dumper/JsonFileDumper.php +++ b/src/Symfony/Component/Translation/Dumper/JsonFileDumper.php @@ -25,7 +25,7 @@ class JsonFileDumper extends FileDumper */ public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []) { - $flags = $options['json_encoding'] ?? JSON_PRETTY_PRINT; + $flags = $options['json_encoding'] ?? \JSON_PRETTY_PRINT; return json_encode($messages->all($domain), $flags); } diff --git a/src/Symfony/Component/Translation/Extractor/PhpExtractor.php b/src/Symfony/Component/Translation/Extractor/PhpExtractor.php index 549754a506c0..f6b1a16ffdda 100644 --- a/src/Symfony/Component/Translation/Extractor/PhpExtractor.php +++ b/src/Symfony/Component/Translation/Extractor/PhpExtractor.php @@ -100,7 +100,7 @@ private function seekToNextRelevantToken(\Iterator $tokenIterator) { for (; $tokenIterator->valid(); $tokenIterator->next()) { $t = $tokenIterator->current(); - if (T_WHITESPACE !== $t[0]) { + if (\T_WHITESPACE !== $t[0]) { break; } } @@ -148,23 +148,23 @@ private function getValue(\Iterator $tokenIterator) } switch ($t[0]) { - case T_START_HEREDOC: + case \T_START_HEREDOC: $docToken = $t[1]; break; - case T_ENCAPSED_AND_WHITESPACE: - case T_CONSTANT_ENCAPSED_STRING: + case \T_ENCAPSED_AND_WHITESPACE: + case \T_CONSTANT_ENCAPSED_STRING: if ('' === $docToken) { $message .= PhpStringTokenParser::parse($t[1]); } else { $docPart = $t[1]; } break; - case T_END_HEREDOC: + case \T_END_HEREDOC: $message .= PhpStringTokenParser::parseDocString($docToken, $docPart); $docToken = ''; $docPart = ''; break; - case T_WHITESPACE: + case \T_WHITESPACE: break; default: break 2; @@ -232,7 +232,7 @@ protected function parseTokens(array $tokens, MessageCatalogue $catalog, string */ protected function canBeExtracted(string $file) { - return $this->isFile($file) && 'php' === pathinfo($file, PATHINFO_EXTENSION); + return $this->isFile($file) && 'php' === pathinfo($file, \PATHINFO_EXTENSION); } /** diff --git a/src/Symfony/Component/Translation/Loader/JsonFileLoader.php b/src/Symfony/Component/Translation/Loader/JsonFileLoader.php index 9f15dbc62889..8a8996b0d209 100644 --- a/src/Symfony/Component/Translation/Loader/JsonFileLoader.php +++ b/src/Symfony/Component/Translation/Loader/JsonFileLoader.php @@ -43,15 +43,15 @@ protected function loadResource($resource) private function getJSONErrorMessage(int $errorCode): string { switch ($errorCode) { - case JSON_ERROR_DEPTH: + case \JSON_ERROR_DEPTH: return 'Maximum stack depth exceeded'; - case JSON_ERROR_STATE_MISMATCH: + case \JSON_ERROR_STATE_MISMATCH: return 'Underflow or the modes mismatch'; - case JSON_ERROR_CTRL_CHAR: + case \JSON_ERROR_CTRL_CHAR: return 'Unexpected control character found'; - case JSON_ERROR_SYNTAX: + case \JSON_ERROR_SYNTAX: return 'Syntax error, malformed JSON'; - case JSON_ERROR_UTF8: + case \JSON_ERROR_UTF8: return 'Malformed UTF-8 characters, possibly incorrectly encoded'; default: return 'Unknown error'; diff --git a/src/Symfony/Component/Translation/Loader/PhpFileLoader.php b/src/Symfony/Component/Translation/Loader/PhpFileLoader.php index 0991c3d3a28c..c361d5293cc0 100644 --- a/src/Symfony/Component/Translation/Loader/PhpFileLoader.php +++ b/src/Symfony/Component/Translation/Loader/PhpFileLoader.php @@ -25,7 +25,7 @@ class PhpFileLoader extends FileLoader */ protected function loadResource($resource) { - if ([] === self::$cache && \function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) || filter_var(ini_get('opcache.enable_cli'), FILTER_VALIDATE_BOOLEAN))) { + if ([] === self::$cache && \function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) || filter_var(ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOLEAN))) { self::$cache = null; } diff --git a/src/Symfony/Component/Translation/Resources/bin/translation-status.php b/src/Symfony/Component/Translation/Resources/bin/translation-status.php index 44918c92ec52..e3e644963046 100644 --- a/src/Symfony/Component/Translation/Resources/bin/translation-status.php +++ b/src/Symfony/Component/Translation/Resources/bin/translation-status.php @@ -61,7 +61,7 @@ foreach ($config['original_files'] as $originalFilePath) { if (!file_exists($originalFilePath)) { - echo sprintf('The following file does not exist. Make sure that you execute this command at the root dir of the Symfony code repository.%s %s', PHP_EOL, $originalFilePath); + echo sprintf('The following file does not exist. Make sure that you execute this command at the root dir of the Symfony code repository.%s %s', \PHP_EOL, $originalFilePath); exit(1); } } @@ -89,7 +89,7 @@ function findTranslationFiles($originalFilePath, $localeToAnalyze) $originalFileName = basename($originalFilePath); $translationFileNamePattern = str_replace('.en.', '.*.', $originalFileName); - $translationFiles = glob($translationsDir.'/'.$translationFileNamePattern, GLOB_NOSORT); + $translationFiles = glob($translationsDir.'/'.$translationFileNamePattern, \GLOB_NOSORT); sort($translationFiles); foreach ($translationFiles as $filePath) { $locale = extractLocaleFromFilePath($filePath); @@ -127,7 +127,7 @@ function printTranslationStatus($originalFilePath, $translationStatus, $verboseO { printTitle($originalFilePath); printTable($translationStatus, $verboseOutput); - echo PHP_EOL.PHP_EOL; + echo \PHP_EOL.\PHP_EOL; } function extractLocaleFromFilePath($filePath) @@ -154,8 +154,8 @@ function extractTranslationKeys($filePath) function printTitle($title) { - echo $title.PHP_EOL; - echo str_repeat('=', strlen($title)).PHP_EOL.PHP_EOL; + echo $title.\PHP_EOL; + echo str_repeat('=', strlen($title)).\PHP_EOL.\PHP_EOL; } function printTable($translations, $verboseOutput) @@ -174,19 +174,19 @@ function printTable($translations, $verboseOutput) textColorGreen(); } - echo sprintf('| Locale: %-'.$longestLocaleNameLength.'s | Translated: %d/%d', $locale, $translation['translated'], $translation['total']).PHP_EOL; + echo sprintf('| Locale: %-'.$longestLocaleNameLength.'s | Translated: %d/%d', $locale, $translation['translated'], $translation['total']).\PHP_EOL; textColorNormal(); if (true === $verboseOutput && count($translation['missingKeys']) > 0) { - echo str_repeat('-', 80).PHP_EOL; - echo '| Missing Translations:'.PHP_EOL; + echo str_repeat('-', 80).\PHP_EOL; + echo '| Missing Translations:'.\PHP_EOL; foreach ($translation['missingKeys'] as $id => $content) { - echo sprintf('| (id=%s) %s', $id, $content).PHP_EOL; + echo sprintf('| (id=%s) %s', $id, $content).\PHP_EOL; } - echo str_repeat('-', 80).PHP_EOL; + echo str_repeat('-', 80).\PHP_EOL; } } } diff --git a/src/Symfony/Component/Translation/Tests/Dumper/JsonFileDumperTest.php b/src/Symfony/Component/Translation/Tests/Dumper/JsonFileDumperTest.php index 04e3d86bec4c..e353f85d990a 100644 --- a/src/Symfony/Component/Translation/Tests/Dumper/JsonFileDumperTest.php +++ b/src/Symfony/Component/Translation/Tests/Dumper/JsonFileDumperTest.php @@ -34,6 +34,6 @@ public function testDumpWithCustomEncoding() $dumper = new JsonFileDumper(); - $this->assertStringEqualsFile(__DIR__.'/../fixtures/resources.dump.json', $dumper->formatCatalogue($catalogue, 'messages', ['json_encoding' => JSON_HEX_QUOT])); + $this->assertStringEqualsFile(__DIR__.'/../fixtures/resources.dump.json', $dumper->formatCatalogue($catalogue, 'messages', ['json_encoding' => \JSON_HEX_QUOT])); } } diff --git a/src/Symfony/Component/Translation/Tests/Formatter/IntlFormatterTest.php b/src/Symfony/Component/Translation/Tests/Formatter/IntlFormatterTest.php index 37d982cf295f..b904c8fc7621 100644 --- a/src/Symfony/Component/Translation/Tests/Formatter/IntlFormatterTest.php +++ b/src/Symfony/Component/Translation/Tests/Formatter/IntlFormatterTest.php @@ -36,7 +36,7 @@ public function testInvalidFormat() public function testFormatWithNamedArguments() { - if (version_compare(INTL_ICU_VERSION, '4.8', '<')) { + if (version_compare(\INTL_ICU_VERSION, '4.8', '<')) { $this->markTestSkipped('Format with named arguments can only be run with ICU 4.8 or higher and PHP >= 5.5'); } diff --git a/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php index b3d77474a1f4..28c91229b0dc 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php @@ -49,7 +49,7 @@ public function testLoadWithInternalErrorsEnabled() public function testLoadWithExternalEntitiesDisabled() { - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { $disableEntities = libxml_disable_entity_loader(true); } @@ -57,7 +57,7 @@ public function testLoadWithExternalEntitiesDisabled() $resource = __DIR__.'/../fixtures/resources.xlf'; $catalogue = $loader->load($resource, 'en', 'domain1'); - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { libxml_disable_entity_loader($disableEntities); } diff --git a/src/Symfony/Component/Translation/Tests/TranslatorTest.php b/src/Symfony/Component/Translation/Tests/TranslatorTest.php index 72a4f9055a37..ed1bb9dba583 100644 --- a/src/Symfony/Component/Translation/Tests/TranslatorTest.php +++ b/src/Symfony/Component/Translation/Tests/TranslatorTest.php @@ -19,6 +19,19 @@ class TranslatorTest extends TestCase { + private $defaultLocale; + + protected function setUp(): void + { + $this->defaultLocale = \Locale::getDefault(); + \Locale::setDefault('en'); + } + + protected function tearDown(): void + { + \Locale::setDefault($this->defaultLocale); + } + /** * @dataProvider getInvalidLocalesTests */ diff --git a/src/Symfony/Component/Translation/Translator.php b/src/Symfony/Component/Translation/Translator.php index c92abf1383f2..4ef5321b9d4a 100644 --- a/src/Symfony/Component/Translation/Translator.php +++ b/src/Symfony/Component/Translation/Translator.php @@ -150,7 +150,7 @@ public function addResource(string $format, $resource, string $locale, string $d public function setLocale(string $locale) { $this->assertValidLocale($locale); - $this->locale = $locale; + $this->locale = $locale ?? (class_exists(\Locale::class) ? \Locale::getDefault() : 'en'); } /** diff --git a/src/Symfony/Component/Translation/Util/XliffUtils.php b/src/Symfony/Component/Translation/Util/XliffUtils.php index 072b2671cb6b..a8c05c2244d4 100644 --- a/src/Symfony/Component/Translation/Util/XliffUtils.php +++ b/src/Symfony/Component/Translation/Util/XliffUtils.php @@ -61,20 +61,20 @@ public static function validateSchema(\DOMDocument $dom): array { $xliffVersion = static::getVersionNumber($dom); $internalErrors = libxml_use_internal_errors(true); - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { $disableEntities = libxml_disable_entity_loader(false); } $isValid = @$dom->schemaValidateSource(self::getSchema($xliffVersion)); if (!$isValid) { - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { libxml_disable_entity_loader($disableEntities); } return self::getXmlErrors($internalErrors); } - if (LIBXML_VERSION < 20900) { + if (\LIBXML_VERSION < 20900) { libxml_disable_entity_loader($disableEntities); } @@ -92,7 +92,7 @@ public static function getErrorsAsString(array $xmlErrors): string foreach ($xmlErrors as $error) { $errorsAsString .= sprintf("[%s %s] %s (in %s - line %d, column %d)\n", - LIBXML_ERR_WARNING === $error['level'] ? 'WARNING' : 'ERROR', + \LIBXML_ERR_WARNING === $error['level'] ? 'WARNING' : 'ERROR', $error['code'], $error['message'], $error['file'], @@ -152,7 +152,7 @@ private static function getXmlErrors(bool $internalErrors): array $errors = []; foreach (libxml_get_errors() as $error) { $errors[] = [ - 'level' => LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR', + 'level' => \LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR', 'code' => $error->code, 'message' => trim($error->message), 'file' => $error->file ?: 'n/a', diff --git a/src/Symfony/Component/Uid/BinaryUtil.php b/src/Symfony/Component/Uid/BinaryUtil.php index 3418d59ee185..082346cd155f 100644 --- a/src/Symfony/Component/Uid/BinaryUtil.php +++ b/src/Symfony/Component/Uid/BinaryUtil.php @@ -120,7 +120,7 @@ public static function timeToFloat(string $time): float return (hexdec($time) - self::TIME_OFFSET_INT) / 10000000; } - $time = str_pad(hex2bin($time), 8, "\0", STR_PAD_LEFT); + $time = str_pad(hex2bin($time), 8, "\0", \STR_PAD_LEFT); $time = self::add($time, self::TIME_OFFSET_COM); $time[0] = $time[0] & "\x7F"; diff --git a/src/Symfony/Component/Uid/NilUuid.php b/src/Symfony/Component/Uid/NilUuid.php index c3b5db16d4b1..b5ff73a47619 100644 --- a/src/Symfony/Component/Uid/NilUuid.php +++ b/src/Symfony/Component/Uid/NilUuid.php @@ -18,7 +18,7 @@ */ class NilUuid extends Uuid { - protected const TYPE = UUID_TYPE_NULL; + protected const TYPE = \UUID_TYPE_NULL; public function __construct() { diff --git a/src/Symfony/Component/Uid/Uuid.php b/src/Symfony/Component/Uid/Uuid.php index 1fe335e4bb78..2719d20b1bf9 100644 --- a/src/Symfony/Component/Uid/Uuid.php +++ b/src/Symfony/Component/Uid/Uuid.php @@ -18,13 +18,13 @@ */ class Uuid extends AbstractUid { - protected const TYPE = UUID_TYPE_DEFAULT; + protected const TYPE = \UUID_TYPE_DEFAULT; public function __construct(string $uuid) { $type = uuid_type($uuid); - if (false === $type || UUID_TYPE_INVALID === $type || (static::TYPE ?: $type) !== $type) { + if (false === $type || \UUID_TYPE_INVALID === $type || (static::TYPE ?: $type) !== $type) { throw new \InvalidArgumentException(sprintf('Invalid UUID%s: "%s".', static::TYPE ? 'v'.static::TYPE : '', $uuid)); } diff --git a/src/Symfony/Component/Uid/UuidV1.php b/src/Symfony/Component/Uid/UuidV1.php index 12ed39a6ff0f..5f2d7e6a8aec 100644 --- a/src/Symfony/Component/Uid/UuidV1.php +++ b/src/Symfony/Component/Uid/UuidV1.php @@ -20,7 +20,7 @@ */ class UuidV1 extends Uuid { - protected const TYPE = UUID_TYPE_TIME; + protected const TYPE = \UUID_TYPE_TIME; public function __construct(string $uuid = null) { diff --git a/src/Symfony/Component/Uid/UuidV3.php b/src/Symfony/Component/Uid/UuidV3.php index cfdf3e48fc01..d5d0d8fe86a4 100644 --- a/src/Symfony/Component/Uid/UuidV3.php +++ b/src/Symfony/Component/Uid/UuidV3.php @@ -22,5 +22,5 @@ */ class UuidV3 extends Uuid { - protected const TYPE = UUID_TYPE_MD5; + protected const TYPE = \UUID_TYPE_MD5; } diff --git a/src/Symfony/Component/Uid/UuidV4.php b/src/Symfony/Component/Uid/UuidV4.php index 97ed1acf7898..d338f1eb0c57 100644 --- a/src/Symfony/Component/Uid/UuidV4.php +++ b/src/Symfony/Component/Uid/UuidV4.php @@ -20,7 +20,7 @@ */ class UuidV4 extends Uuid { - protected const TYPE = UUID_TYPE_RANDOM; + protected const TYPE = \UUID_TYPE_RANDOM; public function __construct(string $uuid = null) { diff --git a/src/Symfony/Component/Uid/UuidV5.php b/src/Symfony/Component/Uid/UuidV5.php index a36f2c94c26f..59a6a2082c64 100644 --- a/src/Symfony/Component/Uid/UuidV5.php +++ b/src/Symfony/Component/Uid/UuidV5.php @@ -22,5 +22,5 @@ */ class UuidV5 extends Uuid { - protected const TYPE = UUID_TYPE_SHA1; + protected const TYPE = \UUID_TYPE_SHA1; } diff --git a/src/Symfony/Component/Uid/UuidV6.php b/src/Symfony/Component/Uid/UuidV6.php index 2d30d8820d29..9d0ca9fdc0d1 100644 --- a/src/Symfony/Component/Uid/UuidV6.php +++ b/src/Symfony/Component/Uid/UuidV6.php @@ -25,7 +25,7 @@ class UuidV6 extends Uuid public function __construct(string $uuid = null) { if (null === $uuid) { - $uuid = uuid_create(UUID_TYPE_TIME); + $uuid = uuid_create(\UUID_TYPE_TIME); $this->uid = substr($uuid, 15, 3).substr($uuid, 9, 4).$uuid[0].'-'.substr($uuid, 1, 4).'-6'.substr($uuid, 5, 3).substr($uuid, 18); } else { parent::__construct($uuid); diff --git a/src/Symfony/Component/Validator/Constraints/DateTimeValidator.php b/src/Symfony/Component/Validator/Constraints/DateTimeValidator.php index d76193aade92..77894ebbab57 100644 --- a/src/Symfony/Component/Validator/Constraints/DateTimeValidator.php +++ b/src/Symfony/Component/Validator/Constraints/DateTimeValidator.php @@ -53,6 +53,12 @@ public function validate($value, Constraint $constraint) return; } + if ('+' === substr($constraint->format, -1)) { + $errors['warnings'] = array_filter($errors['warnings'], function ($warning) { + return 'Trailing data' !== $warning; + }); + } + foreach ($errors['warnings'] as $warning) { if ('The parsed date was invalid' === $warning) { $this->context->buildViolation($constraint->message) diff --git a/src/Symfony/Component/Validator/Constraints/FileValidator.php b/src/Symfony/Component/Validator/Constraints/FileValidator.php index 31218c2020fa..3c946ff96ce8 100644 --- a/src/Symfony/Component/Validator/Constraints/FileValidator.php +++ b/src/Symfony/Component/Validator/Constraints/FileValidator.php @@ -53,7 +53,7 @@ public function validate($value, Constraint $constraint) if ($value instanceof UploadedFile && !$value->isValid()) { switch ($value->getError()) { - case UPLOAD_ERR_INI_SIZE: + case \UPLOAD_ERR_INI_SIZE: $iniLimitSize = UploadedFile::getMaxFilesize(); if ($constraint->maxSize && $constraint->maxSize < $iniLimitSize) { $limitInBytes = $constraint->maxSize; @@ -67,43 +67,43 @@ public function validate($value, Constraint $constraint) $this->context->buildViolation($constraint->uploadIniSizeErrorMessage) ->setParameter('{{ limit }}', $limitAsString) ->setParameter('{{ suffix }}', $suffix) - ->setCode((string) UPLOAD_ERR_INI_SIZE) + ->setCode((string) \UPLOAD_ERR_INI_SIZE) ->addViolation(); return; - case UPLOAD_ERR_FORM_SIZE: + case \UPLOAD_ERR_FORM_SIZE: $this->context->buildViolation($constraint->uploadFormSizeErrorMessage) - ->setCode((string) UPLOAD_ERR_FORM_SIZE) + ->setCode((string) \UPLOAD_ERR_FORM_SIZE) ->addViolation(); return; - case UPLOAD_ERR_PARTIAL: + case \UPLOAD_ERR_PARTIAL: $this->context->buildViolation($constraint->uploadPartialErrorMessage) - ->setCode((string) UPLOAD_ERR_PARTIAL) + ->setCode((string) \UPLOAD_ERR_PARTIAL) ->addViolation(); return; - case UPLOAD_ERR_NO_FILE: + case \UPLOAD_ERR_NO_FILE: $this->context->buildViolation($constraint->uploadNoFileErrorMessage) - ->setCode((string) UPLOAD_ERR_NO_FILE) + ->setCode((string) \UPLOAD_ERR_NO_FILE) ->addViolation(); return; - case UPLOAD_ERR_NO_TMP_DIR: + case \UPLOAD_ERR_NO_TMP_DIR: $this->context->buildViolation($constraint->uploadNoTmpDirErrorMessage) - ->setCode((string) UPLOAD_ERR_NO_TMP_DIR) + ->setCode((string) \UPLOAD_ERR_NO_TMP_DIR) ->addViolation(); return; - case UPLOAD_ERR_CANT_WRITE: + case \UPLOAD_ERR_CANT_WRITE: $this->context->buildViolation($constraint->uploadCantWriteErrorMessage) - ->setCode((string) UPLOAD_ERR_CANT_WRITE) + ->setCode((string) \UPLOAD_ERR_CANT_WRITE) ->addViolation(); return; - case UPLOAD_ERR_EXTENSION: + case \UPLOAD_ERR_EXTENSION: $this->context->buildViolation($constraint->uploadExtensionErrorMessage) - ->setCode((string) UPLOAD_ERR_EXTENSION) + ->setCode((string) \UPLOAD_ERR_EXTENSION) ->addViolation(); return; diff --git a/src/Symfony/Component/Validator/Constraints/HostnameValidator.php b/src/Symfony/Component/Validator/Constraints/HostnameValidator.php index c9af0977e9e5..144d57e37ddc 100644 --- a/src/Symfony/Component/Validator/Constraints/HostnameValidator.php +++ b/src/Symfony/Component/Validator/Constraints/HostnameValidator.php @@ -59,7 +59,7 @@ public function validate($value, Constraint $constraint) private function isValid(string $domain): bool { - return false !== filter_var($domain, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME); + return false !== filter_var($domain, \FILTER_VALIDATE_DOMAIN, \FILTER_FLAG_HOSTNAME); } private function hasValidTld(string $domain): bool diff --git a/src/Symfony/Component/Validator/Constraints/IpValidator.php b/src/Symfony/Component/Validator/Constraints/IpValidator.php index f965a31d4b9c..11d3f52cd3f6 100644 --- a/src/Symfony/Component/Validator/Constraints/IpValidator.php +++ b/src/Symfony/Component/Validator/Constraints/IpValidator.php @@ -49,47 +49,47 @@ public function validate($value, Constraint $constraint) switch ($constraint->version) { case Ip::V4: - $flag = FILTER_FLAG_IPV4; + $flag = \FILTER_FLAG_IPV4; break; case Ip::V6: - $flag = FILTER_FLAG_IPV6; + $flag = \FILTER_FLAG_IPV6; break; case Ip::V4_NO_PRIV: - $flag = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE; + $flag = \FILTER_FLAG_IPV4 | \FILTER_FLAG_NO_PRIV_RANGE; break; case Ip::V6_NO_PRIV: - $flag = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE; + $flag = \FILTER_FLAG_IPV6 | \FILTER_FLAG_NO_PRIV_RANGE; break; case Ip::ALL_NO_PRIV: - $flag = FILTER_FLAG_NO_PRIV_RANGE; + $flag = \FILTER_FLAG_NO_PRIV_RANGE; break; case Ip::V4_NO_RES: - $flag = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_RES_RANGE; + $flag = \FILTER_FLAG_IPV4 | \FILTER_FLAG_NO_RES_RANGE; break; case Ip::V6_NO_RES: - $flag = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_RES_RANGE; + $flag = \FILTER_FLAG_IPV6 | \FILTER_FLAG_NO_RES_RANGE; break; case Ip::ALL_NO_RES: - $flag = FILTER_FLAG_NO_RES_RANGE; + $flag = \FILTER_FLAG_NO_RES_RANGE; break; case Ip::V4_ONLY_PUBLIC: - $flag = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE; + $flag = \FILTER_FLAG_IPV4 | \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE; break; case Ip::V6_ONLY_PUBLIC: - $flag = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE; + $flag = \FILTER_FLAG_IPV6 | \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE; break; case Ip::ALL_ONLY_PUBLIC: - $flag = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE; + $flag = \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE; break; default: @@ -97,7 +97,7 @@ public function validate($value, Constraint $constraint) break; } - if (!filter_var($value, FILTER_VALIDATE_IP, $flag)) { + if (!filter_var($value, \FILTER_VALIDATE_IP, $flag)) { $this->context->buildViolation($constraint->message) ->setParameter('{{ value }}', $this->formatValue($value)) ->setCode(Ip::INVALID_IP_ERROR) diff --git a/src/Symfony/Component/Validator/Constraints/JsonValidator.php b/src/Symfony/Component/Validator/Constraints/JsonValidator.php index 850bbfbcbf90..e553ae359b14 100644 --- a/src/Symfony/Component/Validator/Constraints/JsonValidator.php +++ b/src/Symfony/Component/Validator/Constraints/JsonValidator.php @@ -41,7 +41,7 @@ public function validate($value, Constraint $constraint) json_decode($value); - if (JSON_ERROR_NONE !== json_last_error()) { + if (\JSON_ERROR_NONE !== json_last_error()) { $this->context->buildViolation($constraint->message) ->setParameter('{{ value }}', $this->formatValue($value)) ->setCode(Json::INVALID_JSON_ERROR) diff --git a/src/Symfony/Component/Validator/Constraints/TimezoneValidator.php b/src/Symfony/Component/Validator/Constraints/TimezoneValidator.php index cf52239d0c24..ab6b4eed626a 100644 --- a/src/Symfony/Component/Validator/Constraints/TimezoneValidator.php +++ b/src/Symfony/Component/Validator/Constraints/TimezoneValidator.php @@ -78,7 +78,11 @@ public function validate($value, Constraint $constraint) private static function getPhpTimezones(int $zone, string $countryCode = null): array { if (null !== $countryCode) { - return @\DateTimeZone::listIdentifiers($zone, $countryCode) ?: []; + try { + return @\DateTimeZone::listIdentifiers($zone, $countryCode) ?: []; + } catch (\ValueError $e) { + return []; + } } return \DateTimeZone::listIdentifiers($zone); diff --git a/src/Symfony/Component/Validator/Resources/translations/validators.ar.xlf b/src/Symfony/Component/Validator/Resources/translations/validators.ar.xlf index 46a649848072..fa87a3753de6 100644 --- a/src/Symfony/Component/Validator/Resources/translations/validators.ar.xlf +++ b/src/Symfony/Component/Validator/Resources/translations/validators.ar.xlf @@ -382,6 +382,10 @@ Each element of this collection should satisfy its own set of constraints. يجب أن يفي كل عنصر من عناصر هذه المجموعة بمجموعة القيود الخاصة به. + + This value is not a valid International Securities Identification Number (ISIN). + صالح (ISIN) هذه القيمة ليست رقم تعريف الأوراق المالية الدولي. + diff --git a/src/Symfony/Component/Validator/Resources/translations/validators.bs.xlf b/src/Symfony/Component/Validator/Resources/translations/validators.bs.xlf new file mode 100644 index 000000000000..b17eae9ab85d --- /dev/null +++ b/src/Symfony/Component/Validator/Resources/translations/validators.bs.xlf @@ -0,0 +1,391 @@ + + + + + + This value should be false. + Ova vrijednost bi trebalo da bude "netačno" (false). + + + This value should be true. + Ova vrijednost bi trebalo da bude "tačno" (true). + + + This value should be of type {{ type }}. + Ova vrijednost bi trebalo da bude tipa {{ type }}. + + + This value should be blank. + Ova vrijednost bi trebalo da bude prazna. + + + The value you selected is not a valid choice. + Odabrana vrijednost nije validan izbor. + + + You must select at least {{ limit }} choice.|You must select at least {{ limit }} choices. + Morate odabrati barem {{ limit }} mogućnost.|Morate odabrati barem {{ limit }} mogućnosti.|Morate odabrati barem {{ limit }} mogućnosti. + + + You must select at most {{ limit }} choice.|You must select at most {{ limit }} choices. + Morate odabrati najviše {{ limit }} mogućnost.|Morate odabrati najviše {{ limit }} mogućnosti.|Morate odabrati najviše {{ limit }} mogućnosti. + + + One or more of the given values is invalid. + Jedna ili više datih vrijednosti nisu validne. + + + This field was not expected. + Ovo polje nije očekivano. + + + This field is missing. + Ovo polje nedostaje. + + + This value is not a valid date. + Ova vrijednost nije ispravan datum. + + + This value is not a valid datetime. + Ova vrijednost nije ispravnog datum-vrijeme (datetime) formata. + + + This value is not a valid email address. + Ova vrijednost nije ispravna e-mail adresa. + + + The file could not be found. + Ova datoteka ne može biti pronađena. + + + The file is not readable. + Ova datoteka nije čitljiva. + + + The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}. + Ova datoteka je prevelika ({{ size }} {{ suffix }}). Najveća dozvoljena veličina je {{ limit }} {{ suffix }}. + + + The mime type of the file is invalid ({{ type }}). Allowed mime types are {{ types }}. + Mime tip datoteke nije ispravan ({{ type }}). Dozvoljeni mime tipovi su {{ types }}. + + + This value should be {{ limit }} or less. + Ova vrijednost bi trebalo da bude {{ limit }} ili manje. + + + This value is too long. It should have {{ limit }} character or less.|This value is too long. It should have {{ limit }} characters or less. + Ova vrijednost je predugačka. Trebalo bi da ima {{ limit }} karakter ili manje.|Ova vrijednost je predugačka. Trebalo bi da ima {{ limit }} karaktera ili manje.|Ova vrijednost je predugačka. Trebalo bi da ima {{ limit }} karaktera ili manje. + + + This value should be {{ limit }} or more. + Ova vrijednost bi trebalo da bude {{ limit }} ili više. + + + This value is too short. It should have {{ limit }} character or more.|This value is too short. It should have {{ limit }} characters or more. + Ova vrijednost je prekratka. Trebalo bi da ima {{ limit }} karakter ili više.|Ova vrijednost je prekratka. Trebalo bi da ima {{ limit }} karaktera ili više.|Ova vrijednost je prekratka. Trebalo bi da ima {{ limit }} karaktera ili više. + + + This value should not be blank. + Ova vrijednost ne bi trebalo da bude prazna. + + + This value should not be null. + Ova vrijednost ne bi trebalo da bude null. + + + This value should be null. + Ova vrijednost bi trebalo da bude null. + + + This value is not valid. + Ova vrijednost nije ispravna. + + + This value is not a valid time. + Ova vrijednost nije ispravno vrijeme. + + + This value is not a valid URL. + Ova vrijednost nije ispravan URL. + + + The two values should be equal. + Obje vrijednosti bi trebalo da budu jednake. + + + The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}. + Ova datoteka je prevelika. Najveća dozvoljena veličina je {{ limit }} {{ suffix }}. + + + The file is too large. + Ova datoteka je prevelika. + + + The file could not be uploaded. + Ova datoteka ne može biti prenijeta (uploaded). + + + This value should be a valid number. + Ova vrijednost bi trebalo da bude ispravan broj. + + + This file is not a valid image. + Ova datoteka nije validna slika. + + + This is not a valid IP address. + Ovo nije ispravna IP adresa. + + + This value is not a valid language. + Ova vrijednost nije validan jezik. + + + This value is not a valid locale. + Ova vrijednost nije validna regionalna oznaka. + + + This value is not a valid country. + Ova vrijednost nije validna država. + + + This value is already used. + Ova vrijednost je već upotrebljena. + + + The size of the image could not be detected. + Nije moguće otkriti veličinu ove slike. + + + The image width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px. + Širina slike je prevelika ({{ width }}px). Najveća dozvoljena širina je {{ max_width }}px. + + + The image width is too small ({{ width }}px). Minimum width expected is {{ min_width }}px. + Širina slike je premala ({{ width }}px). Najmanja dozvoljena širina je {{ min_width }}px. + + + The image height is too big ({{ height }}px). Allowed maximum height is {{ max_height }}px. + Dužina slike je prevelika ({{ height }}px). Najveća dozvoljena dužina je {{ max_height }}px. + + + The image height is too small ({{ height }}px). Minimum height expected is {{ min_height }}px. + Dužina slike je premala ({{ height }}px). Najmanja dozvoljena dužina je {{ min_height }}px. + + + This value should be the user's current password. + Ova vrijednost bi trebalo da bude trenutna korisnička lozinka. + + + This value should have exactly {{ limit }} character.|This value should have exactly {{ limit }} characters. + Ova vrijednost bi trebalo da ima tačno {{ limit }} karakter.|Ova vrijednost bi trebalo da ima tačno {{ limit }} karaktera. + + + The file was only partially uploaded. + Datoteka je samo djelimično prenijeta (uploaded). + + + No file was uploaded. + Nijedna datoteka nije prenijeta (uploaded). + + + No temporary folder was configured in php.ini. + Privremeni direktorijum nije konfigurisan u datoteci php.ini. + + + Cannot write temporary file to disk. + Privremenu datoteku nije moguće upisati na disk. + + + A PHP extension caused the upload to fail. + Prenos datoteke nije uspio zbog PHP ekstenzije. + + + This collection should contain {{ limit }} element or more.|This collection should contain {{ limit }} elements or more. + Ova kolekcija bi trebalo da sadrži {{ limit }} ili više elemenata.|Ova kolekcija bi trebalo da sadrži {{ limit }} ili više elemenata.|Ova kolekcija bi trebalo da sadrži {{ limit }} ili više elemenata. + + + This collection should contain {{ limit }} element or less.|This collection should contain {{ limit }} elements or less. + Ova kolekcija bi trebalo da sadrži {{ limit }} ili manje elemenata.|Ova kolekcija bi trebalo da sadrži {{ limit }} ili manje elemenata.|Ova kolekcija bi trebalo da sadrži {{ limit }} ili manje elemenata. + + + This collection should contain exactly {{ limit }} element.|This collection should contain exactly {{ limit }} elements. + Ova kolekcija bi trebalo da sadrži tačno {{ limit }} element.|Ova kolekcija bi trebalo da sadrži tačno {{ limit }} elementa.|Ova kolekcija bi trebalo da sadrži tačno {{ limit }} elemenata. + + + Invalid card number. + Broj kartice je neispravan. + + + Unsupported card type or invalid card number. + Tip kartice nije podržan ili je broj kartice neispravan. + + + This is not a valid International Bank Account Number (IBAN). + Ova vrijednost nije ispravan međunarodni broj bankovnog računa (IBAN). + + + This value is not a valid ISBN-10. + Ova vrijednost nije ispravan ISBN-10. + + + This value is not a valid ISBN-13. + Ova vrijednost nije ispravan ISBN-13. + + + This value is neither a valid ISBN-10 nor a valid ISBN-13. + Ova vrijednost nije ispravan ISBN-10 niti ISBN-13. + + + This value is not a valid ISSN. + Ova vrijednost nije ispravan ISSN. + + + This value is not a valid currency. + Ova vrijednost nije ispravna valuta. + + + This value should be equal to {{ compared_value }}. + Ova vrijednost bi trebalo da bude jednaka {{ compared_value }}. + + + This value should be greater than {{ compared_value }}. + Ova vrijednost bi trebalo da bude veća od {{ compared_value }}. + + + This value should be greater than or equal to {{ compared_value }}. + Ova vrijednost bi trebalo da bude jednaka ili veća od {{ compared_value }}. + + + This value should be identical to {{ compared_value_type }} {{ compared_value }}. + Ova vrijednost bi trebalo da bude identična {{ compared_value_type }} {{ compared_value }}. + + + This value should be less than {{ compared_value }}. + Ova vrijednost bi trebalo da bude manja od {{ compared_value }}. + + + This value should be less than or equal to {{ compared_value }}. + Ova vrijednost bi trebalo da bude jednaka ili manja od {{ compared_value }}. + + + This value should not be equal to {{ compared_value }}. + Ova vrijednost bi trebalo da bude različita od {{ compared_value }}. + + + This value should not be identical to {{ compared_value_type }} {{ compared_value }}. + Ova vrijednost bi trebalo da bude identična sa {{ compared_value_type }} {{ compared_value }}. + + + The image ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}. + Razmjera ove slike je prevelika ({{ ratio }}). Maksimalna dozvoljena razmjera je {{ max_ratio }}. + + + The image ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}. + Razmjera ove slike je premala ({{ ratio }}). Minimalna očekivana razmjera je {{ min_ratio }}. + + + The image is square ({{ width }}x{{ height }}px). Square images are not allowed. + Ova slika je kvadratnog oblika ({{ width }}x{{ height }}px). Kvadratne slike nisu dozvoljene. + + + The image is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented images are not allowed. + Ova slika je orijentisana horizontalno (landscape) ({{ width }}x{{ height }}px). Horizontalno orijentisane slike nisu dozvoljene. + + + The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed. + Ova slika je orijentisana vertikalno (portrait) ({{ width }}x{{ height }}px). Vertikalno orijentisane slike nisu dozvoljene. + + + An empty file is not allowed. + Prazna datoteka nije dozvoljena. + + + The host could not be resolved. + Nije moguće odrediti poslužitelja (host). + + + This value does not match the expected {{ charset }} charset. + Ova vrijednost ne odgovara očekivanom {{ charset }} setu karaktera (charset). + + + This is not a valid Business Identifier Code (BIC). + Ovo nije validan poslovni identifikacioni kod (BIC). + + + Error + Greška + + + This is not a valid UUID. + Ovo nije validan UUID. + + + This value should be a multiple of {{ compared_value }}. + Ova vrijednost bi trebalo da bude djeljiva sa {{ compared_value }}. + + + This Business Identifier Code (BIC) is not associated with IBAN {{ iban }}. + Ovaj poslovni identifikacioni kod (BIC) nije povezan sa IBAN-om {{ iban }}. + + + This value should be valid JSON. + Ova vrijednost bi trebalo da bude validan JSON. + + + This collection should contain only unique elements. + Ova kolekcija bi trebala da sadrži samo jedinstvene elemente. + + + This value should be positive. + Ova vrijednost bi trebalo da bude pozitivna. + + + This value should be either positive or zero. + Ova vrijednost bi trebalo da bude pozitivna ili jednaka nuli. + + + This value should be negative. + Ova vrijednost bi trebalo da bude negativna. + + + This value should be either negative or zero. + Ova vrijednost bi trebalo da bude negativna ili jednaka nuli. + + + This value is not a valid timezone. + Ova vrijednost nije validna vremenska zona. + + + This password has been leaked in a data breach, it must not be used. Please use another password. + Ova lozinka je procurila u nekom od slučajeva kompromitovanja podataka, nemojte je koristiti. Koristite drugu lozinku. + + + This value should be between {{ min }} and {{ max }}. + Ova vrijednosti bi trebala biti između {{ min }} i {{ max }}. + + + This value is not a valid hostname. + Ova vrijednost nije ispravno ime poslužitelja (hostname). + + + The number of elements in this collection should be a multiple of {{ compared_value }}. + Broj elemenata u ovoj kolekciji bi trebalo da bude djeljiv sa {{ compared_value }}. + + + This value should satisfy at least one of the following constraints: + Ova vrijednost bi trebalo da zadovoljava namjanje jedno od narednih ograničenja: + + + Each element of this collection should satisfy its own set of constraints. + Svaki element ove kolekcije bi trebalo da zadovolji sopstveni skup ograničenja. + + + This value is not a valid International Securities Identification Number (ISIN). + Ova vrijednost nije ispravna međunarodna identifikaciona oznaka hartija od vrijednosti (ISIN). + + + + diff --git a/src/Symfony/Component/Validator/Resources/translations/validators.sr_Cyrl.xlf b/src/Symfony/Component/Validator/Resources/translations/validators.sr_Cyrl.xlf index 3f2b9eaba8e3..fce95a0769ff 100644 --- a/src/Symfony/Component/Validator/Resources/translations/validators.sr_Cyrl.xlf +++ b/src/Symfony/Component/Validator/Resources/translations/validators.sr_Cyrl.xlf @@ -366,6 +366,26 @@ This value should be between {{ min }} and {{ max }}. Ова вредност треба да буде између {{ min }} и {{ max }}. + + This value is not a valid hostname. + Ова вредност није исправно име послужитеља (hostname). + + + The number of elements in this collection should be a multiple of {{ compared_value }}. + Број елемената у овој колекцији би требало да буде дељив са {{ compared_value }}. + + + This value should satisfy at least one of the following constraints: + Ова вредност би требало да задовољава најмање једно од наредних ограничења: + + + Each element of this collection should satisfy its own set of constraints. + Сваки елемент ове колекције би требало да задовољи сопствени скуп ограничења. + + + This value is not a valid International Securities Identification Number (ISIN). + Ова вредност није исправна међународна идентификациона ознака хартија од вредности (ISIN). + diff --git a/src/Symfony/Component/Validator/Resources/translations/validators.sr_Latn.xlf b/src/Symfony/Component/Validator/Resources/translations/validators.sr_Latn.xlf index 43d2070ab781..06b164be8a1f 100644 --- a/src/Symfony/Component/Validator/Resources/translations/validators.sr_Latn.xlf +++ b/src/Symfony/Component/Validator/Resources/translations/validators.sr_Latn.xlf @@ -366,6 +366,26 @@ This value should be between {{ min }} and {{ max }}. Ova vrednost treba da bude između {{ min }} i {{ max }}. + + This value is not a valid hostname. + Ova vrednost nije ispravno ime poslužitelja (hostname). + + + The number of elements in this collection should be a multiple of {{ compared_value }}. + Broj elemenata u ovoj kolekciji bi trebalo da bude deljiv sa {{ compared_value }}. + + + This value should satisfy at least one of the following constraints: + Ova vrednost bi trebalo da zadovoljava namjanje jedno od narednih ograničenja: + + + Each element of this collection should satisfy its own set of constraints. + Svaki element ove kolekcije bi trebalo da zadovolji sopstveni skup ograničenja. + + + This value is not a valid International Securities Identification Number (ISIN). + Ova vrednost nije ispravna međunarodna identifikaciona oznaka hartija od vrednosti (ISIN). + diff --git a/src/Symfony/Component/Validator/Resources/translations/validators.tr.xlf b/src/Symfony/Component/Validator/Resources/translations/validators.tr.xlf index a23c652b176e..76de2214e6bc 100644 --- a/src/Symfony/Component/Validator/Resources/translations/validators.tr.xlf +++ b/src/Symfony/Component/Validator/Resources/translations/validators.tr.xlf @@ -84,7 +84,7 @@ This value is too short. It should have {{ limit }} character or more.|This value is too short. It should have {{ limit }} characters or more. - Bu değer çok kısa. {{ limit }} karakter veya daha fazla olmaldır. + Bu değer çok kısa. {{ limit }} karakter veya daha fazla olmalıdır. This value should not be blank. diff --git a/src/Symfony/Component/Validator/Test/ConstraintValidatorTestCase.php b/src/Symfony/Component/Validator/Test/ConstraintValidatorTestCase.php index 6ac799c7a824..cce35db0dd0b 100644 --- a/src/Symfony/Component/Validator/Test/ConstraintValidatorTestCase.php +++ b/src/Symfony/Component/Validator/Test/ConstraintValidatorTestCase.php @@ -24,6 +24,7 @@ use Symfony\Component\Validator\ConstraintValidatorInterface; use Symfony\Component\Validator\ConstraintViolation; use Symfony\Component\Validator\ConstraintViolationInterface; +use Symfony\Component\Validator\ConstraintViolationList; use Symfony\Component\Validator\Context\ExecutionContext; use Symfony\Component\Validator\Context\ExecutionContextInterface; use Symfony\Component\Validator\Mapping\ClassMetadata; @@ -56,6 +57,8 @@ abstract class ConstraintValidatorTestCase extends TestCase protected $propertyPath; protected $constraint; protected $defaultTimezone; + private $expectedViolations; + private $call; protected function setUp(): void { @@ -74,6 +77,9 @@ protected function setUp(): void $this->validator = $this->createValidator(); $this->validator->initialize($this->context); + $this->expectedViolations = []; + $this->call = 0; + \Locale::setDefault('en'); $this->setDefaultTimezone('UTC'); @@ -107,16 +113,56 @@ protected function createContext() $translator = $this->getMockBuilder(TranslatorInterface::class)->getMock(); $translator->expects($this->any())->method('trans')->willReturnArgument(0); $validator = $this->getMockBuilder('Symfony\Component\Validator\Validator\ValidatorInterface')->getMock(); + $validator->expects($this->any()) + ->method('validate') + ->willReturnCallback(function () { + return $this->expectedViolations[$this->call++] ?? new ConstraintViolationList(); + }); $context = new ExecutionContext($validator, $this->root, $translator); $context->setGroup($this->group); $context->setNode($this->value, $this->object, $this->metadata, $this->propertyPath); $context->setConstraint($this->constraint); + $contextualValidator = $this->getMockBuilder(AssertingContextualValidator::class) + ->setConstructorArgs([$context]) + ->setMethods([ + 'atPath', + 'validate', + 'validateProperty', + 'validatePropertyValue', + 'getViolations', + ]) + ->getMock(); + $contextualValidator->expects($this->any()) + ->method('atPath') + ->willReturnCallback(function ($path) use ($contextualValidator) { + return $contextualValidator->doAtPath($path); + }); + $contextualValidator->expects($this->any()) + ->method('validate') + ->willReturnCallback(function ($value, $constraints = null, $groups = null) use ($contextualValidator) { + return $contextualValidator->doValidate($value, $constraints, $groups); + }); + $contextualValidator->expects($this->any()) + ->method('validateProperty') + ->willReturnCallback(function ($object, $propertyName, $groups = null) use ($contextualValidator) { + return $contextualValidator->validateProperty($object, $propertyName, $groups); + }); + $contextualValidator->expects($this->any()) + ->method('validatePropertyValue') + ->willReturnCallback(function ($objectOrClass, $propertyName, $value, $groups = null) use ($contextualValidator) { + return $contextualValidator->doValidatePropertyValue($objectOrClass, $propertyName, $value, $groups); + }); + $contextualValidator->expects($this->any()) + ->method('getViolations') + ->willReturnCallback(function () use ($contextualValidator) { + return $contextualValidator->doGetViolations(); + }); $validator->expects($this->any()) ->method('inContext') ->with($context) - ->willReturn($this->getMockBuilder(AssertingContextualValidator::class)->setConstructorArgs([$context])->setMethods(null)->getMock()); + ->willReturn($contextualValidator); return $context; } @@ -225,11 +271,7 @@ protected function expectViolationsAt($i, $value, Constraint $constraint) $validator->initialize($context); $validator->validate($value, $constraint); - $this->context->getValidator() - ->expects($this->at($i)) - ->method('validate') - ->willReturn($context->getViolations()) - ; + $this->expectedViolations[] = $context->getViolations(); return $context->getViolations(); } @@ -403,6 +445,10 @@ public function __construct(ExecutionContextInterface $context) } public function atPath($path) + { + } + + public function doAtPath($path) { Assert::assertFalse($this->expectNoValidate, 'No validation calls have been expected.'); @@ -416,6 +462,10 @@ public function atPath($path) } public function validate($value, $constraints = null, $groups = null) + { + } + + public function doValidate($value, $constraints = null, $groups = null) { Assert::assertFalse($this->expectNoValidate, 'No validation calls have been expected.'); @@ -437,16 +487,28 @@ public function validate($value, $constraints = null, $groups = null) } public function validateProperty($object, $propertyName, $groups = null) + { + } + + public function doValidateProperty($object, $propertyName, $groups = null) { return $this; } public function validatePropertyValue($objectOrClass, $propertyName, $value, $groups = null) + { + } + + public function doValidatePropertyValue($objectOrClass, $propertyName, $value, $groups = null) { return $this; } public function getViolations() + { + } + + public function doGetViolations() { return $this->context->getViolations(); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php index cad1fd782843..ceb3738d2836 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php @@ -114,4 +114,12 @@ public function getInvalidDateTimes() ['Y-m-d H:i:s', '2010-01-01 00:00:60', DateTime::INVALID_TIME_ERROR], ]; } + + public function testDateTimeWithTrailingData() + { + $this->validator->validate('1995-05-10 00:00:00', new DateTime([ + 'format' => 'Y-m-d+', + ])); + $this->assertNoViolation(); + } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/DivisibleByValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/DivisibleByValidatorTest.php index 623ac4c192c3..7612ada32b53 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/DivisibleByValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/DivisibleByValidatorTest.php @@ -72,7 +72,7 @@ public function provideInvalidComparisons(): array [1, '1', 2, '2', 'int'], [10, '10', 3, '3', 'int'], [10, '10', 0, '0', 'int'], - [42, '42', INF, 'INF', 'float'], + [42, '42', \INF, 'INF', 'float'], [4.15, '4.15', 0.1, '0.1', 'float'], ['22', '"22"', '10', '"10"', 'string'], ]; diff --git a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php index 0bbac3c6b70a..f517baea8736 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php @@ -159,7 +159,7 @@ public function provideMaxSizeExceededTests() */ public function testMaxSizeExceeded($bytesWritten, $limit, $sizeAsString, $limitAsString, $suffix) { - fseek($this->file, $bytesWritten - 1, SEEK_SET); + fseek($this->file, $bytesWritten - 1, \SEEK_SET); fwrite($this->file, '0'); fclose($this->file); @@ -208,7 +208,7 @@ public function provideMaxSizeNotExceededTests() */ public function testMaxSizeNotExceeded($bytesWritten, $limit) { - fseek($this->file, $bytesWritten - 1, SEEK_SET); + fseek($this->file, $bytesWritten - 1, \SEEK_SET); fwrite($this->file, '0'); fclose($this->file); @@ -259,7 +259,7 @@ public function provideBinaryFormatTests() */ public function testBinaryFormat($bytesWritten, $limit, $binaryFormat, $sizeAsString, $limitAsString, $suffix) { - fseek($this->file, $bytesWritten - 1, SEEK_SET); + fseek($this->file, $bytesWritten - 1, \SEEK_SET); fwrite($this->file, '0'); fclose($this->file); @@ -431,23 +431,23 @@ public function testUploadedFileError($error, $message, array $params = [], $max public function uploadedFileErrorProvider() { $tests = [ - [(string) UPLOAD_ERR_FORM_SIZE, 'uploadFormSizeErrorMessage'], - [(string) UPLOAD_ERR_PARTIAL, 'uploadPartialErrorMessage'], - [(string) UPLOAD_ERR_NO_FILE, 'uploadNoFileErrorMessage'], - [(string) UPLOAD_ERR_NO_TMP_DIR, 'uploadNoTmpDirErrorMessage'], - [(string) UPLOAD_ERR_CANT_WRITE, 'uploadCantWriteErrorMessage'], - [(string) UPLOAD_ERR_EXTENSION, 'uploadExtensionErrorMessage'], + [(string) \UPLOAD_ERR_FORM_SIZE, 'uploadFormSizeErrorMessage'], + [(string) \UPLOAD_ERR_PARTIAL, 'uploadPartialErrorMessage'], + [(string) \UPLOAD_ERR_NO_FILE, 'uploadNoFileErrorMessage'], + [(string) \UPLOAD_ERR_NO_TMP_DIR, 'uploadNoTmpDirErrorMessage'], + [(string) \UPLOAD_ERR_CANT_WRITE, 'uploadCantWriteErrorMessage'], + [(string) \UPLOAD_ERR_EXTENSION, 'uploadExtensionErrorMessage'], ]; if (class_exists('Symfony\Component\HttpFoundation\File\UploadedFile')) { // when no maxSize is specified on constraint, it should use the ini value - $tests[] = [(string) UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', [ + $tests[] = [(string) \UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', [ '{{ limit }}' => UploadedFile::getMaxFilesize() / 1048576, '{{ suffix }}' => 'MiB', ]]; // it should use the smaller limitation (maxSize option in this case) - $tests[] = [(string) UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', [ + $tests[] = [(string) \UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', [ '{{ limit }}' => 1, '{{ suffix }}' => 'bytes', ], '1']; @@ -460,14 +460,14 @@ public function uploadedFileErrorProvider() // it correctly parses the maxSize option and not only uses simple string comparison // 1000M should be bigger than the ini value - $tests[] = [(string) UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', [ + $tests[] = [(string) \UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', [ '{{ limit }}' => $limit, '{{ suffix }}' => $suffix, ], '1000M']; // it correctly parses the maxSize option and not only uses simple string comparison // 1000M should be bigger than the ini value - $tests[] = [(string) UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', [ + $tests[] = [(string) \UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', [ '{{ limit }}' => '0.1', '{{ suffix }}' => 'MB', ], '100K']; diff --git a/src/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.php index f81868b5b825..57033884d7a8 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.php @@ -132,7 +132,7 @@ public function testLoadClassMetadataWithConstants() $loader->loadClassMetadata($metadata); $expected = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity'); - $expected->addPropertyConstraint('firstName', new Range(['max' => PHP_INT_MAX])); + $expected->addPropertyConstraint('firstName', new Range(['max' => \PHP_INT_MAX])); $this->assertEquals($expected, $metadata); } diff --git a/src/Symfony/Component/Validator/Validator/TraceableValidator.php b/src/Symfony/Component/Validator/Validator/TraceableValidator.php index be7daf48c853..74a922fa4e1e 100644 --- a/src/Symfony/Component/Validator/Validator/TraceableValidator.php +++ b/src/Symfony/Component/Validator/Validator/TraceableValidator.php @@ -65,7 +65,7 @@ public function validate($value, $constraints = null, $groups = null) { $violations = $this->validator->validate($value, $constraints, $groups); - $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 7); + $trace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 7); $file = $trace[0]['file']; $line = $trace[0]['line']; diff --git a/src/Symfony/Component/Validator/composer.json b/src/Symfony/Component/Validator/composer.json index 28838de19986..d9b12beaeb6a 100644 --- a/src/Symfony/Component/Validator/composer.json +++ b/src/Symfony/Component/Validator/composer.json @@ -34,7 +34,7 @@ "symfony/expression-language": "^5.1", "symfony/cache": "^4.4|^5.0", "symfony/mime": "^4.4|^5.0", - "symfony/phpunit-bridge": "^5.1", + "symfony/phpunit-bridge": "^5.1.1", "symfony/property-access": "^4.4|^5.0", "symfony/property-info": "^4.4|^5.0", "symfony/translation": "^4.4|^5.0", diff --git a/src/Symfony/Component/VarDumper/Caster/AmqpCaster.php b/src/Symfony/Component/VarDumper/Caster/AmqpCaster.php index 883d02b4e69f..daa0d4f798b8 100644 --- a/src/Symfony/Component/VarDumper/Caster/AmqpCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/AmqpCaster.php @@ -23,27 +23,27 @@ class AmqpCaster { private static $flags = [ - AMQP_DURABLE => 'AMQP_DURABLE', - AMQP_PASSIVE => 'AMQP_PASSIVE', - AMQP_EXCLUSIVE => 'AMQP_EXCLUSIVE', - AMQP_AUTODELETE => 'AMQP_AUTODELETE', - AMQP_INTERNAL => 'AMQP_INTERNAL', - AMQP_NOLOCAL => 'AMQP_NOLOCAL', - AMQP_AUTOACK => 'AMQP_AUTOACK', - AMQP_IFEMPTY => 'AMQP_IFEMPTY', - AMQP_IFUNUSED => 'AMQP_IFUNUSED', - AMQP_MANDATORY => 'AMQP_MANDATORY', - AMQP_IMMEDIATE => 'AMQP_IMMEDIATE', - AMQP_MULTIPLE => 'AMQP_MULTIPLE', - AMQP_NOWAIT => 'AMQP_NOWAIT', - AMQP_REQUEUE => 'AMQP_REQUEUE', + \AMQP_DURABLE => 'AMQP_DURABLE', + \AMQP_PASSIVE => 'AMQP_PASSIVE', + \AMQP_EXCLUSIVE => 'AMQP_EXCLUSIVE', + \AMQP_AUTODELETE => 'AMQP_AUTODELETE', + \AMQP_INTERNAL => 'AMQP_INTERNAL', + \AMQP_NOLOCAL => 'AMQP_NOLOCAL', + \AMQP_AUTOACK => 'AMQP_AUTOACK', + \AMQP_IFEMPTY => 'AMQP_IFEMPTY', + \AMQP_IFUNUSED => 'AMQP_IFUNUSED', + \AMQP_MANDATORY => 'AMQP_MANDATORY', + \AMQP_IMMEDIATE => 'AMQP_IMMEDIATE', + \AMQP_MULTIPLE => 'AMQP_MULTIPLE', + \AMQP_NOWAIT => 'AMQP_NOWAIT', + \AMQP_REQUEUE => 'AMQP_REQUEUE', ]; private static $exchangeTypes = [ - AMQP_EX_TYPE_DIRECT => 'AMQP_EX_TYPE_DIRECT', - AMQP_EX_TYPE_FANOUT => 'AMQP_EX_TYPE_FANOUT', - AMQP_EX_TYPE_TOPIC => 'AMQP_EX_TYPE_TOPIC', - AMQP_EX_TYPE_HEADERS => 'AMQP_EX_TYPE_HEADERS', + \AMQP_EX_TYPE_DIRECT => 'AMQP_EX_TYPE_DIRECT', + \AMQP_EX_TYPE_FANOUT => 'AMQP_EX_TYPE_FANOUT', + \AMQP_EX_TYPE_TOPIC => 'AMQP_EX_TYPE_TOPIC', + \AMQP_EX_TYPE_HEADERS => 'AMQP_EX_TYPE_HEADERS', ]; public static function castConnection(\AMQPConnection $c, array $a, Stub $stub, bool $isNested) diff --git a/src/Symfony/Component/VarDumper/Caster/DOMCaster.php b/src/Symfony/Component/VarDumper/Caster/DOMCaster.php index 98359ff41f9a..499aca1f56c7 100644 --- a/src/Symfony/Component/VarDumper/Caster/DOMCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/DOMCaster.php @@ -23,44 +23,44 @@ class DOMCaster { private static $errorCodes = [ - DOM_PHP_ERR => 'DOM_PHP_ERR', - DOM_INDEX_SIZE_ERR => 'DOM_INDEX_SIZE_ERR', - DOMSTRING_SIZE_ERR => 'DOMSTRING_SIZE_ERR', - DOM_HIERARCHY_REQUEST_ERR => 'DOM_HIERARCHY_REQUEST_ERR', - DOM_WRONG_DOCUMENT_ERR => 'DOM_WRONG_DOCUMENT_ERR', - DOM_INVALID_CHARACTER_ERR => 'DOM_INVALID_CHARACTER_ERR', - DOM_NO_DATA_ALLOWED_ERR => 'DOM_NO_DATA_ALLOWED_ERR', - DOM_NO_MODIFICATION_ALLOWED_ERR => 'DOM_NO_MODIFICATION_ALLOWED_ERR', - DOM_NOT_FOUND_ERR => 'DOM_NOT_FOUND_ERR', - DOM_NOT_SUPPORTED_ERR => 'DOM_NOT_SUPPORTED_ERR', - DOM_INUSE_ATTRIBUTE_ERR => 'DOM_INUSE_ATTRIBUTE_ERR', - DOM_INVALID_STATE_ERR => 'DOM_INVALID_STATE_ERR', - DOM_SYNTAX_ERR => 'DOM_SYNTAX_ERR', - DOM_INVALID_MODIFICATION_ERR => 'DOM_INVALID_MODIFICATION_ERR', - DOM_NAMESPACE_ERR => 'DOM_NAMESPACE_ERR', - DOM_INVALID_ACCESS_ERR => 'DOM_INVALID_ACCESS_ERR', - DOM_VALIDATION_ERR => 'DOM_VALIDATION_ERR', + \DOM_PHP_ERR => 'DOM_PHP_ERR', + \DOM_INDEX_SIZE_ERR => 'DOM_INDEX_SIZE_ERR', + \DOMSTRING_SIZE_ERR => 'DOMSTRING_SIZE_ERR', + \DOM_HIERARCHY_REQUEST_ERR => 'DOM_HIERARCHY_REQUEST_ERR', + \DOM_WRONG_DOCUMENT_ERR => 'DOM_WRONG_DOCUMENT_ERR', + \DOM_INVALID_CHARACTER_ERR => 'DOM_INVALID_CHARACTER_ERR', + \DOM_NO_DATA_ALLOWED_ERR => 'DOM_NO_DATA_ALLOWED_ERR', + \DOM_NO_MODIFICATION_ALLOWED_ERR => 'DOM_NO_MODIFICATION_ALLOWED_ERR', + \DOM_NOT_FOUND_ERR => 'DOM_NOT_FOUND_ERR', + \DOM_NOT_SUPPORTED_ERR => 'DOM_NOT_SUPPORTED_ERR', + \DOM_INUSE_ATTRIBUTE_ERR => 'DOM_INUSE_ATTRIBUTE_ERR', + \DOM_INVALID_STATE_ERR => 'DOM_INVALID_STATE_ERR', + \DOM_SYNTAX_ERR => 'DOM_SYNTAX_ERR', + \DOM_INVALID_MODIFICATION_ERR => 'DOM_INVALID_MODIFICATION_ERR', + \DOM_NAMESPACE_ERR => 'DOM_NAMESPACE_ERR', + \DOM_INVALID_ACCESS_ERR => 'DOM_INVALID_ACCESS_ERR', + \DOM_VALIDATION_ERR => 'DOM_VALIDATION_ERR', ]; private static $nodeTypes = [ - XML_ELEMENT_NODE => 'XML_ELEMENT_NODE', - XML_ATTRIBUTE_NODE => 'XML_ATTRIBUTE_NODE', - XML_TEXT_NODE => 'XML_TEXT_NODE', - XML_CDATA_SECTION_NODE => 'XML_CDATA_SECTION_NODE', - XML_ENTITY_REF_NODE => 'XML_ENTITY_REF_NODE', - XML_ENTITY_NODE => 'XML_ENTITY_NODE', - XML_PI_NODE => 'XML_PI_NODE', - XML_COMMENT_NODE => 'XML_COMMENT_NODE', - XML_DOCUMENT_NODE => 'XML_DOCUMENT_NODE', - XML_DOCUMENT_TYPE_NODE => 'XML_DOCUMENT_TYPE_NODE', - XML_DOCUMENT_FRAG_NODE => 'XML_DOCUMENT_FRAG_NODE', - XML_NOTATION_NODE => 'XML_NOTATION_NODE', - XML_HTML_DOCUMENT_NODE => 'XML_HTML_DOCUMENT_NODE', - XML_DTD_NODE => 'XML_DTD_NODE', - XML_ELEMENT_DECL_NODE => 'XML_ELEMENT_DECL_NODE', - XML_ATTRIBUTE_DECL_NODE => 'XML_ATTRIBUTE_DECL_NODE', - XML_ENTITY_DECL_NODE => 'XML_ENTITY_DECL_NODE', - XML_NAMESPACE_DECL_NODE => 'XML_NAMESPACE_DECL_NODE', + \XML_ELEMENT_NODE => 'XML_ELEMENT_NODE', + \XML_ATTRIBUTE_NODE => 'XML_ATTRIBUTE_NODE', + \XML_TEXT_NODE => 'XML_TEXT_NODE', + \XML_CDATA_SECTION_NODE => 'XML_CDATA_SECTION_NODE', + \XML_ENTITY_REF_NODE => 'XML_ENTITY_REF_NODE', + \XML_ENTITY_NODE => 'XML_ENTITY_NODE', + \XML_PI_NODE => 'XML_PI_NODE', + \XML_COMMENT_NODE => 'XML_COMMENT_NODE', + \XML_DOCUMENT_NODE => 'XML_DOCUMENT_NODE', + \XML_DOCUMENT_TYPE_NODE => 'XML_DOCUMENT_TYPE_NODE', + \XML_DOCUMENT_FRAG_NODE => 'XML_DOCUMENT_FRAG_NODE', + \XML_NOTATION_NODE => 'XML_NOTATION_NODE', + \XML_HTML_DOCUMENT_NODE => 'XML_HTML_DOCUMENT_NODE', + \XML_DTD_NODE => 'XML_DTD_NODE', + \XML_ELEMENT_DECL_NODE => 'XML_ELEMENT_DECL_NODE', + \XML_ATTRIBUTE_DECL_NODE => 'XML_ATTRIBUTE_DECL_NODE', + \XML_ENTITY_DECL_NODE => 'XML_ENTITY_DECL_NODE', + \XML_NAMESPACE_DECL_NODE => 'XML_NAMESPACE_DECL_NODE', ]; public static function castException(\DOMException $e, array $a, Stub $stub, bool $isNested) diff --git a/src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php b/src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php index c2eb6be4338f..8f7227682462 100644 --- a/src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php @@ -27,21 +27,21 @@ class ExceptionCaster public static $srcContext = 1; public static $traceArgs = true; public static $errorTypes = [ - E_DEPRECATED => 'E_DEPRECATED', - E_USER_DEPRECATED => 'E_USER_DEPRECATED', - E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', - E_ERROR => 'E_ERROR', - E_WARNING => 'E_WARNING', - E_PARSE => 'E_PARSE', - E_NOTICE => 'E_NOTICE', - E_CORE_ERROR => 'E_CORE_ERROR', - E_CORE_WARNING => 'E_CORE_WARNING', - E_COMPILE_ERROR => 'E_COMPILE_ERROR', - E_COMPILE_WARNING => 'E_COMPILE_WARNING', - E_USER_ERROR => 'E_USER_ERROR', - E_USER_WARNING => 'E_USER_WARNING', - E_USER_NOTICE => 'E_USER_NOTICE', - E_STRICT => 'E_STRICT', + \E_DEPRECATED => 'E_DEPRECATED', + \E_USER_DEPRECATED => 'E_USER_DEPRECATED', + \E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', + \E_ERROR => 'E_ERROR', + \E_WARNING => 'E_WARNING', + \E_PARSE => 'E_PARSE', + \E_NOTICE => 'E_NOTICE', + \E_CORE_ERROR => 'E_CORE_ERROR', + \E_CORE_WARNING => 'E_CORE_WARNING', + \E_COMPILE_ERROR => 'E_COMPILE_ERROR', + \E_COMPILE_WARNING => 'E_COMPILE_WARNING', + \E_USER_ERROR => 'E_USER_ERROR', + \E_USER_WARNING => 'E_USER_WARNING', + \E_USER_NOTICE => 'E_USER_NOTICE', + \E_STRICT => 'E_STRICT', ]; private static $framesCache = []; diff --git a/src/Symfony/Component/VarDumper/Caster/PgSqlCaster.php b/src/Symfony/Component/VarDumper/Caster/PgSqlCaster.php index f9f3c6f78cc1..c153cf9fd6a4 100644 --- a/src/Symfony/Component/VarDumper/Caster/PgSqlCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/PgSqlCaster.php @@ -36,37 +36,37 @@ class PgSqlCaster ]; private static $transactionStatus = [ - PGSQL_TRANSACTION_IDLE => 'PGSQL_TRANSACTION_IDLE', - PGSQL_TRANSACTION_ACTIVE => 'PGSQL_TRANSACTION_ACTIVE', - PGSQL_TRANSACTION_INTRANS => 'PGSQL_TRANSACTION_INTRANS', - PGSQL_TRANSACTION_INERROR => 'PGSQL_TRANSACTION_INERROR', - PGSQL_TRANSACTION_UNKNOWN => 'PGSQL_TRANSACTION_UNKNOWN', + \PGSQL_TRANSACTION_IDLE => 'PGSQL_TRANSACTION_IDLE', + \PGSQL_TRANSACTION_ACTIVE => 'PGSQL_TRANSACTION_ACTIVE', + \PGSQL_TRANSACTION_INTRANS => 'PGSQL_TRANSACTION_INTRANS', + \PGSQL_TRANSACTION_INERROR => 'PGSQL_TRANSACTION_INERROR', + \PGSQL_TRANSACTION_UNKNOWN => 'PGSQL_TRANSACTION_UNKNOWN', ]; private static $resultStatus = [ - PGSQL_EMPTY_QUERY => 'PGSQL_EMPTY_QUERY', - PGSQL_COMMAND_OK => 'PGSQL_COMMAND_OK', - PGSQL_TUPLES_OK => 'PGSQL_TUPLES_OK', - PGSQL_COPY_OUT => 'PGSQL_COPY_OUT', - PGSQL_COPY_IN => 'PGSQL_COPY_IN', - PGSQL_BAD_RESPONSE => 'PGSQL_BAD_RESPONSE', - PGSQL_NONFATAL_ERROR => 'PGSQL_NONFATAL_ERROR', - PGSQL_FATAL_ERROR => 'PGSQL_FATAL_ERROR', + \PGSQL_EMPTY_QUERY => 'PGSQL_EMPTY_QUERY', + \PGSQL_COMMAND_OK => 'PGSQL_COMMAND_OK', + \PGSQL_TUPLES_OK => 'PGSQL_TUPLES_OK', + \PGSQL_COPY_OUT => 'PGSQL_COPY_OUT', + \PGSQL_COPY_IN => 'PGSQL_COPY_IN', + \PGSQL_BAD_RESPONSE => 'PGSQL_BAD_RESPONSE', + \PGSQL_NONFATAL_ERROR => 'PGSQL_NONFATAL_ERROR', + \PGSQL_FATAL_ERROR => 'PGSQL_FATAL_ERROR', ]; private static $diagCodes = [ - 'severity' => PGSQL_DIAG_SEVERITY, - 'sqlstate' => PGSQL_DIAG_SQLSTATE, - 'message' => PGSQL_DIAG_MESSAGE_PRIMARY, - 'detail' => PGSQL_DIAG_MESSAGE_DETAIL, - 'hint' => PGSQL_DIAG_MESSAGE_HINT, - 'statement position' => PGSQL_DIAG_STATEMENT_POSITION, - 'internal position' => PGSQL_DIAG_INTERNAL_POSITION, - 'internal query' => PGSQL_DIAG_INTERNAL_QUERY, - 'context' => PGSQL_DIAG_CONTEXT, - 'file' => PGSQL_DIAG_SOURCE_FILE, - 'line' => PGSQL_DIAG_SOURCE_LINE, - 'function' => PGSQL_DIAG_SOURCE_FUNCTION, + 'severity' => \PGSQL_DIAG_SEVERITY, + 'sqlstate' => \PGSQL_DIAG_SQLSTATE, + 'message' => \PGSQL_DIAG_MESSAGE_PRIMARY, + 'detail' => \PGSQL_DIAG_MESSAGE_DETAIL, + 'hint' => \PGSQL_DIAG_MESSAGE_HINT, + 'statement position' => \PGSQL_DIAG_STATEMENT_POSITION, + 'internal position' => \PGSQL_DIAG_INTERNAL_POSITION, + 'internal query' => \PGSQL_DIAG_INTERNAL_QUERY, + 'context' => \PGSQL_DIAG_CONTEXT, + 'file' => \PGSQL_DIAG_SOURCE_FILE, + 'line' => \PGSQL_DIAG_SOURCE_LINE, + 'function' => \PGSQL_DIAG_SOURCE_FUNCTION, ]; public static function castLargeObject($lo, array $a, Stub $stub, bool $isNested) @@ -79,7 +79,7 @@ public static function castLargeObject($lo, array $a, Stub $stub, bool $isNested public static function castLink($link, array $a, Stub $stub, bool $isNested) { $a['status'] = pg_connection_status($link); - $a['status'] = new ConstStub(PGSQL_CONNECTION_OK === $a['status'] ? 'PGSQL_CONNECTION_OK' : 'PGSQL_CONNECTION_BAD', $a['status']); + $a['status'] = new ConstStub(\PGSQL_CONNECTION_OK === $a['status'] ? 'PGSQL_CONNECTION_OK' : 'PGSQL_CONNECTION_BAD', $a['status']); $a['busy'] = pg_connection_busy($link); $a['transaction'] = pg_transaction_status($link); @@ -115,7 +115,7 @@ public static function castResult($result, array $a, Stub $stub, bool $isNested) if (isset(self::$resultStatus[$a['status']])) { $a['status'] = new ConstStub(self::$resultStatus[$a['status']], $a['status']); } - $a['command-completion tag'] = pg_result_status($result, PGSQL_STATUS_STRING); + $a['command-completion tag'] = pg_result_status($result, \PGSQL_STATUS_STRING); if (-1 === $a['num rows']) { foreach (self::$diagCodes as $k => $v) { diff --git a/src/Symfony/Component/VarDumper/Caster/ReflectionCaster.php b/src/Symfony/Component/VarDumper/Caster/ReflectionCaster.php index 470229b5b588..d9b43ae730dc 100644 --- a/src/Symfony/Component/VarDumper/Caster/ReflectionCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/ReflectionCaster.php @@ -120,7 +120,7 @@ public static function castReflectionGenerator(\ReflectionGenerator $c, array $a 'file' => $c->getExecutingFile(), 'line' => $c->getExecutingLine(), ]; - if ($trace = $c->getTrace(DEBUG_BACKTRACE_IGNORE_ARGS)) { + if ($trace = $c->getTrace(\DEBUG_BACKTRACE_IGNORE_ARGS)) { $function = new \ReflectionGenerator($c->getExecutingGenerator()); array_unshift($trace, [ 'function' => 'yield', diff --git a/src/Symfony/Component/VarDumper/Caster/SplCaster.php b/src/Symfony/Component/VarDumper/Caster/SplCaster.php index ae11252dba91..49cca4fd0c05 100644 --- a/src/Symfony/Component/VarDumper/Caster/SplCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/SplCaster.php @@ -94,10 +94,32 @@ public static function castFileInfo(\SplFileInfo $c, array $a, Stub $stub, bool unset($a["\0SplFileInfo\0fileName"]); unset($a["\0SplFileInfo\0pathName"]); - if (false === $c->getPathname()) { - $a[$prefix.'⚠'] = 'The parent constructor was not called: the object is in an invalid state'; + if (\PHP_VERSION_ID < 80000) { + if (false === $c->getPathname()) { + $a[$prefix.'⚠'] = 'The parent constructor was not called: the object is in an invalid state'; - return $a; + return $a; + } + } else { + try { + $c->isReadable(); + } catch (\RuntimeException $e) { + if ('Object not initialized' !== $e->getMessage()) { + throw $e; + } + + $a[$prefix.'⚠'] = 'The parent constructor was not called: the object is in an invalid state'; + + return $a; + } catch (\Error $e) { + if ('Object not initialized' !== $e->getMessage()) { + throw $e; + } + + $a[$prefix.'⚠'] = 'The parent constructor was not called: the object is in an invalid state'; + + return $a; + } } foreach ($map as $key => $accessor) { diff --git a/src/Symfony/Component/VarDumper/Caster/XmlResourceCaster.php b/src/Symfony/Component/VarDumper/Caster/XmlResourceCaster.php index edece30b6e34..42b25696fe49 100644 --- a/src/Symfony/Component/VarDumper/Caster/XmlResourceCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/XmlResourceCaster.php @@ -23,28 +23,28 @@ class XmlResourceCaster { private static $xmlErrors = [ - XML_ERROR_NONE => 'XML_ERROR_NONE', - XML_ERROR_NO_MEMORY => 'XML_ERROR_NO_MEMORY', - XML_ERROR_SYNTAX => 'XML_ERROR_SYNTAX', - XML_ERROR_NO_ELEMENTS => 'XML_ERROR_NO_ELEMENTS', - XML_ERROR_INVALID_TOKEN => 'XML_ERROR_INVALID_TOKEN', - XML_ERROR_UNCLOSED_TOKEN => 'XML_ERROR_UNCLOSED_TOKEN', - XML_ERROR_PARTIAL_CHAR => 'XML_ERROR_PARTIAL_CHAR', - XML_ERROR_TAG_MISMATCH => 'XML_ERROR_TAG_MISMATCH', - XML_ERROR_DUPLICATE_ATTRIBUTE => 'XML_ERROR_DUPLICATE_ATTRIBUTE', - XML_ERROR_JUNK_AFTER_DOC_ELEMENT => 'XML_ERROR_JUNK_AFTER_DOC_ELEMENT', - XML_ERROR_PARAM_ENTITY_REF => 'XML_ERROR_PARAM_ENTITY_REF', - XML_ERROR_UNDEFINED_ENTITY => 'XML_ERROR_UNDEFINED_ENTITY', - XML_ERROR_RECURSIVE_ENTITY_REF => 'XML_ERROR_RECURSIVE_ENTITY_REF', - XML_ERROR_ASYNC_ENTITY => 'XML_ERROR_ASYNC_ENTITY', - XML_ERROR_BAD_CHAR_REF => 'XML_ERROR_BAD_CHAR_REF', - XML_ERROR_BINARY_ENTITY_REF => 'XML_ERROR_BINARY_ENTITY_REF', - XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF => 'XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF', - XML_ERROR_MISPLACED_XML_PI => 'XML_ERROR_MISPLACED_XML_PI', - XML_ERROR_UNKNOWN_ENCODING => 'XML_ERROR_UNKNOWN_ENCODING', - XML_ERROR_INCORRECT_ENCODING => 'XML_ERROR_INCORRECT_ENCODING', - XML_ERROR_UNCLOSED_CDATA_SECTION => 'XML_ERROR_UNCLOSED_CDATA_SECTION', - XML_ERROR_EXTERNAL_ENTITY_HANDLING => 'XML_ERROR_EXTERNAL_ENTITY_HANDLING', + \XML_ERROR_NONE => 'XML_ERROR_NONE', + \XML_ERROR_NO_MEMORY => 'XML_ERROR_NO_MEMORY', + \XML_ERROR_SYNTAX => 'XML_ERROR_SYNTAX', + \XML_ERROR_NO_ELEMENTS => 'XML_ERROR_NO_ELEMENTS', + \XML_ERROR_INVALID_TOKEN => 'XML_ERROR_INVALID_TOKEN', + \XML_ERROR_UNCLOSED_TOKEN => 'XML_ERROR_UNCLOSED_TOKEN', + \XML_ERROR_PARTIAL_CHAR => 'XML_ERROR_PARTIAL_CHAR', + \XML_ERROR_TAG_MISMATCH => 'XML_ERROR_TAG_MISMATCH', + \XML_ERROR_DUPLICATE_ATTRIBUTE => 'XML_ERROR_DUPLICATE_ATTRIBUTE', + \XML_ERROR_JUNK_AFTER_DOC_ELEMENT => 'XML_ERROR_JUNK_AFTER_DOC_ELEMENT', + \XML_ERROR_PARAM_ENTITY_REF => 'XML_ERROR_PARAM_ENTITY_REF', + \XML_ERROR_UNDEFINED_ENTITY => 'XML_ERROR_UNDEFINED_ENTITY', + \XML_ERROR_RECURSIVE_ENTITY_REF => 'XML_ERROR_RECURSIVE_ENTITY_REF', + \XML_ERROR_ASYNC_ENTITY => 'XML_ERROR_ASYNC_ENTITY', + \XML_ERROR_BAD_CHAR_REF => 'XML_ERROR_BAD_CHAR_REF', + \XML_ERROR_BINARY_ENTITY_REF => 'XML_ERROR_BINARY_ENTITY_REF', + \XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF => 'XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF', + \XML_ERROR_MISPLACED_XML_PI => 'XML_ERROR_MISPLACED_XML_PI', + \XML_ERROR_UNKNOWN_ENCODING => 'XML_ERROR_UNKNOWN_ENCODING', + \XML_ERROR_INCORRECT_ENCODING => 'XML_ERROR_INCORRECT_ENCODING', + \XML_ERROR_UNCLOSED_CDATA_SECTION => 'XML_ERROR_UNCLOSED_CDATA_SECTION', + \XML_ERROR_EXTERNAL_ENTITY_HANDLING => 'XML_ERROR_EXTERNAL_ENTITY_HANDLING', ]; public static function castXml($h, array $a, Stub $stub, bool $isNested) diff --git a/src/Symfony/Component/VarDumper/Cloner/AbstractCloner.php b/src/Symfony/Component/VarDumper/Cloner/AbstractCloner.php index ee36e9f8e724..938bd0385622 100644 --- a/src/Symfony/Component/VarDumper/Cloner/AbstractCloner.php +++ b/src/Symfony/Component/VarDumper/Cloner/AbstractCloner.php @@ -251,7 +251,7 @@ public function setMinDepth(int $minDepth) public function cloneVar($var, int $filter = 0) { $this->prevErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = []) { - if (E_RECOVERABLE_ERROR === $type || E_USER_ERROR === $type) { + if (\E_RECOVERABLE_ERROR === $type || \E_USER_ERROR === $type) { // Cloner never dies throw new \ErrorException($msg, 0, $type, $file, $line); } diff --git a/src/Symfony/Component/VarDumper/Cloner/Data.php b/src/Symfony/Component/VarDumper/Cloner/Data.php index e4a588714d40..74f8f945dbe6 100644 --- a/src/Symfony/Component/VarDumper/Cloner/Data.php +++ b/src/Symfony/Component/VarDumper/Cloner/Data.php @@ -324,7 +324,7 @@ private function dumpItem(DumperInterface $dumper, Cursor $cursor, array &$refs, } } elseif (Stub::TYPE_REF === $item->type) { if ($item->handle) { - if (!isset($refs[$r = $item->handle - (PHP_INT_MAX >> 1)])) { + if (!isset($refs[$r = $item->handle - (\PHP_INT_MAX >> 1)])) { $cursor->refIndex = $refs[$r] = $cursor->refIndex ?: ++$refs[0]; } else { $firstSeen = false; diff --git a/src/Symfony/Component/VarDumper/Dumper/AbstractDumper.php b/src/Symfony/Component/VarDumper/Dumper/AbstractDumper.php index 1a0003878675..c3497e32a1ea 100644 --- a/src/Symfony/Component/VarDumper/Dumper/AbstractDumper.php +++ b/src/Symfony/Component/VarDumper/Dumper/AbstractDumper.php @@ -123,8 +123,8 @@ public function dump(Data $data, $output = null) $this->decimalPoint = localeconv(); $this->decimalPoint = $this->decimalPoint['decimal_point']; - if ($locale = $this->flags & (self::DUMP_COMMA_SEPARATOR | self::DUMP_TRAILING_COMMA) ? setlocale(LC_NUMERIC, 0) : null) { - setlocale(LC_NUMERIC, 'C'); + if ($locale = $this->flags & (self::DUMP_COMMA_SEPARATOR | self::DUMP_TRAILING_COMMA) ? setlocale(\LC_NUMERIC, 0) : null) { + setlocale(\LC_NUMERIC, 'C'); } if ($returnDump = true === $output) { @@ -148,7 +148,7 @@ public function dump(Data $data, $output = null) $this->setOutput($prevOutput); } if ($locale) { - setlocale(LC_NUMERIC, $locale); + setlocale(\LC_NUMERIC, $locale); } } diff --git a/src/Symfony/Component/VarDumper/Dumper/CliDumper.php b/src/Symfony/Component/VarDumper/Dumper/CliDumper.php index 14c008869923..5bb8a0d8987f 100644 --- a/src/Symfony/Component/VarDumper/Dumper/CliDumper.php +++ b/src/Symfony/Component/VarDumper/Dumper/CliDumper.php @@ -145,8 +145,8 @@ public function dumpScalar(Cursor $cursor, string $type, $value) $style = 'num'; switch (true) { - case INF === $value: $value = 'INF'; break; - case -INF === $value: $value = '-INF'; break; + case \INF === $value: $value = 'INF'; break; + case -\INF === $value: $value = '-INF'; break; case is_nan($value): $value = 'NAN'; break; default: $value = (string) $value; diff --git a/src/Symfony/Component/VarDumper/Dumper/ContextProvider/SourceContextProvider.php b/src/Symfony/Component/VarDumper/Dumper/ContextProvider/SourceContextProvider.php index 6f4caba63b98..c3cd3221a800 100644 --- a/src/Symfony/Component/VarDumper/Dumper/ContextProvider/SourceContextProvider.php +++ b/src/Symfony/Component/VarDumper/Dumper/ContextProvider/SourceContextProvider.php @@ -40,7 +40,7 @@ public function __construct(string $charset = null, string $projectDir = null, F public function getContext(): ?array { - $trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, $this->limit); + $trace = debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS, $this->limit); $file = $trace[1]['file']; $line = $trace[1]['line']; diff --git a/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php b/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php index c234b48e07af..a45624247a81 100644 --- a/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php +++ b/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php @@ -159,7 +159,7 @@ protected function getDumpHeader() return $this->dumpHeader; } - $line = str_replace('{$options}', json_encode($this->displayOptions, JSON_FORCE_OBJECT), <<<'EOHTML' + $line = str_replace('{$options}', json_encode($this->displayOptions, \JSON_FORCE_OBJECT), <<<'EOHTML'