+ *
+ * @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 ddb104fd2f085..2a828caf78538 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 b86f7e77b57d8..f686c53b5718f 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 693b1a2272b59..84df7d851680b 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 e1660da6e38d0..d075764af2e4b 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 a82e939d91cd5..f0b77ae6f6f11 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 a31347272278f..196d44f07edce 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 80bbf876b5537..784af89b3189a 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 6c557a777ea78..bcb86cdfbebbc 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(' data-filter-channel="= $this->escape($log['channel']); ?>">
diff --git a/src/Symfony/Component/ErrorHandler/Resources/views/trace.html.php b/src/Symfony/Component/ErrorHandler/Resources/views/trace.html.php
index 153f7d6f8e656..6b4261f3f4e15 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 1e09afbb9f320..1ca2f162b9eb1 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 b31b728e94957..4239be1ed3d2f 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 35b33d2800acc..30c5234669adf 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 5cbe87f49343d..d6efcbefa0cc0 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 99627a71a9dbe..bcb14d34a6e84 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 a67f66a42aa7f..7fb244fa6af67 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 e040e8c4bf264..6fcdac445912c 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 b5648d2f67f54..5a3fb0a0efc17 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 b67fdd12e6143..0bfd7e9977727 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 ed8b6852a5dbc..bd044621fe163 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 d2131c9b9dcd1..eb14fee9e995a 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 c6e63fbc5676b..dcd6a393a9848 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 396a3ab2e8634..76cfb9f9ff8cb 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 e1bcea35d2656..2b13a73ceb42c 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 436a66d84b99b..18e751d77b928 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 65d7423e0da32..62c9faa6e9147 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 7c2572d21047c..150a9d819efb7 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 160b30d77b0c8..4150feaf8ce85 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 20f827bed319a..59a6fdc6e9089 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 85cba6a69151e..6ed37e71a3e74 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 a08b14151764a..fd3d57c81656c 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 ac371c61c56b7..3b5a3a01b5601 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 ce535394d9938..57b37ca21c638 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 b3d0d5ef653bd..c79cbe65b9c96 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 2ac3b57ee5581..ed63d9499cdf3 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 f7db42e0f7273..2532256f2b8c0 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 61455a51330d5..5e8facd4cf959 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 0a97f6408c3ac..a5196a3b68f17 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 e535fe5c03d23..e5f5d1228b5dc 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 c9821bfe7475b..ae23428a43a37 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 69d9e85267672..cb94ca785d530 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 66e955a1dc4d9..41b927d04ac02 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 d2c800be672bf..b5a2008fa0b5c 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 4c047b67c2a2f..306460a9d76fa 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 0731942c8960a..7c6e63935473f 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 bff9852bbbd88..ad1ea18e4a1ce 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 0c69794b4e71c..03ba22716a02a 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 fc10683a5ff49..5174ad053a2ea 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 76e650934b134..5b7b44830722c 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 76031d7298246..606d043298be0 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 f447ce104963d..cf2f1cc6e9891 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 afd4c88fb8b48..61a0c004acfb9 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 2a47dbcca0ec0..0d765b74e68e9 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 fe3de8bf23438..f74e621bb8bae 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 82b0e2c1ebe38..29f82ac9b7ced 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 2ba1b010e41fb..c06df1afb0f0e 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 9f67d7e966617..76af2dfa7e74f 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 087445d6e2d87..ac0031738ed71 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 0525feed6c042..ad07f86451688 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 269464d400e3c..0a628171835b2 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 ac6c30df1f501..c2771cc3ae0a5 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 = <<
@@ -35,7 +35,7 @@
= $this->formatLogMessage($log['message'], $log['context']); ?>
-
= json_encode($log['context'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>
+ = $this->escape(json_encode($log['context'], \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES)); ?>