diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 8b50502e98c7e..2333c06badd58 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -11,6 +11,7 @@ '@Symfony' => true, '@Symfony:risky' => true, 'protected_to_private' => false, + 'native_constant_invocation' => ['strict' => false], 'nullable_type_declaration_for_default_null_value' => ['use_nullable_type_declaration' => false], 'modernize_strpos' => true, ]) diff --git a/src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php b/src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php index 82a4f36ce349c..d262c5e3591e4 100644 --- a/src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php +++ b/src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php @@ -56,7 +56,7 @@ public function dispatchEvent($eventName, EventArgs $eventArgs = null): void return; } - $eventArgs = $eventArgs ?? EventArgs::getEmptyInstance(); + $eventArgs ??= EventArgs::getEmptyInstance(); if (!isset($this->initialized[$eventName])) { $this->initializeListeners($eventName); diff --git a/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php b/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php index 367eb12e29162..4774019da3349 100644 --- a/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php +++ b/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php @@ -134,8 +134,6 @@ protected function setMappingDriverConfig(array $mappingConfig, string $mappingN * If this is a bundle controlled mapping all the missing information can be autodetected by this method. * * Returns false when autodetection failed, an array of the completed information otherwise. - * - * @return array|false */ protected function getMappingDriverBundleConfigDefaults(array $bundleConfig, \ReflectionClass $bundle, ContainerBuilder $container, string $bundleDir = null): array|false { diff --git a/src/Symfony/Bridge/Doctrine/Validator/DoctrineLoader.php b/src/Symfony/Bridge/Doctrine/Validator/DoctrineLoader.php index d06a34a40f630..a4e695d37df1b 100644 --- a/src/Symfony/Bridge/Doctrine/Validator/DoctrineLoader.php +++ b/src/Symfony/Bridge/Doctrine/Validator/DoctrineLoader.php @@ -49,7 +49,7 @@ public function loadClassMetadata(ClassMetadata $metadata): bool $className = $metadata->getClassName(); try { $doctrineMetadata = $this->entityManager->getClassMetadata($className); - } catch (MappingException | OrmMappingException $exception) { + } catch (MappingException|OrmMappingException $exception) { return false; } diff --git a/src/Symfony/Bridge/Twig/AppVariable.php b/src/Symfony/Bridge/Twig/AppVariable.php index d21f6448a481b..b46646b5461ae 100644 --- a/src/Symfony/Bridge/Twig/AppVariable.php +++ b/src/Symfony/Bridge/Twig/AppVariable.php @@ -100,7 +100,7 @@ public function getSession(): ?Session } $request = $this->getRequest(); - return $request && $request->hasSession() ? $request->getSession() : null; + return $request?->hasSession() ? $request->getSession() : null; } /** diff --git a/src/Symfony/Bridge/Twig/UndefinedCallableHandler.php b/src/Symfony/Bridge/Twig/UndefinedCallableHandler.php index 360a386faedec..30dd92ff2ff3b 100644 --- a/src/Symfony/Bridge/Twig/UndefinedCallableHandler.php +++ b/src/Symfony/Bridge/Twig/UndefinedCallableHandler.php @@ -68,9 +68,6 @@ class UndefinedCallableHandler 'workflow' => 'enable "framework.workflows"', ]; - /** - * @return TwigFilter|false - */ public static function onUndefinedFilter(string $name): TwigFilter|false { if (!isset(self::FILTER_COMPONENTS[$name])) { @@ -80,9 +77,6 @@ public static function onUndefinedFilter(string $name): TwigFilter|false throw new SyntaxError(self::onUndefined($name, 'filter', self::FILTER_COMPONENTS[$name])); } - /** - * @return TwigFunction|false - */ public static function onUndefinedFunction(string $name): TwigFunction|false { if (!isset(self::FUNCTION_COMPONENTS[$name])) { diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/WorkflowDumpCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/WorkflowDumpCommand.php index 3cb0a4ffcbb6d..eb96e65470ebf 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/WorkflowDumpCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/WorkflowDumpCommand.php @@ -36,7 +36,8 @@ class WorkflowDumpCommand extends Command { /** - * string is the service id + * string is the service id. + * * @var array */ private array $workflows = []; diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php b/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php index 1ae52cb1ee1a1..86c365c258fb6 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php +++ b/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php @@ -70,8 +70,6 @@ public function setContainer(ContainerInterface $container): ?ContainerInterface /** * Gets a container parameter by its name. - * - * @return array|bool|float|int|string|null */ protected function getParameter(string $name): array|bool|float|int|string|null { diff --git a/src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php b/src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php index a85eb3d017c1e..6795e3c22aa0e 100644 --- a/src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php +++ b/src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php @@ -62,8 +62,6 @@ public function getKernel(): KernelInterface /** * Gets the profile associated with the current Response. - * - * @return HttpProfile|false|null */ public function getProfile(): HttpProfile|false|null { diff --git a/src/Symfony/Bundle/FrameworkBundle/Test/TestContainer.php b/src/Symfony/Bundle/FrameworkBundle/Test/TestContainer.php index 4ce5772d91e63..75a87870691d2 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Test/TestContainer.php +++ b/src/Symfony/Bundle/FrameworkBundle/Test/TestContainer.php @@ -63,8 +63,6 @@ public function getParameterBag(): ParameterBagInterface /** * {@inheritdoc} - * - * @return array|bool|float|int|string|null */ public function getParameter(string $name): array|bool|float|int|string|null { diff --git a/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php b/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php index 045f040225bfc..394006f55b66b 100644 --- a/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php +++ b/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php @@ -185,7 +185,6 @@ public function collect(Request $request, Response $response, \Throwable $except 'authenticators' => $firewallConfig->getAuthenticators(), ]; - // generate exit impersonation path from current request if ($this->data['impersonated'] && null !== $switchUserConfig = $firewallConfig->getSwitchUser()) { $exitPath = $request->getRequestUri(); diff --git a/src/Symfony/Bundle/SecurityBundle/Debug/TraceableListenerTrait.php b/src/Symfony/Bundle/SecurityBundle/Debug/TraceableListenerTrait.php index 2ae1f4af9bb34..357d2414d8bf2 100644 --- a/src/Symfony/Bundle/SecurityBundle/Debug/TraceableListenerTrait.php +++ b/src/Symfony/Bundle/SecurityBundle/Debug/TraceableListenerTrait.php @@ -45,7 +45,7 @@ public function getInfo(): array return [ 'response' => $this->response, 'time' => $this->time, - 'stub' => $this->stub ?? $this->stub = ClassStub::wrapCallable($this->listener instanceof TraceableAuthenticatorManagerListener ? $this->listener->getAuthenticatorManagerListener() : $this->listener), + 'stub' => $this->stub ??= ClassStub::wrapCallable($this->listener instanceof TraceableAuthenticatorManagerListener ? $this->listener->getAuthenticatorManagerListener() : $this->listener), ]; } } diff --git a/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php b/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php index f4bfec100e3a6..5152223669c8d 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php +++ b/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php @@ -95,7 +95,7 @@ public function onKernelResponse(ResponseEvent $event) $nonces = []; if ($this->cspHandler) { - if ($this->dumpDataCollector && $this->dumpDataCollector->getDumpsCount() > 0) { + if ($this->dumpDataCollector?->getDumpsCount() > 0) { $this->cspHandler->disableCsp(); } diff --git a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php index 19f282e23391b..19be14f1d01a4 100644 --- a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php @@ -74,7 +74,7 @@ static function ($deferred, $namespace, &$expiredIds, $getId, $defaultLifetime) $key = (string) $key; if (null === $item->expiry) { $ttl = 0 < $defaultLifetime ? $defaultLifetime : 0; - } elseif (0 === $item->expiry) { + } elseif (!$item->expiry) { $ttl = 0; } elseif (0 >= $ttl = (int) (0.1 + $item->expiry - $now)) { $expiredIds[] = $getId($key); diff --git a/src/Symfony/Component/Cache/Adapter/AbstractTagAwareAdapter.php b/src/Symfony/Component/Cache/Adapter/AbstractTagAwareAdapter.php index 476cec9d15a49..f66c8370d5b91 100644 --- a/src/Symfony/Component/Cache/Adapter/AbstractTagAwareAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/AbstractTagAwareAdapter.php @@ -79,7 +79,7 @@ static function ($deferred, &$expiredIds, $getId, $tagPrefix, $defaultLifetime) $key = (string) $key; if (null === $item->expiry) { $ttl = 0 < $defaultLifetime ? $defaultLifetime : 0; - } elseif (0 === $item->expiry) { + } elseif (!$item->expiry) { $ttl = 0; } elseif (0 >= $ttl = (int) (0.1 + $item->expiry - $now)) { $expiredIds[] = $getId($key); diff --git a/src/Symfony/Component/Cache/Adapter/ArrayAdapter.php b/src/Symfony/Component/Cache/Adapter/ArrayAdapter.php index 3a37297cddba1..d6eb152f08fcb 100644 --- a/src/Symfony/Component/Cache/Adapter/ArrayAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/ArrayAdapter.php @@ -182,14 +182,14 @@ public function save(CacheItemInterface $item): bool $now = microtime(true); - if (0 === $expiry) { - $expiry = \PHP_INT_MAX; - } - - if (null !== $expiry && $expiry <= $now) { - $this->deleteItem($key); + if (null !== $expiry) { + if (!$expiry) { + $expiry = \PHP_INT_MAX; + } elseif ($expiry <= $now) { + $this->deleteItem($key); - return true; + return true; + } } if ($this->storeSerialized && null === $value = $this->freeze($value, $key)) { return false; diff --git a/src/Symfony/Component/Cache/Adapter/ChainAdapter.php b/src/Symfony/Component/Cache/Adapter/ChainAdapter.php index 925e9f2f6b5bc..64ae546440aad 100644 --- a/src/Symfony/Component/Cache/Adapter/ChainAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/ChainAdapter.php @@ -66,10 +66,10 @@ public function __construct(array $adapters, int $defaultLifetime = 0) $this->adapterCount = \count($this->adapters); $this->defaultLifetime = $defaultLifetime; - self::$syncItem ?? self::$syncItem = \Closure::bind( + self::$syncItem ??= \Closure::bind( static function ($sourceItem, $item, $defaultLifetime, $sourceMetadata = null) { $sourceItem->isTaggable = false; - $sourceMetadata = $sourceMetadata ?? $sourceItem->metadata; + $sourceMetadata ??= $sourceItem->metadata; unset($sourceMetadata[CacheItem::METADATA_TAGS]); $item->value = $sourceItem->value; @@ -108,7 +108,7 @@ public function get(string $key, callable $callback, float $beta = null, array & $value = $this->doGet($adapter, $key, $callback, $beta, $metadata); } if (null !== $item) { - (self::$syncItem)($lastItem = $lastItem ?? $item, $item, $this->defaultLifetime, $metadata); + (self::$syncItem)($lastItem ??= $item, $item, $this->defaultLifetime, $metadata); } return $value; diff --git a/src/Symfony/Component/Cache/Adapter/PhpFilesAdapter.php b/src/Symfony/Component/Cache/Adapter/PhpFilesAdapter.php index 13e45435f0f75..7ec96f5d88eba 100644 --- a/src/Symfony/Component/Cache/Adapter/PhpFilesAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/PhpFilesAdapter.php @@ -135,7 +135,7 @@ protected function doFetch(array $ids): iterable foreach ($missingIds as $k => $id) { try { - $file = $this->files[$id] ?? $this->files[$id] = $this->getFile($id); + $file = $this->files[$id] ??= $this->getFile($id); if (isset(self::$valuesCache[$file])) { [$expiresAt, $this->values[$id]] = self::$valuesCache[$file]; @@ -176,7 +176,7 @@ protected function doHave(string $id): bool set_error_handler($this->includeHandler); try { - $file = $this->files[$id] ?? $this->files[$id] = $this->getFile($id); + $file = $this->files[$id] ??= $this->getFile($id); $getExpiry = true; if (isset(self::$valuesCache[$file])) { diff --git a/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php b/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php index c90b80e4cbd51..23434cd4714c9 100644 --- a/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php @@ -92,7 +92,7 @@ static function (CacheItemInterface $innerItem, array $item) { $item["\0*\0value"] = ["\x9D".pack('VN', (int) (0.1 + $metadata[self::METADATA_EXPIRY] - self::METADATA_EXPIRY_OFFSET), $metadata[self::METADATA_CTIME])."\x5F" => $item["\0*\0value"]]; } $innerItem->set($item["\0*\0value"]); - $innerItem->expiresAt(null !== $item["\0*\0expiry"] ? \DateTime::createFromFormat('U.u', sprintf('%.6F', 0 === $item["\0*\0expiry"] ? \PHP_INT_MAX : $item["\0*\0expiry"])) : null); + $innerItem->expiresAt(null !== $item["\0*\0expiry"] ? \DateTime::createFromFormat('U.u', sprintf('%.6F', $item["\0*\0expiry"])) : null); }, null, CacheItem::class diff --git a/src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php b/src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php index 1ec5a8cc30846..cb1c638c5c0db 100644 --- a/src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php @@ -55,7 +55,7 @@ class RedisTagAwareAdapter extends AbstractTagAwareAdapter private const DEFAULT_CACHE_TTL = 8640000; /** - * detected eviction policy used on Redis server + * detected eviction policy used on Redis server. */ private string $redisEvictionPolicy; diff --git a/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php b/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php index a36551d308de7..0176383ef063c 100644 --- a/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php @@ -48,7 +48,7 @@ public function __construct(AdapterInterface $itemsPool, AdapterInterface $tagsP $this->pool = $itemsPool; $this->tags = $tagsPool ?? $itemsPool; $this->knownTagVersionsTtl = $knownTagVersionsTtl; - self::$createCacheItem ?? self::$createCacheItem = \Closure::bind( + self::$createCacheItem ??= \Closure::bind( static function ($key, $value, CacheItem $protoItem) { $item = new CacheItem(); $item->key = $key; @@ -61,7 +61,7 @@ static function ($key, $value, CacheItem $protoItem) { null, CacheItem::class ); - self::$setCacheItemTags ?? self::$setCacheItemTags = \Closure::bind( + self::$setCacheItemTags ??= \Closure::bind( static function (CacheItem $item, $key, array &$itemTags) { $item->isTaggable = true; if (!$item->isHit) { @@ -82,7 +82,7 @@ static function (CacheItem $item, $key, array &$itemTags) { null, CacheItem::class ); - self::$getTagsByKey ?? self::$getTagsByKey = \Closure::bind( + self::$getTagsByKey ??= \Closure::bind( static function ($deferred) { $tagsByKey = []; foreach ($deferred as $key => $item) { @@ -95,7 +95,7 @@ static function ($deferred) { null, CacheItem::class ); - self::$saveTags ?? self::$saveTags = \Closure::bind( + self::$saveTags ??= \Closure::bind( static function (AdapterInterface $tagsAdapter, array $tags) { ksort($tags); @@ -394,7 +394,7 @@ private function getTagVersions(array $tagsByKey): array $newVersion = null; foreach ($this->tags->getItems(array_keys($tags)) as $tag => $version) { if (!$version->isHit()) { - $newTags[$tag] = $version->set($newVersion ?? $newVersion = random_int(\PHP_INT_MIN, \PHP_INT_MAX)); + $newTags[$tag] = $version->set($newVersion ??= random_int(\PHP_INT_MIN, \PHP_INT_MAX)); } $tagVersions[$tag = $tags[$tag]] = $version->get(); $this->knownTagVersions[$tag] = [$now, $tagVersions[$tag]]; diff --git a/src/Symfony/Component/Cache/CHANGELOG.md b/src/Symfony/Component/Cache/CHANGELOG.md index a1dc4617e5b13..1f54db7b8bd80 100644 --- a/src/Symfony/Component/Cache/CHANGELOG.md +++ b/src/Symfony/Component/Cache/CHANGELOG.md @@ -10,7 +10,6 @@ CHANGELOG 5.4 --- - * Make `LockRegistry` use semaphores when possible * Deprecate `DoctrineProvider` and `DoctrineAdapter` because these classes have been added to the `doctrine/cache` package * Add `DoctrineDbalAdapter` identical to `PdoAdapter` for `Doctrine\DBAL\Connection` or DBAL URL * Deprecate usage of `PdoAdapter` with `Doctrine\DBAL\Connection` or DBAL URL diff --git a/src/Symfony/Component/Cache/LockRegistry.php b/src/Symfony/Component/Cache/LockRegistry.php index 5803bccc7688d..da67036dc4666 100644 --- a/src/Symfony/Component/Cache/LockRegistry.php +++ b/src/Symfony/Component/Cache/LockRegistry.php @@ -27,7 +27,7 @@ final class LockRegistry { private static $openedFiles = []; - private static $lockedKeys; + private static $lockedFiles; /** * The number of items in this list controls the max number of concurrent processes. @@ -76,25 +76,21 @@ public static function setFiles(array $files): array fclose($file); } } - self::$openedFiles = self::$lockedKeys = []; + self::$openedFiles = self::$lockedFiles = []; return $previousFiles; } public static function compute(callable $callback, ItemInterface $item, bool &$save, CacheInterface $pool, \Closure $setMetadata = null, LoggerInterface $logger = null) { - if ('\\' === \DIRECTORY_SEPARATOR && null === self::$lockedKeys) { + if ('\\' === \DIRECTORY_SEPARATOR && null === self::$lockedFiles) { // disable locking on Windows by default - self::$files = self::$lockedKeys = []; + self::$files = self::$lockedFiles = []; } - $key = unpack('i', md5($item->getKey(), true))[1]; + $key = self::$files ? abs(crc32($item->getKey())) % \count(self::$files) : -1; - if (!\function_exists('sem_get')) { - $key = self::$files ? abs($key) % \count(self::$files) : null; - } - - if (null === $key || (self::$lockedKeys[$key] ?? false) || !$lock = self::open($key)) { + if ($key < 0 || (self::$lockedFiles[$key] ?? false) || !$lock = self::open($key)) { return $callback($item, $save); } @@ -102,15 +98,11 @@ public static function compute(callable $callback, ItemInterface $item, bool &$s try { $locked = false; // race to get the lock in non-blocking mode - if ($wouldBlock = \function_exists('sem_get')) { - $locked = @sem_acquire($lock, true); - } else { - $locked = flock($lock, \LOCK_EX | \LOCK_NB, $wouldBlock); - } + $locked = flock($lock, \LOCK_EX | \LOCK_NB, $wouldBlock); if ($locked || !$wouldBlock) { - $logger && $logger->info(sprintf('Lock %s, now computing item "{key}"', $locked ? 'acquired' : 'not supported'), ['key' => $item->getKey()]); - self::$lockedKeys[$key] = true; + $logger?->info(sprintf('Lock %s, now computing item "{key}"', $locked ? 'acquired' : 'not supported'), ['key' => $item->getKey()]); + self::$lockedFiles[$key] = true; $value = $callback($item, $save); @@ -125,25 +117,12 @@ public static function compute(callable $callback, ItemInterface $item, bool &$s return $value; } - // if we failed the race, retry locking in blocking mode to wait for the winner - $logger && $logger->info('Item "{key}" is locked, waiting for it to be released', ['key' => $item->getKey()]); - - if (\function_exists('sem_get')) { - $lock = sem_get($key); - @sem_acquire($lock); - } else { - flock($lock, \LOCK_SH); - } + $logger?->info('Item "{key}" is locked, waiting for it to be released', ['key' => $item->getKey()]); + flock($lock, \LOCK_SH); } finally { - if ($locked) { - if (\function_exists('sem_get')) { - sem_remove($lock); - } else { - flock($lock, \LOCK_UN); - } - } - unset(self::$lockedKeys[$key]); + flock($lock, \LOCK_UN); + unset(self::$lockedFiles[$key]); } static $signalingException, $signalingCallback; $signalingException = $signalingException ?? unserialize("O:9:\"Exception\":1:{s:16:\"\0Exception\0trace\";a:0:{}}"); @@ -151,7 +130,7 @@ public static function compute(callable $callback, ItemInterface $item, bool &$s try { $value = $pool->get($item->getKey(), $signalingCallback, 0); - $logger && $logger->info('Item "{key}" retrieved after lock was released', ['key' => $item->getKey()]); + $logger?->info('Item "{key}" retrieved after lock was released', ['key' => $item->getKey()]); $save = false; return $value; @@ -159,7 +138,7 @@ public static function compute(callable $callback, ItemInterface $item, bool &$s if ($signalingException !== $e) { throw $e; } - $logger && $logger->info('Item "{key}" not found while lock was released, now retrying', ['key' => $item->getKey()]); + $logger?->info('Item "{key}" not found while lock was released, now retrying', ['key' => $item->getKey()]); } } @@ -168,10 +147,6 @@ public static function compute(callable $callback, ItemInterface $item, bool &$s private static function open(int $key) { - if (\function_exists('sem_get')) { - return sem_get($key); - } - if (null !== $h = self::$openedFiles[$key] ?? null) { return $h; } diff --git a/src/Symfony/Component/Cache/Marshaller/DefaultMarshaller.php b/src/Symfony/Component/Cache/Marshaller/DefaultMarshaller.php index 7459a9db47029..5c34fb2ea59d3 100644 --- a/src/Symfony/Component/Cache/Marshaller/DefaultMarshaller.php +++ b/src/Symfony/Component/Cache/Marshaller/DefaultMarshaller.php @@ -71,7 +71,7 @@ public function unmarshall(string $value): mixed return null; } static $igbinaryNull; - if ($value === ($igbinaryNull ?? $igbinaryNull = \extension_loaded('igbinary') ? igbinary_serialize(null) : false)) { + if ($value === $igbinaryNull ??= \extension_loaded('igbinary') ? igbinary_serialize(null) : false) { return null; } $unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback'); diff --git a/src/Symfony/Component/Cache/Messenger/EarlyExpirationDispatcher.php b/src/Symfony/Component/Cache/Messenger/EarlyExpirationDispatcher.php index 25b5023b32fd3..5aeacf1d598ef 100644 --- a/src/Symfony/Component/Cache/Messenger/EarlyExpirationDispatcher.php +++ b/src/Symfony/Component/Cache/Messenger/EarlyExpirationDispatcher.php @@ -38,7 +38,7 @@ public function __invoke(callable $callback, CacheItem $item, bool &$save, Adapt { if (!$item->isHit() || null === $message = EarlyExpirationMessage::create($this->reverseContainer, $callback, $item, $pool)) { // The item is stale or the callback cannot be reversed: we must compute the value now - $logger && $logger->info('Computing item "{key}" online: '.($item->isHit() ? 'callback cannot be reversed' : 'item is stale'), ['key' => $item->getKey()]); + $logger?->info('Computing item "{key}" online: '.($item->isHit() ? 'callback cannot be reversed' : 'item is stale'), ['key' => $item->getKey()]); return null !== $this->callbackWrapper ? ($this->callbackWrapper)($callback, $item, $save, $pool, $setMetadata, $logger) : $callback($item, $save); } diff --git a/src/Symfony/Component/Cache/Messenger/EarlyExpirationHandler.php b/src/Symfony/Component/Cache/Messenger/EarlyExpirationHandler.php index 043b4a177c6fb..9d2aaecc76c83 100644 --- a/src/Symfony/Component/Cache/Messenger/EarlyExpirationHandler.php +++ b/src/Symfony/Component/Cache/Messenger/EarlyExpirationHandler.php @@ -59,7 +59,7 @@ public function __invoke(EarlyExpirationMessage $message) static $setMetadata; - $setMetadata ?? $setMetadata = \Closure::bind( + $setMetadata ??= \Closure::bind( function (CacheItem $item, float $startTime) { if ($item->expiry > $endTime = microtime(true)) { $item->newMetadata[CacheItem::METADATA_EXPIRY] = $item->expiry; diff --git a/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterAndRedisAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterAndRedisAdapterTest.php new file mode 100644 index 0000000000000..46516e0095e6e --- /dev/null +++ b/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterAndRedisAdapterTest.php @@ -0,0 +1,72 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Cache\Tests\Adapter; + +use Psr\Cache\CacheItemPoolInterface; +use Symfony\Component\Cache\Adapter\AbstractAdapter; +use Symfony\Component\Cache\Adapter\ProxyAdapter; +use Symfony\Component\Cache\Adapter\RedisAdapter; +use Symfony\Component\Cache\CacheItem; + +/** + * @group integration + */ +class ProxyAdapterAndRedisAdapterTest extends AbstractRedisAdapterTest +{ + protected $skippedTests = [ + 'testPrune' => 'RedisAdapter does not implement PruneableInterface.', + ]; + + public static function setUpBeforeClass(): void + { + parent::setUpBeforeClass(); + self::$redis = AbstractAdapter::createConnection('redis://'.getenv('REDIS_HOST')); + } + + public function createCachePool($defaultLifetime = 0, string $testMethod = null): CacheItemPoolInterface + { + return new ProxyAdapter(new RedisAdapter(self::$redis, str_replace('\\', '.', __CLASS__), 100), 'ProxyNS', $defaultLifetime); + } + + public function testSaveItemPermanently() + { + $setCacheItemExpiry = \Closure::bind( + static function (CacheItem $item, $expiry) { + $item->expiry = $expiry; + + return $item; + }, + null, + CacheItem::class + ); + + $cache = $this->createCachePool(1); + $value = rand(); + $item = $cache->getItem('foo'); + $setCacheItemExpiry($item, 0); + $cache->save($item->set($value)); + $item = $cache->getItem('bar'); + $setCacheItemExpiry($item, 0.0); + $cache->save($item->set($value)); + $item = $cache->getItem('baz'); + $cache->save($item->set($value)); + + $this->assertSame($value, $this->cache->getItem('foo')->get()); + $this->assertSame($value, $this->cache->getItem('bar')->get()); + $this->assertSame($value, $this->cache->getItem('baz')->get()); + + sleep(1); + $this->assertSame($value, $this->cache->getItem('foo')->get()); + $this->assertSame($value, $this->cache->getItem('bar')->get()); + $this->assertFalse($this->cache->getItem('baz')->isHit()); + } +} diff --git a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php index 54ce7822e06af..81e943c144f56 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php @@ -14,12 +14,10 @@ use PHPUnit\Framework\MockObject\MockObject; use Psr\Cache\CacheItemInterface; use Psr\Cache\CacheItemPoolInterface; -use Psr\Log\LoggerInterface; use Symfony\Component\Cache\Adapter\AdapterInterface; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Component\Cache\Adapter\TagAwareAdapter; -use Symfony\Component\Cache\LockRegistry; use Symfony\Component\Cache\Tests\Fixtures\PrunableAdapter; use Symfony\Component\Filesystem\Filesystem; @@ -181,24 +179,6 @@ public function testGetItemReturnsCacheMissWhenPoolDoesNotHaveItemAndOnlyHasTags $this->assertFalse($item->isHit()); } - public function testLog() - { - $lockFiles = LockRegistry::setFiles([__FILE__]); - - $logger = $this->createMock(LoggerInterface::class); - $logger - ->expects($this->atLeastOnce()) - ->method($this->anything()); - - $cache = new TagAwareAdapter(new ArrayAdapter()); - $cache->setLogger($logger); - - // Computing will produce at least one log - $cache->get('foo', static function (): string { return 'ccc'; }); - - LockRegistry::setFiles($lockFiles); - } - /** * @return MockObject&PruneableCacheInterface */ diff --git a/src/Symfony/Component/Cache/Traits/AbstractAdapterTrait.php b/src/Symfony/Component/Cache/Traits/AbstractAdapterTrait.php index 0149b7674c50e..64e35a47a174f 100644 --- a/src/Symfony/Component/Cache/Traits/AbstractAdapterTrait.php +++ b/src/Symfony/Component/Cache/Traits/AbstractAdapterTrait.php @@ -26,12 +26,12 @@ trait AbstractAdapterTrait use LoggerAwareTrait; /** - * needs to be set by class, signature is function(string , mixed , bool ) + * needs to be set by class, signature is function(string , mixed , bool ). */ private static \Closure $createCacheItem; /** - * needs to be set by class, signature is function(array , string , array <&expiredIds>) + * needs to be set by class, signature is function(array , string , array <&expiredIds>). */ private static \Closure $mergeByLifetime; diff --git a/src/Symfony/Component/Cache/Traits/ContractsTrait.php b/src/Symfony/Component/Cache/Traits/ContractsTrait.php index 6361f95161a29..f63b4957ac9ac 100644 --- a/src/Symfony/Component/Cache/Traits/ContractsTrait.php +++ b/src/Symfony/Component/Cache/Traits/ContractsTrait.php @@ -41,12 +41,20 @@ trait ContractsTrait */ public function setCallbackWrapper(?callable $callbackWrapper): callable { - $previousWrapper = $this->callbackWrapper ??= \Closure::fromCallable([LockRegistry::class, 'compute']); + if (!isset($this->callbackWrapper)) { + $this->callbackWrapper = \Closure::fromCallable([LockRegistry::class, 'compute']); + + if (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) { + $this->setCallbackWrapper(null); + } + } + if (null !== $callbackWrapper && !$callbackWrapper instanceof \Closure) { $callbackWrapper = \Closure::fromCallable($callbackWrapper); } - $this->callbackWrapper = $callbackWrapper ?? function (callable $callback, ItemInterface $item, bool &$save, CacheInterface $pool, \Closure $setMetadata, ?LoggerInterface $logger) { + $previousWrapper = $this->callbackWrapper; + $this->callbackWrapper = $callbackWrapper ?? static function (callable $callback, ItemInterface $item, bool &$save, CacheInterface $pool, \Closure $setMetadata, ?LoggerInterface $logger) { return $callback($item, $save); }; @@ -55,13 +63,13 @@ public function setCallbackWrapper(?callable $callbackWrapper): callable private function doGet(AdapterInterface $pool, string $key, callable $callback, ?float $beta, array &$metadata = null) { - if (0 > $beta = $beta ?? 1.0) { + if (0 > $beta ??= 1.0) { throw new InvalidArgumentException(sprintf('Argument "$beta" provided to "%s::get()" must be a positive number, %f given.', static::class, $beta)); } static $setMetadata; - $setMetadata ?? $setMetadata = \Closure::bind( + $setMetadata ??= \Closure::bind( static function (CacheItem $item, float $startTime, ?array &$metadata) { if ($item->expiry > $endTime = microtime(true)) { $item->newMetadata[CacheItem::METADATA_EXPIRY] = $metadata[CacheItem::METADATA_EXPIRY] = $item->expiry; @@ -88,6 +96,10 @@ static function (CacheItem $item, float $startTime, ?array &$metadata) { $this->computing[$key] = $key; $startTime = microtime(true); + if (!isset($this->callbackWrapper)) { + $this->setCallbackWrapper($this->setCallbackWrapper(null)); + } + try { $value = ($this->callbackWrapper)($callback, $item, $save, $pool, function (CacheItem $item) use ($setMetadata, $startTime, &$metadata) { $setMetadata($item, $startTime, $metadata); diff --git a/src/Symfony/Component/Cache/Traits/RedisTrait.php b/src/Symfony/Component/Cache/Traits/RedisTrait.php index fc833beb7f23a..9a48944bafd4a 100644 --- a/src/Symfony/Component/Cache/Traits/RedisTrait.php +++ b/src/Symfony/Component/Cache/Traits/RedisTrait.php @@ -441,7 +441,7 @@ protected function doDelete(array $ids): bool if ($this->redis instanceof \Predis\ClientInterface && $this->redis->getConnection() instanceof ClusterInterface) { static $del; - $del = $del ?? (class_exists(UNLINK::class) ? 'unlink' : 'del'); + $del ??= (class_exists(UNLINK::class) ? 'unlink' : 'del'); $this->pipeline(function () use ($ids, $del) { foreach ($ids as $id) { @@ -498,7 +498,7 @@ protected function doSave(array $values, int $lifetime): array|bool private function pipeline(\Closure $generator, object $redis = null): \Generator { $ids = []; - $redis = $redis ?? $this->redis; + $redis ??= $this->redis; if ($redis instanceof RedisClusterProxy || $redis instanceof \RedisCluster || ($redis instanceof \Predis\ClientInterface && $redis->getConnection() instanceof RedisCluster)) { // phpredis & predis don't support pipelining with RedisCluster diff --git a/src/Symfony/Component/Config/Definition/Builder/ExprBuilder.php b/src/Symfony/Component/Config/Definition/Builder/ExprBuilder.php index 71d156dfc47a1..22f8280d6018a 100644 --- a/src/Symfony/Component/Config/Definition/Builder/ExprBuilder.php +++ b/src/Symfony/Component/Config/Definition/Builder/ExprBuilder.php @@ -204,8 +204,6 @@ public function thenUnset(): static /** * Returns the related node. * - * @return NodeDefinition|ArrayNodeDefinition|VariableNodeDefinition - * * @throws \RuntimeException */ public function end(): NodeDefinition|ArrayNodeDefinition|VariableNodeDefinition diff --git a/src/Symfony/Component/Config/Definition/Builder/MergeBuilder.php b/src/Symfony/Component/Config/Definition/Builder/MergeBuilder.php index 1b55b185bd970..f8980a6e041c9 100644 --- a/src/Symfony/Component/Config/Definition/Builder/MergeBuilder.php +++ b/src/Symfony/Component/Config/Definition/Builder/MergeBuilder.php @@ -53,8 +53,6 @@ public function denyOverwrite(bool $deny = true): static /** * Returns the related node. - * - * @return NodeDefinition|ArrayNodeDefinition|VariableNodeDefinition */ public function end(): NodeDefinition|ArrayNodeDefinition|VariableNodeDefinition { diff --git a/src/Symfony/Component/Config/Definition/Builder/TreeBuilder.php b/src/Symfony/Component/Config/Definition/Builder/TreeBuilder.php index 4a106d1d289d2..e469e69044c3f 100644 --- a/src/Symfony/Component/Config/Definition/Builder/TreeBuilder.php +++ b/src/Symfony/Component/Config/Definition/Builder/TreeBuilder.php @@ -25,7 +25,7 @@ class TreeBuilder implements NodeParentInterface public function __construct(string $name, string $type = 'array', NodeBuilder $builder = null) { - $builder = $builder ?? new NodeBuilder(); + $builder ??= new NodeBuilder(); $this->root = $builder->node($name, $type)->setParent($this); } diff --git a/src/Symfony/Component/Config/Tests/Builder/GeneratedConfigTest.php b/src/Symfony/Component/Config/Tests/Builder/GeneratedConfigTest.php index e85558cac8d96..c988c0ab30bb7 100644 --- a/src/Symfony/Component/Config/Tests/Builder/GeneratedConfigTest.php +++ b/src/Symfony/Component/Config/Tests/Builder/GeneratedConfigTest.php @@ -148,7 +148,7 @@ public function testSetExtraKeyMethodIsNotGeneratedWhenAllowExtraKeysIsFalse() */ private function generateConfigBuilder(string $configurationClass, string $outputDir = null) { - $outputDir ?? $outputDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('sf_config_builder', true); + $outputDir ??= sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('sf_config_builder', true); if (!str_contains($outputDir, __DIR__)) { $this->tempDir[] = $outputDir; } diff --git a/src/Symfony/Component/Console/Application.php b/src/Symfony/Component/Console/Application.php index b582435f7d102..0ed5649b8ac55 100644 --- a/src/Symfony/Component/Console/Application.php +++ b/src/Symfony/Component/Console/Application.php @@ -558,7 +558,7 @@ public function has(string $name): bool { $this->init(); - return isset($this->commands[$name]) || ($this->commandLoader && $this->commandLoader->has($name) && $this->add($this->commandLoader->get($name))); + return isset($this->commands[$name]) || ($this->commandLoader?->has($name) && $this->add($this->commandLoader->get($name))); } /** diff --git a/src/Symfony/Component/Console/Command/Command.php b/src/Symfony/Component/Console/Command/Command.php index decfea278282b..0bd3426c07eb3 100644 --- a/src/Symfony/Component/Console/Command/Command.php +++ b/src/Symfony/Component/Console/Command/Command.php @@ -556,7 +556,7 @@ public function getHelp(): string public function getProcessedHelp(): string { $name = $this->name; - $isSingleCommand = $this->application && $this->application->isSingleCommand(); + $isSingleCommand = $this->application?->isSingleCommand(); $placeholders = [ '%command.name%', diff --git a/src/Symfony/Component/Console/Completion/CompletionInput.php b/src/Symfony/Component/Console/Completion/CompletionInput.php index eda95bef55468..b0f00088e7150 100644 --- a/src/Symfony/Component/Console/Completion/CompletionInput.php +++ b/src/Symfony/Component/Console/Completion/CompletionInput.php @@ -84,7 +84,7 @@ public function bind(InputDefinition $definition): void return; } - if (null !== $option && $option->acceptValue()) { + if ($option?->acceptValue()) { $this->completionType = self::TYPE_OPTION_VALUE; $this->completionName = $option->getName(); $this->completionValue = $optionValue ?: (!str_starts_with($optionToken, '--') ? substr($optionToken, 2) : ''); @@ -97,7 +97,7 @@ public function bind(InputDefinition $definition): void if ('-' === $previousToken[0] && '' !== trim($previousToken, '-')) { // check if previous option accepted a value $previousOption = $this->getOptionFromToken($previousToken); - if (null !== $previousOption && $previousOption->acceptValue()) { + if ($previousOption?->acceptValue()) { $this->completionType = self::TYPE_OPTION_VALUE; $this->completionName = $previousOption->getName(); $this->completionValue = $relevantToken; diff --git a/src/Symfony/Component/Console/DependencyInjection/AddConsoleCommandPass.php b/src/Symfony/Component/Console/DependencyInjection/AddConsoleCommandPass.php index efaf39a2c9a20..4334556663078 100644 --- a/src/Symfony/Component/Console/DependencyInjection/AddConsoleCommandPass.php +++ b/src/Symfony/Component/Console/DependencyInjection/AddConsoleCommandPass.php @@ -87,7 +87,7 @@ public function process(ContainerBuilder $container) $lazyCommandMap[$tag['command']] = $id; } - $description = $description ?? $tag['description'] ?? null; + $description ??= $tag['description'] ?? null; } $definition->addMethodCall('setName', [$commandName]); diff --git a/src/Symfony/Component/Console/Formatter/NullOutputFormatter.php b/src/Symfony/Component/Console/Formatter/NullOutputFormatter.php index d14db326a050d..7950fad1ede30 100644 --- a/src/Symfony/Component/Console/Formatter/NullOutputFormatter.php +++ b/src/Symfony/Component/Console/Formatter/NullOutputFormatter.php @@ -32,7 +32,7 @@ public function format(?string $message): ?string public function getStyle(string $name): OutputFormatterStyleInterface { // to comply with the interface we must return a OutputFormatterStyleInterface - return $this->style ?? $this->style = new NullOutputFormatterStyle(); + return $this->style ??= new NullOutputFormatterStyle(); } /** diff --git a/src/Symfony/Component/Console/Helper/Dumper.php b/src/Symfony/Component/Console/Helper/Dumper.php index 76b76c0a4047d..29263d853e26f 100644 --- a/src/Symfony/Component/Console/Helper/Dumper.php +++ b/src/Symfony/Component/Console/Helper/Dumper.php @@ -34,10 +34,10 @@ public function __construct(OutputInterface $output, CliDumper $dumper = null, C if (class_exists(CliDumper::class)) { $this->handler = function ($var): string { - $dumper = $this->dumper ?? $this->dumper = new CliDumper(null, null, CliDumper::DUMP_LIGHT_ARRAY | CliDumper::DUMP_COMMA_SEPARATOR); + $dumper = $this->dumper ??= new CliDumper(null, null, CliDumper::DUMP_LIGHT_ARRAY | CliDumper::DUMP_COMMA_SEPARATOR); $dumper->setColors($this->output->isDecorated()); - return rtrim($dumper->dump(($this->cloner ?? $this->cloner = new VarCloner())->cloneVar($var)->withRefHandles(false), true)); + return rtrim($dumper->dump(($this->cloner ??= new VarCloner())->cloneVar($var)->withRefHandles(false), true)); }; } else { $this->handler = function ($var): string { diff --git a/src/Symfony/Component/Console/Helper/Helper.php b/src/Symfony/Component/Console/Helper/Helper.php index 01e39a9b38804..44e3199a987c8 100644 --- a/src/Symfony/Component/Console/Helper/Helper.php +++ b/src/Symfony/Component/Console/Helper/Helper.php @@ -45,7 +45,7 @@ public function getHelperSet(): ?HelperSet */ public static function width(?string $string): int { - $string ?? $string = ''; + $string ??= ''; if (preg_match('//u', $string)) { return (new UnicodeString($string))->width(false); @@ -64,7 +64,7 @@ public static function width(?string $string): int */ public static function length(?string $string): int { - $string ?? $string = ''; + $string ??= ''; if (preg_match('//u', $string)) { return (new UnicodeString($string))->length(); @@ -82,7 +82,7 @@ public static function length(?string $string): int */ public static function substr(?string $string, int $from, int $length = null): string { - $string ?? $string = ''; + $string ??= ''; if (false === $encoding = mb_detect_encoding($string, null, true)) { return substr($string, $from, $length); diff --git a/src/Symfony/Component/Console/Input/ArgvInput.php b/src/Symfony/Component/Console/Input/ArgvInput.php index 4e90c812e2cbd..a9585de17e5ca 100644 --- a/src/Symfony/Component/Console/Input/ArgvInput.php +++ b/src/Symfony/Component/Console/Input/ArgvInput.php @@ -45,7 +45,7 @@ class ArgvInput extends Input public function __construct(array $argv = null, InputDefinition $definition = null) { - $argv = $argv ?? $_SERVER['argv'] ?? []; + $argv ??= $_SERVER['argv'] ?? []; // strip the application name array_shift($argv); diff --git a/src/Symfony/Component/Console/Input/InputArgument.php b/src/Symfony/Component/Console/Input/InputArgument.php index f89fa33c97eaf..143e4b10ae71f 100644 --- a/src/Symfony/Component/Console/Input/InputArgument.php +++ b/src/Symfony/Component/Console/Input/InputArgument.php @@ -105,8 +105,6 @@ public function setDefault(string|bool|int|float|array $default = null) /** * Returns the default value. - * - * @return string|bool|int|float|array|null */ public function getDefault(): string|bool|int|float|array|null { diff --git a/src/Symfony/Component/Console/Input/InputOption.php b/src/Symfony/Component/Console/Input/InputOption.php index 613af20353f08..f9d74a8961ce2 100644 --- a/src/Symfony/Component/Console/Input/InputOption.php +++ b/src/Symfony/Component/Console/Input/InputOption.php @@ -187,8 +187,6 @@ public function setDefault(string|bool|int|float|array $default = null) /** * Returns the default value. - * - * @return string|bool|int|float|array|null */ public function getDefault(): string|bool|int|float|array|null { diff --git a/src/Symfony/Component/Console/Question/Question.php b/src/Symfony/Component/Console/Question/Question.php index 7d5e3accb0c05..f25e938a83197 100644 --- a/src/Symfony/Component/Console/Question/Question.php +++ b/src/Symfony/Component/Console/Question/Question.php @@ -52,8 +52,6 @@ public function getQuestion(): string /** * Returns the default answer. - * - * @return string|bool|int|float|null */ public function getDefault(): string|bool|int|float|null { @@ -154,7 +152,7 @@ public function setAutocompleterValues(?iterable $values): static } elseif ($values instanceof \Traversable) { $valueCache = null; $callback = static function () use ($values, &$valueCache) { - return $valueCache ?? $valueCache = iterator_to_array($values, false); + return $valueCache ??= iterator_to_array($values, false); }; } else { $callback = null; diff --git a/src/Symfony/Component/Console/Style/SymfonyStyle.php b/src/Symfony/Component/Console/Style/SymfonyStyle.php index 58640ab5f0f3d..5e0aabb6e7b4d 100644 --- a/src/Symfony/Component/Console/Style/SymfonyStyle.php +++ b/src/Symfony/Component/Console/Style/SymfonyStyle.php @@ -59,7 +59,7 @@ public function __construct(InputInterface $input, OutputInterface $output) /** * Formats a message as a block of text. */ - public function block(string|array $messages, ?string $type = null, string $style = null, string $prefix = ' ', bool $padding = false, bool $escape = true) + public function block(string|array $messages, string $type = null, string $style = null, string $prefix = ' ', bool $padding = false, bool $escape = true) { $messages = \is_array($messages) ? array_values($messages) : [$messages]; diff --git a/src/Symfony/Component/CssSelector/CssSelectorConverter.php b/src/Symfony/Component/CssSelector/CssSelectorConverter.php index a322e93fbb18c..7120a2950e185 100644 --- a/src/Symfony/Component/CssSelector/CssSelectorConverter.php +++ b/src/Symfony/Component/CssSelector/CssSelectorConverter.php @@ -62,6 +62,6 @@ public function __construct(bool $html = true) */ public function toXPath(string $cssExpr, string $prefix = 'descendant-or-self::'): string { - return $this->cache[$prefix][$cssExpr] ?? $this->cache[$prefix][$cssExpr] = $this->translator->cssToXPath($cssExpr, $prefix); + return $this->cache[$prefix][$cssExpr] ??= $this->translator->cssToXPath($cssExpr, $prefix); } } diff --git a/src/Symfony/Component/CssSelector/Parser/Reader.php b/src/Symfony/Component/CssSelector/Parser/Reader.php index f926e605c59fa..c0b6923a4d1f8 100644 --- a/src/Symfony/Component/CssSelector/Parser/Reader.php +++ b/src/Symfony/Component/CssSelector/Parser/Reader.php @@ -60,9 +60,6 @@ public function getOffset(string $string) return false === $position ? false : $position - $this->position; } - /** - * @return array|false - */ public function findPattern(string $pattern): array|false { $source = substr($this->source, $this->position); diff --git a/src/Symfony/Component/DependencyInjection/Argument/ServiceLocator.php b/src/Symfony/Component/DependencyInjection/Argument/ServiceLocator.php index 3d6a8c7fa7413..676d232428f2b 100644 --- a/src/Symfony/Component/DependencyInjection/Argument/ServiceLocator.php +++ b/src/Symfony/Component/DependencyInjection/Argument/ServiceLocator.php @@ -45,6 +45,6 @@ public function get(string $id): mixed */ public function getProvidedServices(): array { - return $this->serviceTypes ?? $this->serviceTypes = array_map(function () { return '?'; }, $this->serviceMap); + return $this->serviceTypes ??= array_map(function () { return '?'; }, $this->serviceMap); } } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/AnalyzeServiceReferencesPass.php b/src/Symfony/Component/DependencyInjection/Compiler/AnalyzeServiceReferencesPass.php index 4f53882d90569..9f3059fbd77be 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/AnalyzeServiceReferencesPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/AnalyzeServiceReferencesPass.php @@ -98,7 +98,7 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed $targetId, $targetDefinition, $value, - $this->lazy || ($this->hasProxyDumper && $targetDefinition && $targetDefinition->isLazy()), + $this->lazy || ($this->hasProxyDumper && $targetDefinition?->isLazy()), ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $value->getInvalidBehavior(), $this->byConstructor ); @@ -110,7 +110,7 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed $targetId, $targetDefinition, $value, - $this->lazy || ($targetDefinition && $targetDefinition->isLazy()), + $this->lazy || $targetDefinition?->isLazy(), true ); } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/CheckTypeDeclarationsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/CheckTypeDeclarationsPass.php index 56c498d75daa4..9b8bef35665bc 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/CheckTypeDeclarationsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/CheckTypeDeclarationsPass.php @@ -160,7 +160,7 @@ private function checkTypeDeclarations(Definition $checkedDefinition, \Reflectio */ private function checkType(Definition $checkedDefinition, mixed $value, \ReflectionParameter $parameter, ?string $envPlaceholderUniquePrefix, \ReflectionType $reflectionType = null): void { - $reflectionType = $reflectionType ?? $parameter->getType(); + $reflectionType ??= $parameter->getType(); if ($reflectionType instanceof \ReflectionUnionType) { foreach ($reflectionType->getTypes() as $t) { diff --git a/src/Symfony/Component/DependencyInjection/Compiler/DecoratorServicePass.php b/src/Symfony/Component/DependencyInjection/Compiler/DecoratorServicePass.php index f5493a88bc5de..a0c45d1cf1a89 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/DecoratorServicePass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/DecoratorServicePass.php @@ -80,7 +80,7 @@ public function process(ContainerBuilder $container) throw new ServiceNotFoundException($inner, $id); } - if ($decoratedDefinition && $decoratedDefinition->isSynthetic()) { + if ($decoratedDefinition?->isSynthetic()) { throw new InvalidArgumentException(sprintf('A synthetic service cannot be decorated: service "%s" cannot decorate "%s".', $id, $inner)); } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/PriorityTaggedServiceTrait.php b/src/Symfony/Component/DependencyInjection/Compiler/PriorityTaggedServiceTrait.php index 0126747f7f781..afc081ec1bad8 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/PriorityTaggedServiceTrait.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/PriorityTaggedServiceTrait.php @@ -68,7 +68,7 @@ private function findAndSortTaggedServices(string|TaggedIteratorArgument $tagNam } elseif (null === $defaultPriority && $defaultPriorityMethod && $class) { $defaultPriority = PriorityTaggedServiceUtil::getDefault($container, $serviceId, $class, $defaultPriorityMethod, $tagName, 'priority', $checkTaggedItem); } - $priority = $priority ?? $defaultPriority ?? $defaultPriority = 0; + $priority ??= $defaultPriority ??= 0; if (null === $indexAttribute && !$defaultIndexMethod && !$needsIndexes) { $services[] = [$priority, ++$i, null, $serviceId, null]; @@ -80,7 +80,7 @@ private function findAndSortTaggedServices(string|TaggedIteratorArgument $tagNam } elseif (null === $defaultIndex && $defaultPriorityMethod && $class) { $defaultIndex = PriorityTaggedServiceUtil::getDefault($container, $serviceId, $class, $defaultIndexMethod ?? 'getDefaultName', $tagName, $indexAttribute, $checkTaggedItem); } - $index = $index ?? $defaultIndex ?? $defaultIndex = $serviceId; + $index ??= $defaultIndex ??= $serviceId; $services[] = [$priority, ++$i, $index, $serviceId, $class]; } @@ -114,9 +114,6 @@ private function findAndSortTaggedServices(string|TaggedIteratorArgument $tagNam */ class PriorityTaggedServiceUtil { - /** - * @return string|int|null - */ public static function getDefault(ContainerBuilder $container, string $serviceId, string $class, string $defaultMethod, string $tagName, ?string $indexAttribute, bool $checkTaggedItem): string|int|null { if (!($r = $container->getReflectionClass($class)) || (!$checkTaggedItem && !$r->hasMethod($defaultMethod))) { diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ResolveInstanceofConditionalsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ResolveInstanceofConditionalsPass.php index b211b84e1336d..a6f5187782f74 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ResolveInstanceofConditionalsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ResolveInstanceofConditionalsPass.php @@ -73,7 +73,7 @@ private function processDefinition(ContainerBuilder $container, string $id, Defi $parent = $definition instanceof ChildDefinition ? $definition->getParent() : null; foreach ($conditionals as $interface => $instanceofDefs) { - if ($interface !== $class && !($reflectionClass ?? $reflectionClass = $container->getReflectionClass($class, false) ?: false)) { + if ($interface !== $class && !($reflectionClass ??= $container->getReflectionClass($class, false) ?: false)) { continue; } diff --git a/src/Symfony/Component/DependencyInjection/Container.php b/src/Symfony/Component/DependencyInjection/Container.php index 0532120adf80b..b9dd8388988b0 100644 --- a/src/Symfony/Component/DependencyInjection/Container.php +++ b/src/Symfony/Component/DependencyInjection/Container.php @@ -380,7 +380,7 @@ final protected function getService(string|false $registry, string $id, ?string return false !== $registry ? $this->{$registry}[$id] ?? null : null; } if (false !== $registry) { - return $this->{$registry}[$id] ?? $this->{$registry}[$id] = $load ? $this->load($method) : $this->{$method}(); + return $this->{$registry}[$id] ??= $load ? $this->load($method) : $this->{$method}(); } if (!$load) { return $this->{$method}(); diff --git a/src/Symfony/Component/DependencyInjection/Definition.php b/src/Symfony/Component/DependencyInjection/Definition.php index dd38841487821..34638059fe86b 100644 --- a/src/Symfony/Component/DependencyInjection/Definition.php +++ b/src/Symfony/Component/DependencyInjection/Definition.php @@ -710,8 +710,6 @@ public function setConfigurator(string|array|Reference|null $configurator): stat /** * Gets the configurator to call after the service is fully initialized. - * - * @return string|array|null */ public function getConfigurator(): string|array|null { diff --git a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php index cbbbcc76d8dac..dd9e2be24dc9f 100644 --- a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php +++ b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php @@ -221,7 +221,7 @@ public function dump(array $options = []): string|array $this->addDefaultParametersMethod() ; - $proxyClasses = $proxyClasses ?? $this->generateProxyClasses(); + $proxyClasses ??= $this->generateProxyClasses(); if ($this->addGetService) { $code = preg_replace( @@ -1802,7 +1802,7 @@ private function dumpValue(mixed $value, bool $interpolate = true): string if ($value->hasErrors() && $e = $value->getErrors()) { return sprintf('throw new RuntimeException(%s)', $this->export(reset($e))); } - if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) { + if ($this->definitionVariables?->contains($value)) { return $this->dumpValue($this->definitionVariables[$value], $interpolate); } if ($value->getMethodCalls()) { diff --git a/src/Symfony/Component/DependencyInjection/Loader/PhpFileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/PhpFileLoader.php index 386f5d7edad89..2bc6484a3d661 100644 --- a/src/Symfony/Component/DependencyInjection/Loader/PhpFileLoader.php +++ b/src/Symfony/Component/DependencyInjection/Loader/PhpFileLoader.php @@ -135,7 +135,7 @@ private function executeCallback(callable $callback, ContainerConfigurator $cont default: try { $configBuilder = $this->configBuilder($type); - } catch (InvalidArgumentException | \LogicException $e) { + } catch (InvalidArgumentException|\LogicException $e) { throw new \InvalidArgumentException(sprintf('Could not resolve argument "%s" for "%s".', $type.' $'.$parameter->getName(), $path), 0, $e); } $configBuilders[] = $configBuilder; diff --git a/src/Symfony/Component/DependencyInjection/ParameterBag/ContainerBag.php b/src/Symfony/Component/DependencyInjection/ParameterBag/ContainerBag.php index b3f23302155b6..40f263cf739ae 100644 --- a/src/Symfony/Component/DependencyInjection/ParameterBag/ContainerBag.php +++ b/src/Symfony/Component/DependencyInjection/ParameterBag/ContainerBag.php @@ -35,8 +35,6 @@ public function all(): array /** * {@inheritdoc} - * - * @return array|bool|string|int|float|null */ public function get(string $name): array|bool|string|int|float|null { diff --git a/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBagInterface.php b/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBagInterface.php index 6b9cc4c951e5c..7e276fd8f35c7 100644 --- a/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBagInterface.php +++ b/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBagInterface.php @@ -43,8 +43,6 @@ public function all(): array; /** * Gets a service container parameter. * - * @return array|bool|string|int|float|null - * * @throws ParameterNotFoundException if the parameter is not defined */ public function get(string $name): array|bool|string|int|float|null; diff --git a/src/Symfony/Component/DomCrawler/Crawler.php b/src/Symfony/Component/DomCrawler/Crawler.php index 8397d75b20f14..ddf437c93ade1 100644 --- a/src/Symfony/Component/DomCrawler/Crawler.php +++ b/src/Symfony/Component/DomCrawler/Crawler.php @@ -629,8 +629,6 @@ public function outerHtml(): string * * Since an XPath expression might evaluate to either a simple type or a \DOMNodeList, * this method will return either an array of simple types or a new Crawler instance. - * - * @return array|Crawler */ public function evaluate(string $xpath): array|Crawler { @@ -1085,11 +1083,11 @@ private function convertToHtmlEntities(string $htmlContent, string $charset = 'U try { return mb_convert_encoding($htmlContent, 'HTML-ENTITIES', $charset); - } catch (\Exception | \ValueError $e) { + } catch (\Exception|\ValueError $e) { try { $htmlContent = iconv($charset, 'UTF-8', $htmlContent); $htmlContent = mb_convert_encoding($htmlContent, 'HTML-ENTITIES', 'UTF-8'); - } catch (\Exception | \ValueError $e) { + } catch (\Exception|\ValueError $e) { } return $htmlContent; diff --git a/src/Symfony/Component/Dotenv/Command/DebugCommand.php b/src/Symfony/Component/Dotenv/Command/DebugCommand.php index 8ceb1fd484845..925d99328eeb9 100644 --- a/src/Symfony/Component/Dotenv/Command/DebugCommand.php +++ b/src/Symfony/Component/Dotenv/Command/DebugCommand.php @@ -91,7 +91,7 @@ private function getVariables(array $envFiles): array $realValue = $_SERVER[$var]; $varDetails = [$var, $realValue]; foreach ($envFiles as $envFile) { - $values = $fileValues[$envFile] ?? $fileValues[$envFile] = $this->loadValues($envFile); + $values = $fileValues[$envFile] ??= $this->loadValues($envFile); $varString = $values[$var] ?? 'n/a'; $shortenedVar = $this->getHelper('formatter')->truncate($varString, 30); diff --git a/src/Symfony/Component/Dotenv/Dotenv.php b/src/Symfony/Component/Dotenv/Dotenv.php index b4beea383f8f3..c12e14406a9e8 100644 --- a/src/Symfony/Component/Dotenv/Dotenv.php +++ b/src/Symfony/Component/Dotenv/Dotenv.php @@ -72,8 +72,8 @@ public function usePutenv(bool $usePutenv = true): static /** * Loads one or several .env files. * - * @param string $path A file to load - * @param ...string $extraPaths A list of additional files to load + * @param string $path A file to load + * @param string[] ...$extraPaths A list of additional files to load * * @throws FormatException when a file has a syntax error * @throws PathException when a file does not exist or is not readable @@ -158,8 +158,8 @@ public function bootEnv(string $path, string $defaultEnv = 'dev', array $testEnv /** * Loads one or several .env files and enables override existing vars. * - * @param string $path A file to load - * @param ...string $extraPaths A list of additional files to load + * @param string $path A file to load + * @param string[] ...$extraPaths A list of additional files to load * * @throws FormatException when a file has a syntax error * @throws PathException when a file does not exist or is not readable @@ -304,7 +304,7 @@ private function lexValue(): string throw $this->createFormatException('Whitespace are not supported before the value'); } - $loadedVars = array_flip(explode(',', $_SERVER['SYMFONY_DOTENV_VARS'] ?? ($_ENV['SYMFONY_DOTENV_VARS'] ?? ''))); + $loadedVars = array_flip(explode(',', $_SERVER['SYMFONY_DOTENV_VARS'] ?? $_ENV['SYMFONY_DOTENV_VARS'] ?? '')); unset($loadedVars['']); $v = ''; diff --git a/src/Symfony/Component/ErrorHandler/DebugClassLoader.php b/src/Symfony/Component/ErrorHandler/DebugClassLoader.php index d9aaa90a0b0f4..85b486a97dede 100644 --- a/src/Symfony/Component/ErrorHandler/DebugClassLoader.php +++ b/src/Symfony/Component/ErrorHandler/DebugClassLoader.php @@ -553,7 +553,7 @@ public function checkAnnotations(\ReflectionClass $refl, string $class): array $this->patchReturnTypeWillChange($method); } - if (null !== ($returnType ?? $returnType = self::MAGIC_METHODS[$method->name] ?? null) && !$method->hasReturnType() && !isset($doc['return'])) { + if (null !== ($returnType ??= self::MAGIC_METHODS[$method->name] ?? null) && !$method->hasReturnType() && !isset($doc['return'])) { [$normalizedType, $returnType, $declaringClass, $declaringFile] = \is_string($returnType) ? [$returnType, $returnType, '', ''] : $returnType; if ($canAddReturnType && 'docblock' !== $this->patchTypes['force']) { @@ -935,10 +935,10 @@ private function patchMethod(\ReflectionMethod $method, string $returnType, stri continue; } - [$namespace, $useOffset, $useMap] = $useStatements[$file] ?? $useStatements[$file] = self::getUseStatements($file); + [$namespace, $useOffset, $useMap] = $useStatements[$file] ??= self::getUseStatements($file); if ('\\' !== $type[0]) { - [$declaringNamespace, , $declaringUseMap] = $useStatements[$declaringFile] ?? $useStatements[$declaringFile] = self::getUseStatements($declaringFile); + [$declaringNamespace, , $declaringUseMap] = $useStatements[$declaringFile] ??= self::getUseStatements($declaringFile); $p = strpos($type, '\\', 1); $alias = $p ? substr($type, 0, $p) : $type; diff --git a/src/Symfony/Component/ErrorHandler/Resources/bin/extract-tentative-return-types.php b/src/Symfony/Component/ErrorHandler/Resources/bin/extract-tentative-return-types.php index a4d2c201c04da..cc98f58b58fa0 100755 --- a/src/Symfony/Component/ErrorHandler/Resources/bin/extract-tentative-return-types.php +++ b/src/Symfony/Component/ErrorHandler/Resources/bin/extract-tentative-return-types.php @@ -40,7 +40,7 @@ class TentativeTypes EOPHP; -while (false !== $file = fgets(STDIN)) { +while (false !== $file = fgets(\STDIN)) { $code = file_get_contents(substr($file, 0, -1)); if (!str_contains($code, '@tentative-return-type')) { diff --git a/src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php b/src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php index e375f7a1bd517..ddbc588c6ba54 100644 --- a/src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php +++ b/src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php @@ -131,7 +131,7 @@ public function hasListeners(string $eventName = null): bool */ public function dispatch(object $event, string $eventName = null): object { - $eventName = $eventName ?? \get_class($event); + $eventName ??= \get_class($event); if (null === $this->callStack) { $this->callStack = new \SplObjectStorage(); diff --git a/src/Symfony/Component/EventDispatcher/EventDispatcher.php b/src/Symfony/Component/EventDispatcher/EventDispatcher.php index 33d91b7d28e3d..c9cfd64a75258 100644 --- a/src/Symfony/Component/EventDispatcher/EventDispatcher.php +++ b/src/Symfony/Component/EventDispatcher/EventDispatcher.php @@ -47,7 +47,7 @@ public function __construct() */ public function dispatch(object $event, string $eventName = null): object { - $eventName = $eventName ?? \get_class($event); + $eventName ??= \get_class($event); if (isset($this->optimized)) { $listeners = $this->optimized[$eventName] ?? (empty($this->listeners[$eventName]) ? [] : $this->optimizeListeners($eventName)); @@ -99,14 +99,14 @@ public function getListenerPriority(string $eventName, callable|array $listener) if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure && 2 >= \count($listener)) { $listener[0] = $listener[0](); - $listener[1] = $listener[1] ?? '__invoke'; + $listener[1] ??= '__invoke'; } foreach ($this->listeners[$eventName] as $priority => &$listeners) { foreach ($listeners as &$v) { if ($v !== $listener && \is_array($v) && isset($v[0]) && $v[0] instanceof \Closure && 2 >= \count($v)) { $v[0] = $v[0](); - $v[1] = $v[1] ?? '__invoke'; + $v[1] ??= '__invoke'; } if ($v === $listener) { return $priority; @@ -155,14 +155,14 @@ public function removeListener(string $eventName, callable|array $listener) if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure && 2 >= \count($listener)) { $listener[0] = $listener[0](); - $listener[1] = $listener[1] ?? '__invoke'; + $listener[1] ??= '__invoke'; } foreach ($this->listeners[$eventName] as $priority => &$listeners) { foreach ($listeners as $k => &$v) { if ($v !== $listener && \is_array($v) && isset($v[0]) && $v[0] instanceof \Closure && 2 >= \count($v)) { $v[0] = $v[0](); - $v[1] = $v[1] ?? '__invoke'; + $v[1] ??= '__invoke'; } if ($v === $listener) { unset($listeners[$k], $this->sorted[$eventName], $this->optimized[$eventName]); @@ -243,7 +243,7 @@ private function sortListeners(string $eventName) foreach ($listeners as $k => &$listener) { if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure && 2 >= \count($listener)) { $listener[0] = $listener[0](); - $listener[1] = $listener[1] ?? '__invoke'; + $listener[1] ??= '__invoke'; } $this->sorted[$eventName][] = $listener; } @@ -265,7 +265,7 @@ private function optimizeListeners(string $eventName): array $closure = static function (...$args) use (&$listener, &$closure) { if ($listener[0] instanceof \Closure) { $listener[0] = $listener[0](); - $listener[1] = $listener[1] ?? '__invoke'; + $listener[1] ??= '__invoke'; } ($closure = \Closure::fromCallable($listener))(...$args); }; diff --git a/src/Symfony/Component/Form/Button.php b/src/Symfony/Component/Form/Button.php index 92d00ee14554f..7c80d03e341ec 100644 --- a/src/Symfony/Component/Form/Button.php +++ b/src/Symfony/Component/Form/Button.php @@ -271,7 +271,7 @@ public function isRequired(): bool */ public function isDisabled(): bool { - if ($this->parent && $this->parent->isDisabled()) { + if ($this->parent?->isDisabled()) { return true; } diff --git a/src/Symfony/Component/Form/Command/DebugCommand.php b/src/Symfony/Component/Form/Command/DebugCommand.php index d5545a67042c8..c58dc2217d339 100644 --- a/src/Symfony/Component/Form/Command/DebugCommand.php +++ b/src/Symfony/Component/Form/Command/DebugCommand.php @@ -275,7 +275,7 @@ private function completeOptions(string $class, CompletionSuggestions $suggestio if (!class_exists($class) || !is_subclass_of($class, FormTypeInterface::class)) { $classes = $this->getFqcnTypeClasses($class); - if (1 === count($classes)) { + if (1 === \count($classes)) { $class = $classes[0]; } } diff --git a/src/Symfony/Component/Form/Extension/DataCollector/FormDataCollector.php b/src/Symfony/Component/Form/Extension/DataCollector/FormDataCollector.php index 023a63fe174df..f4640f1ff07b1 100644 --- a/src/Symfony/Component/Form/Extension/DataCollector/FormDataCollector.php +++ b/src/Symfony/Component/Form/Extension/DataCollector/FormDataCollector.php @@ -326,9 +326,7 @@ private function &recursiveBuildFinalFormTree(FormInterface $form = null, FormVi foreach ($view->children as $name => $childView) { // The CSRF token, for example, is never added to the form tree. // It is only present in the view. - $childForm = null !== $form && $form->has($name) - ? $form->get($name) - : null; + $childForm = $form?->has($name) ? $form->get($name) : null; $output['children'][$name] = &$this->recursiveBuildFinalFormTree($childForm, $childView, $outputByHash); } diff --git a/src/Symfony/Component/Form/Extension/DataCollector/FormDataCollectorInterface.php b/src/Symfony/Component/Form/Extension/DataCollector/FormDataCollectorInterface.php index f51773e405c63..0e1d32bfc857c 100644 --- a/src/Symfony/Component/Form/Extension/DataCollector/FormDataCollectorInterface.php +++ b/src/Symfony/Component/Form/Extension/DataCollector/FormDataCollectorInterface.php @@ -78,8 +78,6 @@ public function buildFinalFormTree(FormInterface $form, FormView $view); /** * Returns all collected data. - * - * @return array|Data */ public function getData(): array|Data; } diff --git a/src/Symfony/Component/Form/Form.php b/src/Symfony/Component/Form/Form.php index bed1fcb6c376c..394f6a89f2b19 100644 --- a/src/Symfony/Component/Form/Form.php +++ b/src/Symfony/Component/Form/Form.php @@ -196,7 +196,7 @@ public function getPropertyPath(): ?PropertyPathInterface $parent = $this->parent; - while ($parent && $parent->getConfig()->getInheritData()) { + while ($parent?->getConfig()->getInheritData()) { $parent = $parent->getParent(); } @@ -727,8 +727,6 @@ public function isValid(): bool /** * Returns the button that was used to submit the form. - * - * @return FormInterface|ClickableInterface|null */ public function getClickedButton(): FormInterface|ClickableInterface|null { diff --git a/src/Symfony/Component/Form/Guess/ValueGuess.php b/src/Symfony/Component/Form/Guess/ValueGuess.php index ddc8b53dd5e1f..36abe6602d723 100644 --- a/src/Symfony/Component/Form/Guess/ValueGuess.php +++ b/src/Symfony/Component/Form/Guess/ValueGuess.php @@ -32,8 +32,6 @@ public function __construct(string|int|bool|null $value, int $confidence) /** * Returns the guessed value. - * - * @return string|int|bool|null */ public function getValue(): string|int|bool|null { diff --git a/src/Symfony/Component/HttpClient/HttpClient.php b/src/Symfony/Component/HttpClient/HttpClient.php index c3f9583d1c0ec..dd4acf89c8b36 100644 --- a/src/Symfony/Component/HttpClient/HttpClient.php +++ b/src/Symfony/Component/HttpClient/HttpClient.php @@ -41,10 +41,10 @@ public static function create(array $defaultOptions = [], int $maxHostConnection } static $curlVersion = null; - $curlVersion = $curlVersion ?? curl_version(); + $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); } } diff --git a/src/Symfony/Component/HttpClient/HttpClientTrait.php b/src/Symfony/Component/HttpClient/HttpClientTrait.php index cecb1c0d9220d..08724df555919 100644 --- a/src/Symfony/Component/HttpClient/HttpClientTrait.php +++ b/src/Symfony/Component/HttpClient/HttpClientTrait.php @@ -186,7 +186,7 @@ private static function mergeDefaultOptions(array $options, array $defaultOption } // Option "query" is never inherited from defaults - $options['query'] = $options['query'] ?? []; + $options['query'] ??= []; foreach ($defaultOptions as $k => $v) { if ('normalized_headers' !== $k && !isset($options[$k])) { @@ -381,7 +381,7 @@ private static function normalizePeerFingerprint(mixed $fingerprint): array */ private static function jsonEncode(mixed $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 ??= \JSON_HEX_TAG | \JSON_HEX_APOS | \JSON_HEX_AMP | \JSON_HEX_QUOT | \JSON_PRESERVE_ZERO_FRACTION; try { $value = json_encode($value, $flags | \JSON_THROW_ON_ERROR, $maxDepth); @@ -421,7 +421,7 @@ private static function resolveUrl(array $url, ?array $base, array $queryDefault } else { if (null === $url['path']) { $url['path'] = $base['path']; - $url['query'] = $url['query'] ?? $base['query']; + $url['query'] ??= $base['query']; } else { if ('/' !== $url['path'][0]) { if (null === $base['path']) { @@ -617,7 +617,7 @@ private static function getProxy(?string $proxy, array $url, ?string $noProxy): throw new TransportException(sprintf('Unsupported proxy scheme "%s": "http" or "https" expected.', $proxy['scheme'])); } - $noProxy = $noProxy ?? $_SERVER['no_proxy'] ?? $_SERVER['NO_PROXY'] ?? ''; + $noProxy ??= $_SERVER['no_proxy'] ?? $_SERVER['NO_PROXY'] ?? ''; $noProxy = $noProxy ? preg_split('/[\s,]+/', $noProxy) : []; return [ diff --git a/src/Symfony/Component/HttpClient/Response/AmpResponse.php b/src/Symfony/Component/HttpClient/Response/AmpResponse.php index 72d644e2b1a3a..6a28e55a80f58 100644 --- a/src/Symfony/Component/HttpClient/Response/AmpResponse.php +++ b/src/Symfony/Component/HttpClient/Response/AmpResponse.php @@ -309,7 +309,7 @@ private static function followRedirects(Request $originRequest, AmpClientState $ }; try { - $previousUrl = $previousUrl ?? $urlResolver::parseUrl($info['url']); + $previousUrl ??= $urlResolver::parseUrl($info['url']); $location = $urlResolver::parseUrl($location); $location = $urlResolver::resolveUrl($location, $previousUrl); $info['redirect_url'] = implode('', $location); @@ -327,7 +327,7 @@ private static function followRedirects(Request $originRequest, AmpClientState $ // Discard body of redirects while (null !== yield $response->getBody()->read()) { } - } catch (HttpException | StreamException $e) { + } catch (HttpException|StreamException $e) { // Ignore streaming errors on previous responses } diff --git a/src/Symfony/Component/HttpClient/Response/NativeResponse.php b/src/Symfony/Component/HttpClient/Response/NativeResponse.php index 933a87f63109a..b79d3cc03a54a 100644 --- a/src/Symfony/Component/HttpClient/Response/NativeResponse.php +++ b/src/Symfony/Component/HttpClient/Response/NativeResponse.php @@ -364,7 +364,7 @@ private static function select(ClientState $multi, float $timeout): int continue; } - if ($pauseExpiry && ($now ?? $now = microtime(true)) < $pauseExpiry) { + if ($pauseExpiry && ($now ??= microtime(true)) < $pauseExpiry) { $timeout = min($timeout, $pauseExpiry - $now); continue; } diff --git a/src/Symfony/Component/HttpClient/Response/TraceableResponse.php b/src/Symfony/Component/HttpClient/Response/TraceableResponse.php index 1549a6178090e..4d665f4d8c7f4 100644 --- a/src/Symfony/Component/HttpClient/Response/TraceableResponse.php +++ b/src/Symfony/Component/HttpClient/Response/TraceableResponse.php @@ -59,7 +59,7 @@ public function __destruct() try { $this->response->__destruct(); } finally { - if ($this->event && $this->event->isStarted()) { + if ($this->event?->isStarted()) { $this->event->stop(); } } @@ -70,7 +70,7 @@ public function getStatusCode(): int try { return $this->response->getStatusCode(); } finally { - if ($this->event && $this->event->isStarted()) { + if ($this->event?->isStarted()) { $this->event->lap(); } } @@ -81,7 +81,7 @@ public function getHeaders(bool $throw = true): array try { return $this->response->getHeaders($throw); } finally { - if ($this->event && $this->event->isStarted()) { + if ($this->event?->isStarted()) { $this->event->lap(); } } @@ -96,7 +96,7 @@ public function getContent(bool $throw = true): string return $this->content = $this->response->getContent(false); } finally { - if ($this->event && $this->event->isStarted()) { + if ($this->event?->isStarted()) { $this->event->stop(); } if ($throw) { @@ -114,7 +114,7 @@ public function toArray(bool $throw = true): array return $this->content = $this->response->toArray(false); } finally { - if ($this->event && $this->event->isStarted()) { + if ($this->event?->isStarted()) { $this->event->stop(); } if ($throw) { @@ -127,7 +127,7 @@ public function cancel(): void { $this->response->cancel(); - if ($this->event && $this->event->isStarted()) { + if ($this->event?->isStarted()) { $this->event->stop(); } } diff --git a/src/Symfony/Component/HttpClient/Response/TransportResponseTrait.php b/src/Symfony/Component/HttpClient/Response/TransportResponseTrait.php index 97b149966ab11..c639eb9fcd1c6 100644 --- a/src/Symfony/Component/HttpClient/Response/TransportResponseTrait.php +++ b/src/Symfony/Component/HttpClient/Response/TransportResponseTrait.php @@ -191,7 +191,7 @@ public static function stream(iterable $responses, float $timeout = null): \Gene continue; } elseif ($elapsedTimeout >= $timeoutMax) { $multi->handlesActivity[$j] = [new ErrorChunk($response->offset, sprintf('Idle timeout reached for "%s".', $response->getInfo('url')))]; - $multi->lastTimeout ?? $multi->lastTimeout = $lastActivity; + $multi->lastTimeout ??= $lastActivity; } else { continue; } diff --git a/src/Symfony/Component/HttpClient/Tests/AsyncDecoratorTraitTest.php b/src/Symfony/Component/HttpClient/Tests/AsyncDecoratorTraitTest.php index 0dfca6d4a2f97..820efde4d9211 100644 --- a/src/Symfony/Component/HttpClient/Tests/AsyncDecoratorTraitTest.php +++ b/src/Symfony/Component/HttpClient/Tests/AsyncDecoratorTraitTest.php @@ -34,7 +34,7 @@ protected function getHttpClient(string $testCase, \Closure $chunkFilter = null, return HttpClient::create(); } - $chunkFilter = $chunkFilter ?? static function (ChunkInterface $chunk, AsyncContext $context) { yield $chunk; }; + $chunkFilter ??= static function (ChunkInterface $chunk, AsyncContext $context) { yield $chunk; }; return new class($decoratedClient ?? parent::getHttpClient($testCase), $chunkFilter) implements HttpClientInterface { use AsyncDecoratorTrait; diff --git a/src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php b/src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php index 8c0c77959fb2e..cf6e5f421a24c 100644 --- a/src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php +++ b/src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php @@ -23,7 +23,7 @@ class CurlHttpClientTest extends HttpClientTestCase protected function getHttpClient(string $testCase): HttpClientInterface { if (str_contains($testCase, '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'); } } diff --git a/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php b/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php index 96f0a64c3bb0e..5f20e1989dfa1 100755 --- a/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php +++ b/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php @@ -218,4 +218,18 @@ public function testStopwatchDestruct() $this->assertCount(1, $events['GET http://localhost:8057']->getPeriods()); $this->assertGreaterThan(0.0, $events['GET http://localhost:8057']->getDuration()); } + + public function testWithOptions() + { + $sut = new TraceableHttpClient(new NativeHttpClient()); + + $sut2 = $sut->withOptions(['base_uri' => 'http://localhost:8057']); + + $response = $sut2->request('GET', '/'); + + $this->assertSame(200, $response->getStatusCode()); + $this->assertSame('http://localhost:8057/', $response->getInfo('url')); + + $this->assertCount(1, $sut->getTracedRequests()); + } } diff --git a/src/Symfony/Component/HttpClient/TraceableHttpClient.php b/src/Symfony/Component/HttpClient/TraceableHttpClient.php index 8872d16ed5aef..a89cfc94d50c3 100644 --- a/src/Symfony/Component/HttpClient/TraceableHttpClient.php +++ b/src/Symfony/Component/HttpClient/TraceableHttpClient.php @@ -27,13 +27,14 @@ final class TraceableHttpClient implements HttpClientInterface, ResetInterface, LoggerAwareInterface { private HttpClientInterface $client; - private array $tracedRequests = []; private ?Stopwatch $stopwatch; + private \ArrayObject $tracedRequests; public function __construct(HttpClientInterface $client, Stopwatch $stopwatch = null) { $this->client = $client; $this->stopwatch = $stopwatch; + $this->tracedRequests = new \ArrayObject(); } /** @@ -82,7 +83,7 @@ public function stream(ResponseInterface|iterable $responses, float $timeout = n public function getTracedRequests(): array { - return $this->tracedRequests; + return $this->tracedRequests->getArrayCopy(); } public function reset() @@ -91,7 +92,7 @@ public function reset() $this->client->reset(); } - $this->tracedRequests = []; + $this->tracedRequests->exchangeArray([]); } /** diff --git a/src/Symfony/Component/HttpFoundation/Response.php b/src/Symfony/Component/HttpFoundation/Response.php index 70da218aa92ca..accacff8e549b 100644 --- a/src/Symfony/Component/HttpFoundation/Response.php +++ b/src/Symfony/Component/HttpFoundation/Response.php @@ -397,8 +397,6 @@ public function setContent(?string $content): static /** * Gets the current response content. - * - * @return string|false */ public function getContent(): string|false { diff --git a/src/Symfony/Component/HttpFoundation/Session/Session.php b/src/Symfony/Component/HttpFoundation/Session/Session.php index 1a0230bac516f..35070051bb195 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Session.php +++ b/src/Symfony/Component/HttpFoundation/Session/Session.php @@ -45,11 +45,11 @@ public function __construct(SessionStorageInterface $storage = null, AttributeBa $this->storage = $storage ?? new NativeSessionStorage(); $this->usageReporter = $usageReporter instanceof \Closure || !\is_callable($usageReporter) ? $usageReporter : \Closure::fromCallable($usageReporter); - $attributes = $attributes ?? new AttributeBag(); + $attributes ??= new AttributeBag(); $this->attributeName = $attributes->getName(); $this->registerBag($attributes); - $flashes = $flashes ?? new FlashBag(); + $flashes ??= new FlashBag(); $this->flashName = $flashes->getName(); $this->registerBag($flashes); } diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php index 843fedf0e493b..9ef1c496e1153 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php @@ -454,7 +454,7 @@ private function buildDsnFromUrl(string $dsnOrUrl): string // If "unix_socket" is not in the query, we continue with the same process as pgsql // no break case 'pgsql': - $dsn ?? $dsn = 'pgsql:'; + $dsn ??= 'pgsql:'; if (isset($params['host']) && '' !== $params['host']) { $dsn .= 'host='.$params['host'].';'; @@ -582,7 +582,7 @@ protected function doRead(string $sessionId): string $selectStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); $insertStmt = null; - do { + while (true) { $selectStmt->execute(); $sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM); @@ -628,7 +628,7 @@ protected function doRead(string $sessionId): string } return ''; - } while (true); + } } /** diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php index eb3210d4a4b1f..09b33d5b18fa7 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php @@ -112,8 +112,6 @@ public function __construct(array $options = [], AbstractProxy|\SessionHandlerIn /** * Gets the save handler instance. - * - * @return AbstractProxy|\SessionHandlerInterface */ public function getSaveHandler(): AbstractProxy|\SessionHandlerInterface { diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorageFactory.php b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorageFactory.php index ecbd6feb7bc09..08901284c33a2 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorageFactory.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorageFactory.php @@ -41,7 +41,7 @@ public function __construct(array $options = [], AbstractProxy|\SessionHandlerIn public function createStorage(?Request $request): SessionStorageInterface { $storage = new NativeSessionStorage($this->options, $this->handler, $this->metaBag); - if ($this->secure && $request && $request->isSecure()) { + if ($this->secure && $request?->isSecure()) { $storage->setOptions(['cookie_secure' => true]); } diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/PhpBridgeSessionStorageFactory.php b/src/Symfony/Component/HttpFoundation/Session/Storage/PhpBridgeSessionStorageFactory.php index 6d729cc66c16e..5cc73802422f3 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/PhpBridgeSessionStorageFactory.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/PhpBridgeSessionStorageFactory.php @@ -36,7 +36,7 @@ public function __construct(AbstractProxy|\SessionHandlerInterface $handler = nu public function createStorage(?Request $request): SessionStorageInterface { $storage = new PhpBridgeSessionStorage($this->handler, $this->metaBag); - if ($this->secure && $request && $request->isSecure()) { + if ($this->secure && $request?->isSecure()) { $storage->setOptions(['cookie_secure' => true]); } diff --git a/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php b/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php index e2626e0bb2c86..c9b5003c4d113 100644 --- a/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php +++ b/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php @@ -45,7 +45,7 @@ public function getController(Request $request): callable|false if (isset($controller[0]) && \is_string($controller[0]) && isset($controller[1])) { try { $controller[0] = $this->instantiateController($controller[0]); - } catch (\Error | \LogicException $e) { + } catch (\Error|\LogicException $e) { if (\is_callable($controller)) { return $controller; } @@ -107,7 +107,7 @@ protected function createController(string $controller): callable try { $controller = [$this->instantiateController($class), $method]; - } catch (\Error | \LogicException $e) { + } catch (\Error|\LogicException $e) { try { if ((new \ReflectionMethod($class, $method))->isStatic()) { return $class.'::'.$method; diff --git a/src/Symfony/Component/HttpKernel/DataCollector/ExceptionDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/ExceptionDataCollector.php index ce05e70a8cdb7..382e2dc40df9a 100644 --- a/src/Symfony/Component/HttpKernel/DataCollector/ExceptionDataCollector.php +++ b/src/Symfony/Component/HttpKernel/DataCollector/ExceptionDataCollector.php @@ -47,9 +47,6 @@ public function hasException(): bool return isset($this->data['exception']); } - /** - * @return \Exception|FlattenException - */ public function getException(): \Exception|FlattenException { return $this->data['exception']; diff --git a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php index b3c9c786721f4..1ff67e4f7d7bb 100644 --- a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php +++ b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php @@ -110,7 +110,7 @@ public function collect(Request $request, Response $response, \Throwable $except 'session_metadata' => $sessionMetadata, 'session_attributes' => $sessionAttributes, 'session_usages' => array_values($this->sessionUsages), - 'stateless_check' => $this->requestStack && $this->requestStack->getMainRequest()->attributes->get('_stateless', false), + 'stateless_check' => $this->requestStack?->getMainRequest()->attributes->get('_stateless') ?? false, 'flashes' => $flashes, 'path_info' => $request->getPathInfo(), 'controller' => 'n/a', diff --git a/src/Symfony/Component/HttpKernel/EventListener/AbstractSessionListener.php b/src/Symfony/Component/HttpKernel/EventListener/AbstractSessionListener.php index 75c78703ff199..2312cf868d4a7 100644 --- a/src/Symfony/Component/HttpKernel/EventListener/AbstractSessionListener.php +++ b/src/Symfony/Component/HttpKernel/EventListener/AbstractSessionListener.php @@ -209,11 +209,11 @@ public function onSessionUsage(): void return; } - if ($this->container && $this->container->has('session_collector')) { + if ($this->container?->has('session_collector')) { $this->container->get('session_collector')(); } - if (!$requestStack = $this->container && $this->container->has('request_stack') ? $this->container->get('request_stack') : null) { + if (!$requestStack = $this->container?->has('request_stack') ? $this->container->get('request_stack') : null) { return; } diff --git a/src/Symfony/Component/HttpKernel/EventListener/DebugHandlersListener.php b/src/Symfony/Component/HttpKernel/EventListener/DebugHandlersListener.php index 4726a069783a8..2bfd139b8421b 100644 --- a/src/Symfony/Component/HttpKernel/EventListener/DebugHandlersListener.php +++ b/src/Symfony/Component/HttpKernel/EventListener/DebugHandlersListener.php @@ -55,7 +55,7 @@ public function __construct(callable $exceptionHandler = null, LoggerInterface $ $this->earlyHandler = \is_array($handler) ? $handler[0] : null; restore_exception_handler(); - $this->exceptionHandler = $exceptionHandler === null || $exceptionHandler instanceof \Closure ? $exceptionHandler : \Closure::fromCallable($exceptionHandler); + $this->exceptionHandler = null === $exceptionHandler || $exceptionHandler instanceof \Closure ? $exceptionHandler : \Closure::fromCallable($exceptionHandler); $this->logger = $logger; $this->levels = $levels ?? \E_ALL; $this->throwAt = \is_int($throwAt) ? $throwAt : (null === $throwAt ? null : ($throwAt ? \E_ALL : null)); diff --git a/src/Symfony/Component/HttpKernel/EventListener/ErrorListener.php b/src/Symfony/Component/HttpKernel/EventListener/ErrorListener.php index d8d7060eaba52..8bac8afe268e9 100644 --- a/src/Symfony/Component/HttpKernel/EventListener/ErrorListener.php +++ b/src/Symfony/Component/HttpKernel/EventListener/ErrorListener.php @@ -19,6 +19,7 @@ use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent; use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\KernelEvents; @@ -46,6 +47,7 @@ public function logKernelException(ExceptionEvent $event) { $throwable = $event->getThrowable(); $logLevel = null; + foreach ($this->exceptionsMapping as $class => $config) { if ($throwable instanceof $class && $config['log_level']) { $logLevel = $config['log_level']; @@ -53,6 +55,18 @@ public function logKernelException(ExceptionEvent $event) } } + foreach ($this->exceptionsMapping as $class => $config) { + if (!$throwable instanceof $class || !$config['status_code']) { + continue; + } + if (!$throwable instanceof HttpExceptionInterface || $throwable->getStatusCode() !== $config['status_code']) { + $headers = $throwable instanceof HttpExceptionInterface ? $throwable->getHeaders() : []; + $throwable = new HttpException($config['status_code'], $throwable->getMessage(), $throwable, $headers); + $event->setThrowable($throwable); + } + break; + } + $e = FlattenException::createFromThrowable($throwable); $this->logException($throwable, sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', $e->getClass(), $e->getMessage(), $e->getFile(), $e->getLine()), $logLevel); @@ -88,13 +102,6 @@ public function onKernelException(ExceptionEvent $event) throw $e; } - foreach ($this->exceptionsMapping as $exception => $config) { - if ($throwable instanceof $exception && $config['status_code']) { - $response->setStatusCode($config['status_code']); - break; - } - } - $event->setResponse($response); if ($this->debug) { diff --git a/src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php b/src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php index adbe05d2bb6c1..cf0e243c6bc5e 100644 --- a/src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php +++ b/src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php @@ -633,7 +633,7 @@ private function restoreResponseBody(Request $request, Response $response) protected function processResponseBody(Request $request, Response $response) { - if (null !== $this->surrogate && $this->surrogate->needsParsing($response)) { + if ($this->surrogate?->needsParsing($response)) { $this->surrogate->process($request, $response); } } diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/ErrorListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/ErrorListenerTest.php index 2c8d725466e20..00a6bde9004ce 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/ErrorListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/ErrorListenerTest.php @@ -22,6 +22,7 @@ use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\HttpKernel\Event\ResponseEvent; use Symfony\Component\HttpKernel\EventListener\ErrorListener; +use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; @@ -231,6 +232,11 @@ class TestKernel implements HttpKernelInterface { public function handle(Request $request, $type = self::MAIN_REQUEST, $catch = true): Response { + $e = $request->attributes->get('exception'); + if ($e instanceof HttpExceptionInterface) { + return new Response('foo', $e->getStatusCode(), $e->getHeaders()); + } + return new Response('foo'); } } diff --git a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Query.php b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Query.php index b028d7f089340..997b21be1c055 100644 --- a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Query.php +++ b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Query.php @@ -204,11 +204,6 @@ private function resetPagination() /** * Sets LDAP pagination controls. -<<<<<<< HEAD -======= - * - * @param resource|LDAPConnection $con ->>>>>>> 5.4 */ private function controlPagedResult(int $pageSize, bool $critical, string $cookie): bool { diff --git a/src/Symfony/Component/Ldap/Security/LdapAuthenticator.php b/src/Symfony/Component/Ldap/Security/LdapAuthenticator.php index a14446493bf77..27ea288824fc3 100644 --- a/src/Symfony/Component/Ldap/Security/LdapAuthenticator.php +++ b/src/Symfony/Component/Ldap/Security/LdapAuthenticator.php @@ -16,8 +16,8 @@ use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface; -use Symfony\Component\Security\Http\Authenticator\Passport\Passport; use Symfony\Component\Security\Http\Authenticator\InteractiveAuthenticatorInterface; +use Symfony\Component\Security\Http\Authenticator\Passport\Passport; use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; use Symfony\Component\Security\Http\EntryPoint\Exception\NotAnEntryPointException; diff --git a/src/Symfony/Component/Mailer/Bridge/Amazon/Transport/SesTransportFactory.php b/src/Symfony/Component/Mailer/Bridge/Amazon/Transport/SesTransportFactory.php index 65cb3db970c5e..fc69010b1336e 100644 --- a/src/Symfony/Component/Mailer/Bridge/Amazon/Transport/SesTransportFactory.php +++ b/src/Symfony/Component/Mailer/Bridge/Amazon/Transport/SesTransportFactory.php @@ -45,7 +45,7 @@ public function create(Dsn $dsn): TransportInterface // no break case 'ses': case 'ses+https': - $class = $class ?? SesHttpAsyncAwsTransport::class; + $class ??= SesHttpAsyncAwsTransport::class; $options = [ 'region' => $dsn->getOption('region') ?: 'eu-west-1', 'accessKeyId' => $dsn->getUser(), diff --git a/src/Symfony/Component/Mailer/Test/TransportFactoryTestCase.php b/src/Symfony/Component/Mailer/Test/TransportFactoryTestCase.php index c2426a0bf27db..1cf22e9b6ca29 100644 --- a/src/Symfony/Component/Mailer/Test/TransportFactoryTestCase.php +++ b/src/Symfony/Component/Mailer/Test/TransportFactoryTestCase.php @@ -102,16 +102,16 @@ public function testIncompleteDsnException(Dsn $dsn) protected function getDispatcher(): EventDispatcherInterface { - return $this->dispatcher ?? $this->dispatcher = $this->createMock(EventDispatcherInterface::class); + return $this->dispatcher ??= $this->createMock(EventDispatcherInterface::class); } protected function getClient(): HttpClientInterface { - return $this->client ?? $this->client = $this->createMock(HttpClientInterface::class); + return $this->client ??= $this->createMock(HttpClientInterface::class); } protected function getLogger(): LoggerInterface { - return $this->logger ?? $this->logger = $this->createMock(LoggerInterface::class); + return $this->logger ??= $this->createMock(LoggerInterface::class); } } diff --git a/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Tests/Transport/AmazonSqsTransportTest.php b/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Tests/Transport/AmazonSqsTransportTest.php index 8e7b152732b98..541b543f699d0 100644 --- a/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Tests/Transport/AmazonSqsTransportTest.php +++ b/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Tests/Transport/AmazonSqsTransportTest.php @@ -169,8 +169,8 @@ public function testItConvertsHttpExceptionDuringResetIntoTransportException() private function getTransport(SerializerInterface $serializer = null, Connection $connection = null) { - $serializer = $serializer ?? $this->createMock(SerializerInterface::class); - $connection = $connection ?? $this->createMock(Connection::class); + $serializer ??= $this->createMock(SerializerInterface::class); + $connection ??= $this->createMock(Connection::class); return new AmazonSqsTransport($connection, $serializer); } diff --git a/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Transport/AmazonSqsTransport.php b/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Transport/AmazonSqsTransport.php index f6e440d49e438..297fccbd3f077 100644 --- a/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Transport/AmazonSqsTransport.php +++ b/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Transport/AmazonSqsTransport.php @@ -33,6 +33,9 @@ class AmazonSqsTransport implements TransportInterface, SetupableTransportInterf private ?ReceiverInterface $receiver; private ?SenderInterface $sender; + /** + * @param MessageCountAwareInterface&ReceiverInterface|null $receiver + */ public function __construct(Connection $connection, SerializerInterface $serializer = null, ReceiverInterface $receiver = null, SenderInterface $sender = null) { $this->connection = $connection; @@ -46,7 +49,7 @@ public function __construct(Connection $connection, SerializerInterface $seriali */ public function get(): iterable { - return ($this->receiver ?? $this->getReceiver())->get(); + return $this->getReceiver()->get(); } /** @@ -54,7 +57,7 @@ public function get(): iterable */ public function ack(Envelope $envelope): void { - ($this->receiver ?? $this->getReceiver())->ack($envelope); + $this->getReceiver()->ack($envelope); } /** @@ -62,7 +65,7 @@ public function ack(Envelope $envelope): void */ public function reject(Envelope $envelope): void { - ($this->receiver ?? $this->getReceiver())->reject($envelope); + $this->getReceiver()->reject($envelope); } /** @@ -70,7 +73,7 @@ public function reject(Envelope $envelope): void */ public function getMessageCount(): int { - return ($this->receiver ?? $this->getReceiver())->getMessageCount(); + return $this->getReceiver()->getMessageCount(); } /** @@ -78,7 +81,7 @@ public function getMessageCount(): int */ public function send(Envelope $envelope): Envelope { - return ($this->sender ?? $this->getSender())->send($envelope); + return $this->getSender()->send($envelope); } /** @@ -102,13 +105,16 @@ public function reset() } } - private function getReceiver(): AmazonSqsReceiver + /** + * @return MessageCountAwareInterface&ReceiverInterface + */ + private function getReceiver(): ReceiverInterface { - return $this->receiver = new AmazonSqsReceiver($this->connection, $this->serializer); + return $this->receiver ??= new AmazonSqsReceiver($this->connection, $this->serializer); } - private function getSender(): AmazonSqsSender + private function getSender(): SenderInterface { - return $this->sender = new AmazonSqsSender($this->connection, $this->serializer); + return $this->sender ??= new AmazonSqsSender($this->connection, $this->serializer); } } diff --git a/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpTransportTest.php b/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpTransportTest.php index 0223a0396c011..433aeebdfe5d5 100644 --- a/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpTransportTest.php +++ b/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/AmqpTransportTest.php @@ -54,8 +54,8 @@ public function testReceivesMessages() private function getTransport(SerializerInterface $serializer = null, Connection $connection = null): AmqpTransport { - $serializer = $serializer ?? $this->createMock(SerializerInterface::class); - $connection = $connection ?? $this->createMock(Connection::class); + $serializer ??= $this->createMock(SerializerInterface::class); + $connection ??= $this->createMock(Connection::class); return new AmqpTransport($connection, $serializer); } diff --git a/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/AmqpTransport.php b/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/AmqpTransport.php index d00f838202bdb..cd3c397f27d87 100644 --- a/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/AmqpTransport.php +++ b/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/AmqpTransport.php @@ -40,7 +40,7 @@ public function __construct(Connection $connection, SerializerInterface $seriali */ public function get(): iterable { - return ($this->receiver ?? $this->getReceiver())->get(); + return $this->getReceiver()->get(); } /** @@ -48,7 +48,7 @@ public function get(): iterable */ public function getFromQueues(array $queueNames): iterable { - return ($this->receiver ?? $this->getReceiver())->getFromQueues($queueNames); + return $this->getReceiver()->getFromQueues($queueNames); } /** @@ -56,7 +56,7 @@ public function getFromQueues(array $queueNames): iterable */ public function ack(Envelope $envelope): void { - ($this->receiver ?? $this->getReceiver())->ack($envelope); + $this->getReceiver()->ack($envelope); } /** @@ -64,7 +64,7 @@ public function ack(Envelope $envelope): void */ public function reject(Envelope $envelope): void { - ($this->receiver ?? $this->getReceiver())->reject($envelope); + $this->getReceiver()->reject($envelope); } /** @@ -72,7 +72,7 @@ public function reject(Envelope $envelope): void */ public function send(Envelope $envelope): Envelope { - return ($this->sender ?? $this->getSender())->send($envelope); + return $this->getSender()->send($envelope); } /** @@ -88,17 +88,17 @@ public function setup(): void */ public function getMessageCount(): int { - return ($this->receiver ?? $this->getReceiver())->getMessageCount(); + return $this->getReceiver()->getMessageCount(); } private function getReceiver(): AmqpReceiver { - return $this->receiver = new AmqpReceiver($this->connection, $this->serializer); + return $this->receiver ??= new AmqpReceiver($this->connection, $this->serializer); } private function getSender(): AmqpSender { - return $this->sender = new AmqpSender($this->connection, $this->serializer); + return $this->sender ??= new AmqpSender($this->connection, $this->serializer); } } diff --git a/src/Symfony/Component/Messenger/Bridge/Beanstalkd/Tests/Transport/BeanstalkdTransportTest.php b/src/Symfony/Component/Messenger/Bridge/Beanstalkd/Tests/Transport/BeanstalkdTransportTest.php index 5671163982b5e..6ba15f30d4fa7 100644 --- a/src/Symfony/Component/Messenger/Bridge/Beanstalkd/Tests/Transport/BeanstalkdTransportTest.php +++ b/src/Symfony/Component/Messenger/Bridge/Beanstalkd/Tests/Transport/BeanstalkdTransportTest.php @@ -52,8 +52,8 @@ public function testReceivesMessages() private function getTransport(SerializerInterface $serializer = null, Connection $connection = null): BeanstalkdTransport { - $serializer = $serializer ?? $this->createMock(SerializerInterface::class); - $connection = $connection ?? $this->createMock(Connection::class); + $serializer ??= $this->createMock(SerializerInterface::class); + $connection ??= $this->createMock(Connection::class); return new BeanstalkdTransport($connection, $serializer); } diff --git a/src/Symfony/Component/Messenger/Bridge/Beanstalkd/Transport/BeanstalkdTransport.php b/src/Symfony/Component/Messenger/Bridge/Beanstalkd/Transport/BeanstalkdTransport.php index a67df46800a7e..4a95f22cae65e 100644 --- a/src/Symfony/Component/Messenger/Bridge/Beanstalkd/Transport/BeanstalkdTransport.php +++ b/src/Symfony/Component/Messenger/Bridge/Beanstalkd/Transport/BeanstalkdTransport.php @@ -38,7 +38,7 @@ public function __construct(Connection $connection, SerializerInterface $seriali */ public function get(): iterable { - return ($this->receiver ?? $this->getReceiver())->get(); + return $this->getReceiver()->get(); } /** @@ -46,7 +46,7 @@ public function get(): iterable */ public function ack(Envelope $envelope): void { - ($this->receiver ?? $this->getReceiver())->ack($envelope); + $this->getReceiver()->ack($envelope); } /** @@ -54,7 +54,7 @@ public function ack(Envelope $envelope): void */ public function reject(Envelope $envelope): void { - ($this->receiver ?? $this->getReceiver())->reject($envelope); + $this->getReceiver()->reject($envelope); } /** @@ -62,7 +62,7 @@ public function reject(Envelope $envelope): void */ public function getMessageCount(): int { - return ($this->receiver ?? $this->getReceiver())->getMessageCount(); + return $this->getReceiver()->getMessageCount(); } /** @@ -70,16 +70,16 @@ public function getMessageCount(): int */ public function send(Envelope $envelope): Envelope { - return ($this->sender ?? $this->getSender())->send($envelope); + return $this->getSender()->send($envelope); } private function getReceiver(): BeanstalkdReceiver { - return $this->receiver = new BeanstalkdReceiver($this->connection, $this->serializer); + return $this->receiver ??= new BeanstalkdReceiver($this->connection, $this->serializer); } private function getSender(): BeanstalkdSender { - return $this->sender = new BeanstalkdSender($this->connection, $this->serializer); + return $this->sender ??= new BeanstalkdSender($this->connection, $this->serializer); } } diff --git a/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrineTransportTest.php b/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrineTransportTest.php index 751390503234d..d6c5b1f619b79 100644 --- a/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrineTransportTest.php +++ b/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrineTransportTest.php @@ -71,8 +71,8 @@ public function testConfigureSchema() private function getTransport(SerializerInterface $serializer = null, Connection $connection = null): DoctrineTransport { - $serializer = $serializer ?? $this->createMock(SerializerInterface::class); - $connection = $connection ?? $this->createMock(Connection::class); + $serializer ??= $this->createMock(SerializerInterface::class); + $connection ??= $this->createMock(Connection::class); return new DoctrineTransport($connection, $serializer); } diff --git a/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/DoctrineTransport.php b/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/DoctrineTransport.php index c29f529b6fe6d..35b5904658a80 100644 --- a/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/DoctrineTransport.php +++ b/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/DoctrineTransport.php @@ -42,7 +42,7 @@ public function __construct(Connection $connection, SerializerInterface $seriali */ public function get(): iterable { - return ($this->receiver ?? $this->getReceiver())->get(); + return $this->getReceiver()->get(); } /** @@ -50,7 +50,7 @@ public function get(): iterable */ public function ack(Envelope $envelope): void { - ($this->receiver ?? $this->getReceiver())->ack($envelope); + $this->getReceiver()->ack($envelope); } /** @@ -58,7 +58,7 @@ public function ack(Envelope $envelope): void */ public function reject(Envelope $envelope): void { - ($this->receiver ?? $this->getReceiver())->reject($envelope); + $this->getReceiver()->reject($envelope); } /** @@ -66,7 +66,7 @@ public function reject(Envelope $envelope): void */ public function getMessageCount(): int { - return ($this->receiver ?? $this->getReceiver())->getMessageCount(); + return $this->getReceiver()->getMessageCount(); } /** @@ -74,7 +74,7 @@ public function getMessageCount(): int */ public function all(int $limit = null): iterable { - return ($this->receiver ?? $this->getReceiver())->all($limit); + return $this->getReceiver()->all($limit); } /** @@ -82,7 +82,7 @@ public function all(int $limit = null): iterable */ public function find(mixed $id): ?Envelope { - return ($this->receiver ?? $this->getReceiver())->find($id); + return $this->getReceiver()->find($id); } /** @@ -90,7 +90,7 @@ public function find(mixed $id): ?Envelope */ public function send(Envelope $envelope): Envelope { - return ($this->sender ?? $this->getSender())->send($envelope); + return $this->getSender()->send($envelope); } /** @@ -121,12 +121,12 @@ public function getExtraSetupSqlForTable(Table $createdTable): array private function getReceiver(): DoctrineReceiver { - return $this->receiver = new DoctrineReceiver($this->connection, $this->serializer); + return $this->receiver ??= new DoctrineReceiver($this->connection, $this->serializer); } private function getSender(): DoctrineSender { - return $this->sender = new DoctrineSender($this->connection, $this->serializer); + return $this->sender ??= new DoctrineSender($this->connection, $this->serializer); } } diff --git a/src/Symfony/Component/Messenger/Bridge/Redis/Tests/Transport/RedisTransportTest.php b/src/Symfony/Component/Messenger/Bridge/Redis/Tests/Transport/RedisTransportTest.php index d3a9da9d728e9..199edb8944ae0 100644 --- a/src/Symfony/Component/Messenger/Bridge/Redis/Tests/Transport/RedisTransportTest.php +++ b/src/Symfony/Component/Messenger/Bridge/Redis/Tests/Transport/RedisTransportTest.php @@ -56,8 +56,8 @@ public function testReceivesMessages() private function getTransport(SerializerInterface $serializer = null, Connection $connection = null): RedisTransport { - $serializer = $serializer ?? $this->createMock(SerializerInterface::class); - $connection = $connection ?? $this->createMock(Connection::class); + $serializer ??= $this->createMock(SerializerInterface::class); + $connection ??= $this->createMock(Connection::class); return new RedisTransport($connection, $serializer); } diff --git a/src/Symfony/Component/Messenger/Bridge/Redis/Transport/RedisTransport.php b/src/Symfony/Component/Messenger/Bridge/Redis/Transport/RedisTransport.php index 8fa5c61fabf65..8f77e97587f10 100644 --- a/src/Symfony/Component/Messenger/Bridge/Redis/Transport/RedisTransport.php +++ b/src/Symfony/Component/Messenger/Bridge/Redis/Transport/RedisTransport.php @@ -39,7 +39,7 @@ public function __construct(Connection $connection, SerializerInterface $seriali */ public function get(): iterable { - return ($this->receiver ?? $this->getReceiver())->get(); + return $this->getReceiver()->get(); } /** @@ -47,7 +47,7 @@ public function get(): iterable */ public function ack(Envelope $envelope): void { - ($this->receiver ?? $this->getReceiver())->ack($envelope); + $this->getReceiver()->ack($envelope); } /** @@ -55,7 +55,7 @@ public function ack(Envelope $envelope): void */ public function reject(Envelope $envelope): void { - ($this->receiver ?? $this->getReceiver())->reject($envelope); + $this->getReceiver()->reject($envelope); } /** @@ -63,7 +63,7 @@ public function reject(Envelope $envelope): void */ public function send(Envelope $envelope): Envelope { - return ($this->sender ?? $this->getSender())->send($envelope); + return $this->getSender()->send($envelope); } /** @@ -76,12 +76,12 @@ public function setup(): void private function getReceiver(): RedisReceiver { - return $this->receiver = new RedisReceiver($this->connection, $this->serializer); + return $this->receiver ??= new RedisReceiver($this->connection, $this->serializer); } private function getSender(): RedisSender { - return $this->sender = new RedisSender($this->connection, $this->serializer); + return $this->sender ??= new RedisSender($this->connection, $this->serializer); } } diff --git a/src/Symfony/Component/Messenger/Command/AbstractFailedMessagesCommand.php b/src/Symfony/Component/Messenger/Command/AbstractFailedMessagesCommand.php index febc7163fcce3..62f01fc03f051 100644 --- a/src/Symfony/Component/Messenger/Command/AbstractFailedMessagesCommand.php +++ b/src/Symfony/Component/Messenger/Command/AbstractFailedMessagesCommand.php @@ -149,7 +149,7 @@ protected function printPendingMessagesMessage(ReceiverInterface $receiver, Symf protected function getReceiver(string $name = null): ReceiverInterface { - if (null === $name = $name ?? $this->globalFailureReceiverName) { + if (null === $name ??= $this->globalFailureReceiverName) { throw new InvalidArgumentException(sprintf('No default failure transport is defined. Available transports are: "%s".', implode('", "', array_keys($this->failureTransports->getProvidedServices())))); } diff --git a/src/Symfony/Component/Messenger/Envelope.php b/src/Symfony/Component/Messenger/Envelope.php index 48743e79bd706..74ab6edcce2ff 100644 --- a/src/Symfony/Component/Messenger/Envelope.php +++ b/src/Symfony/Component/Messenger/Envelope.php @@ -95,7 +95,7 @@ public function withoutStampsOfType(string $type): self public function last(string $stampFqcn): ?StampInterface { - return isset($this->stamps[$stampFqcn = $stampFqcn]) ? end($this->stamps[$stampFqcn]) : null; + return isset($this->stamps[$stampFqcn]) ? end($this->stamps[$stampFqcn]) : null; } /** diff --git a/src/Symfony/Component/Messenger/Transport/InMemoryTransport.php b/src/Symfony/Component/Messenger/Transport/InMemoryTransport.php index 217454d56a065..dc734c25d4c7d 100644 --- a/src/Symfony/Component/Messenger/Transport/InMemoryTransport.php +++ b/src/Symfony/Component/Messenger/Transport/InMemoryTransport.php @@ -157,4 +157,3 @@ private function decode(array $messagesEncoded): array ); } } - diff --git a/src/Symfony/Component/Notifier/Bridge/Mercure/MercureTransport.php b/src/Symfony/Component/Notifier/Bridge/Mercure/MercureTransport.php index 08850d890ed85..a49cf0565fca3 100644 --- a/src/Symfony/Component/Notifier/Bridge/Mercure/MercureTransport.php +++ b/src/Symfony/Component/Notifier/Bridge/Mercure/MercureTransport.php @@ -87,7 +87,7 @@ protected function doSend(MessageInterface $message): SentMessage $sentMessage->setMessageId($messageId); return $sentMessage; - } catch (MercureRuntimeException | InvalidArgumentException $e) { + } catch (MercureRuntimeException|InvalidArgumentException $e) { throw new RuntimeException('Unable to post the Mercure message: '.$e->getMessage(), $e->getCode(), $e); } } diff --git a/src/Symfony/Component/Notifier/Bridge/Mercure/Tests/MercureTransportTest.php b/src/Symfony/Component/Notifier/Bridge/Mercure/Tests/MercureTransportTest.php index 21c59e38e76ad..6d04b10fe6571 100644 --- a/src/Symfony/Component/Notifier/Bridge/Mercure/Tests/MercureTransportTest.php +++ b/src/Symfony/Component/Notifier/Bridge/Mercure/Tests/MercureTransportTest.php @@ -36,7 +36,7 @@ final class MercureTransportTest extends TransportTestCase { public function createTransport(HttpClientInterface $client = null, HubInterface $hub = null, string $hubId = 'hubId', $topics = null): MercureTransport { - $hub = $hub ?? $this->createMock(HubInterface::class); + $hub ??= $this->createMock(HubInterface::class); return new MercureTransport($hub, $hubId, $topics); } diff --git a/src/Symfony/Component/Notifier/Bridge/MessageMedia/MessageMediaTransport.php b/src/Symfony/Component/Notifier/Bridge/MessageMedia/MessageMediaTransport.php index a71dc6175e868..dd52e3ff01a65 100644 --- a/src/Symfony/Component/Notifier/Bridge/MessageMedia/MessageMediaTransport.php +++ b/src/Symfony/Component/Notifier/Bridge/MessageMedia/MessageMediaTransport.php @@ -98,7 +98,7 @@ protected function doSend(MessageInterface $message): SentMessage $error = $response->toArray(false); $errorMessage = $error['details'][0] ?? ($error['message'] ?? 'Unknown reason'); - } catch (DecodingExceptionInterface | TransportExceptionInterface $e) { + } catch (DecodingExceptionInterface|TransportExceptionInterface $e) { $errorMessage = 'Unknown reason'; } diff --git a/src/Symfony/Component/Notifier/Bridge/Mobyt/MobytTransport.php b/src/Symfony/Component/Notifier/Bridge/Mobyt/MobytTransport.php index 4ab0ff94a1cb2..0ca093a351d07 100644 --- a/src/Symfony/Component/Notifier/Bridge/Mobyt/MobytTransport.php +++ b/src/Symfony/Component/Notifier/Bridge/Mobyt/MobytTransport.php @@ -40,7 +40,7 @@ public function __construct(string $accountSid, string $authToken, string $from, $this->authToken = $authToken; $this->from = $from; - $typeQuality = $typeQuality ?? MobytOptions::MESSAGE_TYPE_QUALITY_LOW; + $typeQuality ??= MobytOptions::MESSAGE_TYPE_QUALITY_LOW; MobytOptions::validateMessageType($typeQuality); $this->typeQuality = $typeQuality; @@ -69,12 +69,12 @@ protected function doSend(MessageInterface $message): SentMessage } $options = $message->getOptions() ? $message->getOptions()->toArray() : []; - $options['message_type'] = $options['message_type'] ?? $this->typeQuality; + $options['message_type'] ??= $this->typeQuality; - $options['message'] = $options['message'] ?? $message->getSubject(); + $options['message'] ??= $message->getSubject(); $options['recipient'] = [$message->getPhone()]; - $options['sender'] = $options['sender'] ?? $this->from; + $options['sender'] ??= $this->from; $response = $this->client->request('POST', 'https://'.$this->getEndpoint().'/API/v1.0/REST/sms', [ 'headers' => [ diff --git a/src/Symfony/Component/Notifier/Bridge/Sms77/Tests/Sms77TransportTest.php b/src/Symfony/Component/Notifier/Bridge/Sms77/Tests/Sms77TransportTest.php index 1c574ed7e4e8e..734b181650e9c 100644 --- a/src/Symfony/Component/Notifier/Bridge/Sms77/Tests/Sms77TransportTest.php +++ b/src/Symfony/Component/Notifier/Bridge/Sms77/Tests/Sms77TransportTest.php @@ -21,9 +21,6 @@ final class Sms77TransportTest extends TransportTestCase { - /** - * @return Sms77Transport - */ public function createTransport(HttpClientInterface $client = null, string $from = null): Sms77Transport { return new Sms77Transport('apiKey', $from, $client ?? $this->createMock(HttpClientInterface::class)); diff --git a/src/Symfony/Component/Notifier/Bridge/SpotHit/SpotHitTransport.php b/src/Symfony/Component/Notifier/Bridge/SpotHit/SpotHitTransport.php index 0cb053bd725ba..d627688bef9b2 100644 --- a/src/Symfony/Component/Notifier/Bridge/SpotHit/SpotHitTransport.php +++ b/src/Symfony/Component/Notifier/Bridge/SpotHit/SpotHitTransport.php @@ -87,7 +87,7 @@ protected function doSend(MessageInterface $message): SentMessage $data = $response->toArray(); } catch (TransportExceptionInterface $e) { throw new TransportException('Could not reach the remote SpotHit server.', $response, 0, $e); - } catch (HttpExceptionInterface | DecodingExceptionInterface $e) { + } catch (HttpExceptionInterface|DecodingExceptionInterface $e) { throw new TransportException('Unexpected reply from the remote SpotHit server.', $response, 0, $e); } diff --git a/src/Symfony/Component/PasswordHasher/Hasher/NativePasswordHasher.php b/src/Symfony/Component/PasswordHasher/Hasher/NativePasswordHasher.php index 611dddc56aa20..3deef74cacab0 100644 --- a/src/Symfony/Component/PasswordHasher/Hasher/NativePasswordHasher.php +++ b/src/Symfony/Component/PasswordHasher/Hasher/NativePasswordHasher.php @@ -33,9 +33,9 @@ final class NativePasswordHasher implements PasswordHasherInterface */ public function __construct(int $opsLimit = null, int $memLimit = null, int $cost = null, string $algorithm = null) { - $cost = $cost ?? 13; - $opsLimit = $opsLimit ?? max(4, \defined('SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE') ? \SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE : 4); - $memLimit = $memLimit ?? max(64 * 1024 * 1024, \defined('SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE') ? \SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE : 64 * 1024 * 1024); + $cost ??= 13; + $opsLimit ??= max(4, \defined('SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE') ? \SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE : 4); + $memLimit ??= max(64 * 1024 * 1024, \defined('SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE') ? \SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE : 64 * 1024 * 1024); if (3 > $opsLimit) { throw new \InvalidArgumentException('$opsLimit must be 3 or greater.'); diff --git a/src/Symfony/Component/PasswordHasher/Tests/Hasher/UserPasswordHasherTest.php b/src/Symfony/Component/PasswordHasher/Tests/Hasher/UserPasswordHasherTest.php index ad858f8f9376e..274272583c321 100644 --- a/src/Symfony/Component/PasswordHasher/Tests/Hasher/UserPasswordHasherTest.php +++ b/src/Symfony/Component/PasswordHasher/Tests/Hasher/UserPasswordHasherTest.php @@ -18,8 +18,8 @@ use Symfony\Component\PasswordHasher\PasswordHasherInterface; use Symfony\Component\PasswordHasher\Tests\Fixtures\TestLegacyPasswordAuthenticatedUser; use Symfony\Component\PasswordHasher\Tests\Fixtures\TestPasswordAuthenticatedUser; -use Symfony\Component\Security\Core\User\User; use Symfony\Component\Security\Core\User\InMemoryUser; +use Symfony\Component\Security\Core\User\User; class UserPasswordHasherTest extends TestCase { diff --git a/src/Symfony/Component/Process/Pipes/AbstractPipes.php b/src/Symfony/Component/Process/Pipes/AbstractPipes.php index dca7ae7f9550e..c2014a6829c0f 100644 --- a/src/Symfony/Component/Process/Pipes/AbstractPipes.php +++ b/src/Symfony/Component/Process/Pipes/AbstractPipes.php @@ -133,7 +133,7 @@ protected function write(): ?array } if ($input) { - for (;;) { + while (true) { $data = fread($input, self::CHUNK_SIZE); if (!isset($data[0])) { break; diff --git a/src/Symfony/Component/Process/Tests/ProcessTest.php b/src/Symfony/Component/Process/Tests/ProcessTest.php index 91ba7c4f37249..fc4de7bc5565a 100644 --- a/src/Symfony/Component/Process/Tests/ProcessTest.php +++ b/src/Symfony/Component/Process/Tests/ProcessTest.php @@ -772,7 +772,8 @@ public function testIterateOverProcessWithTimeout() $start = microtime(true); try { $process->start(); - foreach ($process as $buffer); + foreach ($process as $buffer) { + } $this->fail('A RuntimeException should have been raised'); } catch (RuntimeException $e) { } diff --git a/src/Symfony/Component/PropertyInfo/Extractor/PhpDocExtractor.php b/src/Symfony/Component/PropertyInfo/Extractor/PhpDocExtractor.php index 0f2fba5ad4432..b414330b5a247 100644 --- a/src/Symfony/Component/PropertyInfo/Extractor/PhpDocExtractor.php +++ b/src/Symfony/Component/PropertyInfo/Extractor/PhpDocExtractor.php @@ -155,7 +155,7 @@ public function getTypes(string $class, string $property, array $context = []): break; case 'parent': - if (false !== $resolvedClass = $parentClass ?? $parentClass = get_parent_class($class)) { + if (false !== $resolvedClass = $parentClass ??= get_parent_class($class)) { break; } // no break diff --git a/src/Symfony/Component/PropertyInfo/Extractor/PhpStanExtractor.php b/src/Symfony/Component/PropertyInfo/Extractor/PhpStanExtractor.php index 4a6a296784d6d..3c66d48cd522f 100644 --- a/src/Symfony/Component/PropertyInfo/Extractor/PhpStanExtractor.php +++ b/src/Symfony/Component/PropertyInfo/Extractor/PhpStanExtractor.php @@ -107,7 +107,7 @@ public function getTypes(string $class, string $property, array $context = []): break; case 'parent': - if (false !== $resolvedClass = $parentClass ?? $parentClass = get_parent_class($class)) { + if (false !== $resolvedClass = $parentClass ??= get_parent_class($class)) { break; } // no break diff --git a/src/Symfony/Component/PropertyInfo/Util/PhpDocTypeHelper.php b/src/Symfony/Component/PropertyInfo/Util/PhpDocTypeHelper.php index d1752d6c1b2fb..f1e166c171694 100644 --- a/src/Symfony/Component/PropertyInfo/Util/PhpDocTypeHelper.php +++ b/src/Symfony/Component/PropertyInfo/Util/PhpDocTypeHelper.php @@ -93,7 +93,7 @@ public function getTypes(DocType $varType): array */ private function createType(DocType $type, bool $nullable, string $docType = null): ?Type { - $docType = $docType ?? (string) $type; + $docType ??= (string) $type; if ($type instanceof Collection) { $fqsen = $type->getFqsen(); diff --git a/src/Symfony/Component/RateLimiter/Policy/Window.php b/src/Symfony/Component/RateLimiter/Policy/Window.php index e1438d3534a56..cef914b648245 100644 --- a/src/Symfony/Component/RateLimiter/Policy/Window.php +++ b/src/Symfony/Component/RateLimiter/Policy/Window.php @@ -46,7 +46,7 @@ public function getExpirationTime(): ?int public function add(int $hits = 1, float $now = null) { - $now = $now ?? microtime(true); + $now ??= microtime(true); if (($now - $this->timer) > $this->intervalInSeconds) { // reset window $this->timer = $now; diff --git a/src/Symfony/Component/Routing/Generator/UrlGenerator.php b/src/Symfony/Component/Routing/Generator/UrlGenerator.php index ba4625c7b447e..4607a81ee595f 100644 --- a/src/Symfony/Component/Routing/Generator/UrlGenerator.php +++ b/src/Symfony/Component/Routing/Generator/UrlGenerator.php @@ -128,9 +128,7 @@ public function isStrictRequirements(): ?bool public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH): string { $route = null; - $locale = $parameters['_locale'] - ?? $this->context->getParameter('_locale') - ?: $this->defaultLocale; + $locale = $parameters['_locale'] ?? $this->context->getParameter('_locale') ?: $this->defaultLocale; if (null !== $locale) { do { @@ -140,7 +138,7 @@ public function generate(string $name, array $parameters = [], int $referenceTyp } while (false !== $locale = strstr($locale, '_', true)); } - if (null === $route = $route ?? $this->routes->get($name)) { + if (null === $route ??= $this->routes->get($name)) { throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name)); } diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherDumper.php b/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherDumper.php index 10631dfa9de40..fb06479f1c0d9 100644 --- a/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherDumper.php +++ b/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherDumper.php @@ -427,7 +427,7 @@ private function compileRoute(Route $route, string $name, string|array|null $var if ($condition = $route->getCondition()) { $condition = $this->getExpressionLanguage()->compile($condition, ['context', 'request']); - $condition = $conditions[$condition] ?? $conditions[$condition] = (str_contains($condition, '$request') ? 1 : -1) * \count($conditions); + $condition = $conditions[$condition] ??= (str_contains($condition, '$request') ? 1 : -1) * \count($conditions); } else { $condition = null; } diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherTrait.php b/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherTrait.php index 8b3bf53fef5cc..7e869e0491960 100644 --- a/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherTrait.php +++ b/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherTrait.php @@ -92,7 +92,7 @@ private function doMatch(string $pathinfo, array &$allow = [], array &$allowSche $supportsRedirections = 'GET' === $canonicalMethod && $this instanceof RedirectableUrlMatcherInterface; foreach ($this->staticRoutes[$trimmedPathinfo] ?? [] as [$ret, $requiredHost, $requiredMethods, $requiredSchemes, $hasTrailingSlash, , $condition]) { - if ($condition && !($this->checkCondition)($condition, $context, 0 < $condition ? $request ?? $request = $this->request ?: $this->createRequest($pathinfo) : null)) { + if ($condition && !($this->checkCondition)($condition, $context, 0 < $condition ? $request ??= $this->request ?: $this->createRequest($pathinfo) : null)) { continue; } @@ -136,7 +136,7 @@ private function doMatch(string $pathinfo, array &$allow = [], array &$allowSche if (0 === $condition) { // marks the last route in the regexp continue 3; } - if (!($this->checkCondition)($condition, $context, 0 < $condition ? $request ?? $request = $this->request ?: $this->createRequest($pathinfo) : null)) { + if (!($this->checkCondition)($condition, $context, 0 < $condition ? $request ??= $this->request ?: $this->createRequest($pathinfo) : null)) { continue; } } diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/StaticPrefixCollection.php b/src/Symfony/Component/Routing/Matcher/Dumper/StaticPrefixCollection.php index 403607114991a..ab357bafd4b20 100644 --- a/src/Symfony/Component/Routing/Matcher/Dumper/StaticPrefixCollection.php +++ b/src/Symfony/Component/Routing/Matcher/Dumper/StaticPrefixCollection.php @@ -152,7 +152,7 @@ private function getCommonPrefix(string $prefix, string $anotherPrefix): array try { for ($i = $baseLength; $i < $end && $prefix[$i] === $anotherPrefix[$i]; ++$i) { if ('(' === $prefix[$i]) { - $staticLength = $staticLength ?? $i; + $staticLength ??= $i; for ($j = 1 + $i, $n = 1; $j < $end && 0 < $n; ++$j) { if ($prefix[$j] !== $anotherPrefix[$j]) { break 2; diff --git a/src/Symfony/Component/Runtime/GenericRuntime.php b/src/Symfony/Component/Runtime/GenericRuntime.php index 54a00e0d1aca7..6277988a2fe4b 100644 --- a/src/Symfony/Component/Runtime/GenericRuntime.php +++ b/src/Symfony/Component/Runtime/GenericRuntime.php @@ -59,8 +59,8 @@ class GenericRuntime implements RuntimeInterface */ public function __construct(array $options = []) { - $options['env_var_name'] ?? $options['env_var_name'] = 'APP_ENV'; - $debugKey = $options['debug_var_name'] ?? $options['debug_var_name'] = 'APP_DEBUG'; + $options['env_var_name'] ??= 'APP_ENV'; + $debugKey = $options['debug_var_name'] ??= 'APP_DEBUG'; $debug = $options['debug'] ?? $_SERVER[$debugKey] ?? $_ENV[$debugKey] ?? true; diff --git a/src/Symfony/Component/Runtime/SymfonyRuntime.php b/src/Symfony/Component/Runtime/SymfonyRuntime.php index 4a8782b55d035..2e853ca9d2497 100644 --- a/src/Symfony/Component/Runtime/SymfonyRuntime.php +++ b/src/Symfony/Component/Runtime/SymfonyRuntime.php @@ -90,8 +90,8 @@ class SymfonyRuntime extends GenericRuntime */ public function __construct(array $options = []) { - $envKey = $options['env_var_name'] ?? $options['env_var_name'] = 'APP_ENV'; - $debugKey = $options['debug_var_name'] ?? $options['debug_var_name'] = 'APP_DEBUG'; + $envKey = $options['env_var_name'] ??= 'APP_ENV'; + $debugKey = $options['debug_var_name'] ??= 'APP_DEBUG'; if (isset($options['env'])) { $_SERVER[$envKey] = $options['env']; @@ -105,14 +105,14 @@ public function __construct(array $options = []) ->setProdEnvs((array) ($options['prod_envs'] ?? ['prod'])) ->usePutenv($options['use_putenv'] ?? false) ->bootEnv($options['project_dir'].'/'.($options['dotenv_path'] ?? '.env'), 'dev', (array) ($options['test_envs'] ?? ['test']), $options['dotenv_overload'] ?? false); - $options['debug'] ?? $options['debug'] = '1' === $_SERVER[$debugKey]; + $options['debug'] ??= '1' === $_SERVER[$debugKey]; $options['disable_dotenv'] = true; } else { - $_SERVER[$envKey] ?? $_SERVER[$envKey] = $_ENV[$envKey] ?? 'dev'; - $_SERVER[$debugKey] ?? $_SERVER[$debugKey] = $_ENV[$debugKey] ?? !\in_array($_SERVER[$envKey], (array) ($options['prod_envs'] ?? ['prod']), true); + $_SERVER[$envKey] ??= $_ENV[$envKey] ?? 'dev'; + $_SERVER[$debugKey] ??= $_ENV[$debugKey] ?? !\in_array($_SERVER[$envKey], (array) ($options['prod_envs'] ?? ['prod']), true); } - $options['error_handler'] ?? $options['error_handler'] = SymfonyErrorHandler::class; + $options['error_handler'] ??= SymfonyErrorHandler::class; parent::__construct($options); } @@ -128,7 +128,7 @@ public function getRunner(?object $application): RunnerInterface } if ($application instanceof Command) { - $console = $this->console ?? $this->console = new Application(); + $console = $this->console ??= new Application(); $console->setName($application->getName() ?: $console->getName()); if (!$application->getName() || !$console->has($application->getName())) { @@ -149,7 +149,7 @@ public function getRunner(?object $application): RunnerInterface set_time_limit(0); $defaultEnv = !isset($this->options['env']) ? ($_SERVER[$this->options['env_var_name']] ?? 'dev') : null; - $output = $this->output ?? $this->output = new ConsoleOutput(); + $output = $this->output ??= new ConsoleOutput(); return new ConsoleApplicationRunner($application, $defaultEnv, $this->getInput(), $output); } @@ -171,13 +171,13 @@ protected function getArgument(\ReflectionParameter $parameter, ?string $type): return $this->getInput(); case OutputInterface::class: - return $this->output ?? $this->output = new ConsoleOutput(); + return $this->output ??= new ConsoleOutput(); case Application::class: - return $this->console ?? $this->console = new Application(); + return $this->console ??= new Application(); case Command::class: - return $this->command ?? $this->command = new Command(); + return $this->command ??= new Command(); } return parent::getArgument($parameter, $type); diff --git a/src/Symfony/Component/Security/Core/Signature/ExpiredSignatureStorage.php b/src/Symfony/Component/Security/Core/Signature/ExpiredSignatureStorage.php index 402092f6cb60e..20803b9742e02 100644 --- a/src/Symfony/Component/Security/Core/Signature/ExpiredSignatureStorage.php +++ b/src/Symfony/Component/Security/Core/Signature/ExpiredSignatureStorage.php @@ -15,8 +15,6 @@ /** * @author Ryan Weaver - * - * @final */ final class ExpiredSignatureStorage { diff --git a/src/Symfony/Component/Security/Http/Authenticator/Debug/TraceableAuthenticator.php b/src/Symfony/Component/Security/Http/Authenticator/Debug/TraceableAuthenticator.php index 6e536b3784948..5aa009d7ffc46 100644 --- a/src/Symfony/Component/Security/Http/Authenticator/Debug/TraceableAuthenticator.php +++ b/src/Symfony/Component/Security/Http/Authenticator/Debug/TraceableAuthenticator.php @@ -45,7 +45,7 @@ public function getInfo(): array 'supports' => true, 'passport' => $this->passport, 'duration' => $this->duration, - 'stub' => $this->stub ?? $this->stub = class_exists(ClassStub::class) ? new ClassStub(\get_class($this->authenticator)) : \get_class($this->authenticator), + 'stub' => $this->stub ??= class_exists(ClassStub::class) ? new ClassStub(\get_class($this->authenticator)) : \get_class($this->authenticator), ]; } diff --git a/src/Symfony/Component/Serializer/Normalizer/NormalizableInterface.php b/src/Symfony/Component/Serializer/Normalizer/NormalizableInterface.php index e518608eb0b81..d449a43065140 100644 --- a/src/Symfony/Component/Serializer/Normalizer/NormalizableInterface.php +++ b/src/Symfony/Component/Serializer/Normalizer/NormalizableInterface.php @@ -32,8 +32,6 @@ interface NormalizableInterface * @param string|null $format The format is optionally given to be able to normalize differently * based on different output formats * @param array $context Options for normalizing this object - * - * @return array|string|int|float|bool */ public function normalize(NormalizerInterface $normalizer, string $format = null, array $context = []): array|string|int|float|bool; } diff --git a/src/Symfony/Component/Serializer/Normalizer/ObjectToPopulateTrait.php b/src/Symfony/Component/Serializer/Normalizer/ObjectToPopulateTrait.php index 6a0d324ce0691..23be4c6afdb51 100644 --- a/src/Symfony/Component/Serializer/Normalizer/ObjectToPopulateTrait.php +++ b/src/Symfony/Component/Serializer/Normalizer/ObjectToPopulateTrait.php @@ -23,7 +23,7 @@ trait ObjectToPopulateTrait */ protected function extractObjectToPopulate(string $class, array $context, string $key = null): ?object { - $key = $key ?? AbstractNormalizer::OBJECT_TO_POPULATE; + $key ??= AbstractNormalizer::OBJECT_TO_POPULATE; if (isset($context[$key]) && \is_object($context[$key]) && $context[$key] instanceof $class) { return $context[$key]; diff --git a/src/Symfony/Component/String/AbstractString.php b/src/Symfony/Component/String/AbstractString.php index 0c17f9e181b86..b66e3d20e4f52 100644 --- a/src/Symfony/Component/String/AbstractString.php +++ b/src/Symfony/Component/String/AbstractString.php @@ -74,7 +74,7 @@ public static function wrap(array $values): array foreach ($values as $k => $v) { if (\is_string($k) && '' !== $k && $k !== $j = (string) new static($k)) { - $keys = $keys ?? array_keys($values); + $keys ??= array_keys($values); $keys[$i] = $j; } @@ -425,9 +425,6 @@ public function repeat(int $multiplier): static abstract public function replace(string $from, string $to): static; - /** - * @param string|callable $to - */ abstract public function replaceMatches(string $fromRegexp, string|callable $to): static; abstract public function reverse(): static; diff --git a/src/Symfony/Component/String/ByteString.php b/src/Symfony/Component/String/ByteString.php index 05ec6903749c2..21bbf4a670471 100644 --- a/src/Symfony/Component/String/ByteString.php +++ b/src/Symfony/Component/String/ByteString.php @@ -48,7 +48,7 @@ public static function fromRandom(int $length = 16, string $alphabet = null): se throw new InvalidArgumentException(sprintf('A strictly positive length is expected, "%d" given.', $length)); } - $alphabet = $alphabet ?? self::ALPHABET_ALPHANUMERIC; + $alphabet ??= self::ALPHABET_ALPHANUMERIC; $alphabetSize = \strlen($alphabet); $bits = (int) ceil(log($alphabetSize, 2.0)); if ($bits <= 0 || $bits > 56) { @@ -363,7 +363,7 @@ public function splice(string $replacement, int $start = 0, int $length = null): public function split(string $delimiter, int $limit = null, int $flags = null): array { - if (1 > $limit = $limit ?? \PHP_INT_MAX) { + if (1 > $limit ??= \PHP_INT_MAX) { throw new InvalidArgumentException('Split limit must be a positive integer.'); } diff --git a/src/Symfony/Component/String/CodePointString.php b/src/Symfony/Component/String/CodePointString.php index 926ff79849a36..f5c900fb2c73f 100644 --- a/src/Symfony/Component/String/CodePointString.php +++ b/src/Symfony/Component/String/CodePointString.php @@ -210,7 +210,7 @@ public function splice(string $replacement, int $start = 0, int $length = null): public function split(string $delimiter, int $limit = null, int $flags = null): array { - if (1 > $limit = $limit ?? \PHP_INT_MAX) { + if (1 > $limit ??= \PHP_INT_MAX) { throw new InvalidArgumentException('Split limit must be a positive integer.'); } diff --git a/src/Symfony/Component/String/Resources/functions.php b/src/Symfony/Component/String/Resources/functions.php index c950894f3934d..7a970400a86bc 100644 --- a/src/Symfony/Component/String/Resources/functions.php +++ b/src/Symfony/Component/String/Resources/functions.php @@ -31,7 +31,7 @@ function b(?string $string = ''): ByteString */ function s(?string $string = ''): AbstractString { - $string = $string ?? ''; + $string ??= ''; return preg_match('//u', $string) ? new UnicodeString($string) : new ByteString($string); } diff --git a/src/Symfony/Component/String/Slugger/AsciiSlugger.php b/src/Symfony/Component/String/Slugger/AsciiSlugger.php index 77b1e13b006e9..d32e3051f9051 100644 --- a/src/Symfony/Component/String/Slugger/AsciiSlugger.php +++ b/src/Symfony/Component/String/Slugger/AsciiSlugger.php @@ -93,7 +93,7 @@ public function getLocale(): string */ public function slug(string $string, string $separator = '-', string $locale = null): AbstractUnicodeString { - $locale = $locale ?? $this->defaultLocale; + $locale ??= $this->defaultLocale; $transliterator = []; if ($locale && ('de' === $locale || str_starts_with($locale, 'de_'))) { diff --git a/src/Symfony/Component/String/Tests/AbstractUnicodeTestCase.php b/src/Symfony/Component/String/Tests/AbstractUnicodeTestCase.php index f84942c4ba84b..7afbca87e9440 100644 --- a/src/Symfony/Component/String/Tests/AbstractUnicodeTestCase.php +++ b/src/Symfony/Component/String/Tests/AbstractUnicodeTestCase.php @@ -37,9 +37,9 @@ public function provideCreateFromCodePoint(): array ['*', [42]], ['AZ', [65, 90]], ['€', [8364]], - ['€', [0x20ac]], + ['€', [0x20AC]], ['Ʃ', [425]], - ['Ʃ', [0x1a9]], + ['Ʃ', [0x1A9]], ['☢☎❄', [0x2622, 0x260E, 0x2744]], ]; } diff --git a/src/Symfony/Component/String/UnicodeString.php b/src/Symfony/Component/String/UnicodeString.php index 70cf4c54348c9..47a708bbcb0a9 100644 --- a/src/Symfony/Component/String/UnicodeString.php +++ b/src/Symfony/Component/String/UnicodeString.php @@ -280,7 +280,7 @@ public function splice(string $replacement, int $start = 0, int $length = null): public function split(string $delimiter, int $limit = null, int $flags = null): array { - if (1 > $limit = $limit ?? 2147483647) { + if (1 > $limit ??= 2147483647) { throw new InvalidArgumentException('Split limit must be a positive integer.'); } diff --git a/src/Symfony/Component/Templating/Loader/LoaderInterface.php b/src/Symfony/Component/Templating/Loader/LoaderInterface.php index 00b7f46cb83be..531a1dff13818 100644 --- a/src/Symfony/Component/Templating/Loader/LoaderInterface.php +++ b/src/Symfony/Component/Templating/Loader/LoaderInterface.php @@ -23,8 +23,6 @@ interface LoaderInterface { /** * Loads a template. - * - * @return Storage|false */ public function load(TemplateReferenceInterface $template): Storage|false; diff --git a/src/Symfony/Component/Translation/DataCollector/TranslationDataCollector.php b/src/Symfony/Component/Translation/DataCollector/TranslationDataCollector.php index e6676fb4ed14f..4244511e46afa 100644 --- a/src/Symfony/Component/Translation/DataCollector/TranslationDataCollector.php +++ b/src/Symfony/Component/Translation/DataCollector/TranslationDataCollector.php @@ -62,9 +62,6 @@ public function reset() $this->data = []; } - /** - * @return array|Data - */ public function getMessages(): array|Data { return $this->data['messages'] ?? []; diff --git a/src/Symfony/Component/Translation/DependencyInjection/TranslatorPathsPass.php b/src/Symfony/Component/Translation/DependencyInjection/TranslatorPathsPass.php index 976c4c8bbc89f..b85c0662181d6 100644 --- a/src/Symfony/Component/Translation/DependencyInjection/TranslatorPathsPass.php +++ b/src/Symfony/Component/Translation/DependencyInjection/TranslatorPathsPass.php @@ -85,7 +85,7 @@ public function process(ContainerBuilder $container) protected function processValue(mixed $value, bool $isRoot = false): mixed { if ($value instanceof Reference) { - if ((string) $value === 'translator') { + if ('translator' === (string) $value) { for ($i = $this->level - 1; $i >= 0; --$i) { $class = $this->definitions[$i]->getClass(); diff --git a/src/Symfony/Component/Translation/Formatter/IntlFormatter.php b/src/Symfony/Component/Translation/Formatter/IntlFormatter.php index f7f1c36a2a127..546c992a2c6a4 100644 --- a/src/Symfony/Component/Translation/Formatter/IntlFormatter.php +++ b/src/Symfony/Component/Translation/Formatter/IntlFormatter.php @@ -34,7 +34,7 @@ public function formatIntl(string $message, string $locale, array $parameters = } if (!$formatter = $this->cache[$locale][$message] ?? null) { - if (!($this->hasMessageFormatter ?? $this->hasMessageFormatter = class_exists(\MessageFormatter::class))) { + if (!$this->hasMessageFormatter ??= class_exists(\MessageFormatter::class)) { throw new LogicException('Cannot parse message translation: please install the "intl" PHP extension or the "symfony/polyfill-intl-messageformatter" package.'); } try { diff --git a/src/Symfony/Component/Translation/Loader/XliffFileLoader.php b/src/Symfony/Component/Translation/Loader/XliffFileLoader.php index 94be7c5cca008..c379d6ca5ba04 100644 --- a/src/Symfony/Component/Translation/Loader/XliffFileLoader.php +++ b/src/Symfony/Component/Translation/Loader/XliffFileLoader.php @@ -57,7 +57,7 @@ public function load(mixed $resource, string $locale, string $domain = 'messages } else { $dom = XmlUtils::loadFile($resource); } - } catch (\InvalidArgumentException | XmlParsingException | InvalidXmlException $e) { + } catch (\InvalidArgumentException|XmlParsingException|InvalidXmlException $e) { throw new InvalidResourceException(sprintf('Unable to load "%s": ', $resource).$e->getMessage(), $e->getCode(), $e); } diff --git a/src/Symfony/Component/Uid/BinaryUtil.php b/src/Symfony/Component/Uid/BinaryUtil.php index 131976021560f..8fd19d8674af0 100644 --- a/src/Symfony/Component/Uid/BinaryUtil.php +++ b/src/Symfony/Component/Uid/BinaryUtil.php @@ -39,7 +39,7 @@ class BinaryUtil // https://tools.ietf.org/html/rfc4122#section-4.1.4 // 0x01b21dd213814000 is the number of 100-ns intervals between the // UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. - private const TIME_OFFSET_INT = 0x01b21dd213814000; + private const TIME_OFFSET_INT = 0x01B21DD213814000; private const TIME_OFFSET_BIN = "\x01\xb2\x1d\xd2\x13\x81\x40\x00"; private const TIME_OFFSET_COM1 = "\xfe\x4d\xe2\x2d\xec\x7e\xbf\xff"; private const TIME_OFFSET_COM2 = "\xfe\x4d\xe2\x2d\xec\x7e\xc0\x00"; diff --git a/src/Symfony/Component/Uid/Factory/NameBasedUuidFactory.php b/src/Symfony/Component/Uid/Factory/NameBasedUuidFactory.php index e367d8e26f83e..c8cf36663725b 100644 --- a/src/Symfony/Component/Uid/Factory/NameBasedUuidFactory.php +++ b/src/Symfony/Component/Uid/Factory/NameBasedUuidFactory.php @@ -26,9 +26,6 @@ public function __construct(string $class, Uuid $namespace) $this->namespace = $namespace; } - /** - * @return UuidV5|UuidV3 - */ public function create(string $name): UuidV5|UuidV3 { switch ($class = $this->class) { diff --git a/src/Symfony/Component/Uid/Factory/TimeBasedUuidFactory.php b/src/Symfony/Component/Uid/Factory/TimeBasedUuidFactory.php index 5074dc2ba766b..dffb50e258baf 100644 --- a/src/Symfony/Component/Uid/Factory/TimeBasedUuidFactory.php +++ b/src/Symfony/Component/Uid/Factory/TimeBasedUuidFactory.php @@ -26,9 +26,6 @@ public function __construct(string $class, Uuid $node = null) $this->node = $node; } - /** - * @return UuidV6|UuidV1 - */ public function create(\DateTimeInterface $time = null): UuidV6|UuidV1 { $class = $this->class; diff --git a/src/Symfony/Component/Uid/Factory/UuidFactory.php b/src/Symfony/Component/Uid/Factory/UuidFactory.php index 279c0d5ce9bf7..35a06e80f33f2 100644 --- a/src/Symfony/Component/Uid/Factory/UuidFactory.php +++ b/src/Symfony/Component/Uid/Factory/UuidFactory.php @@ -44,9 +44,6 @@ public function __construct(string|int $defaultClass = UuidV6::class, string|int $this->nameBasedNamespace = $nameBasedNamespace; } - /** - * @return UuidV6|UuidV4|UuidV1 - */ public function create(): UuidV6|UuidV4|UuidV1 { $class = $this->defaultClass; @@ -61,7 +58,7 @@ public function randomBased(): RandomBasedUuidFactory public function timeBased(Uuid|string $node = null): TimeBasedUuidFactory { - $node ?? $node = $this->timeBasedNode; + $node ??= $this->timeBasedNode; if (null !== $node && !$node instanceof Uuid) { $node = Uuid::fromString($node); @@ -72,7 +69,7 @@ public function timeBased(Uuid|string $node = null): TimeBasedUuidFactory public function nameBased(Uuid|string $namespace = null): NameBasedUuidFactory { - $namespace ?? $namespace = $this->nameBasedNamespace; + $namespace ??= $this->nameBasedNamespace; if (null === $namespace) { throw new \LogicException(sprintf('A namespace should be defined when using "%s()".', __METHOD__)); diff --git a/src/Symfony/Component/Uid/UuidV1.php b/src/Symfony/Component/Uid/UuidV1.php index 4c1c120dfb0be..1f4ad3314a957 100644 --- a/src/Symfony/Component/Uid/UuidV1.php +++ b/src/Symfony/Component/Uid/UuidV1.php @@ -54,7 +54,7 @@ public static function generate(\DateTimeInterface $time = null, Uuid $node = nu $seq = substr($uuid, 19, 4); while (null === self::$clockSeq || $seq === self::$clockSeq) { - self::$clockSeq = sprintf('%04x', random_int(0, 0x3fff) | 0x8000); + self::$clockSeq = sprintf('%04x', random_int(0, 0x3FFF) | 0x8000); } $seq = self::$clockSeq; diff --git a/src/Symfony/Component/Uid/UuidV6.php b/src/Symfony/Component/Uid/UuidV6.php index 1ef7d5c64eb74..3e753f6a8ab90 100644 --- a/src/Symfony/Component/Uid/UuidV6.php +++ b/src/Symfony/Component/Uid/UuidV6.php @@ -56,7 +56,7 @@ public static function generate(\DateTimeInterface $time = null, Uuid $node = nu // UUIDv6 prefers a truly random number here, let's XOR both to preserve the entropy if (!isset(self::$node)) { - $seed = [random_int(0, 0xffffff), random_int(0, 0xffffff)]; + $seed = [random_int(0, 0xFFFFFF), random_int(0, 0xFFFFFF)]; $node = unpack('N2', hex2bin('00'.substr($uuidV1, 24, 6)).hex2bin('00'.substr($uuidV1, 30))); self::$node = sprintf('%06x%06x', ($seed[0] ^ $node[1]) | 0x010000, $seed[1] ^ $node[2]); } diff --git a/src/Symfony/Component/Validator/Constraints/Count.php b/src/Symfony/Component/Validator/Constraints/Count.php index a29f69a588c10..f8ffc3750efa4 100644 --- a/src/Symfony/Component/Validator/Constraints/Count.php +++ b/src/Symfony/Component/Validator/Constraints/Count.php @@ -61,8 +61,8 @@ public function __construct( $exactly = $options['value'] ?? null; } - $min = $min ?? $options['min'] ?? null; - $max = $max ?? $options['max'] ?? null; + $min ??= $options['min'] ?? null; + $max ??= $options['max'] ?? null; unset($options['value'], $options['min'], $options['max']); diff --git a/src/Symfony/Component/Validator/Constraints/Length.php b/src/Symfony/Component/Validator/Constraints/Length.php index 717e5b2c4ce8f..7585b417d45c5 100644 --- a/src/Symfony/Component/Validator/Constraints/Length.php +++ b/src/Symfony/Component/Validator/Constraints/Length.php @@ -64,8 +64,8 @@ public function __construct( $exactly = $options['value'] ?? null; } - $min = $min ?? $options['min'] ?? null; - $max = $max ?? $options['max'] ?? null; + $min ??= $options['min'] ?? null; + $max ??= $options['max'] ?? null; unset($options['value'], $options['min'], $options['max']); diff --git a/src/Symfony/Component/Validator/Mapping/Factory/LazyLoadingMetadataFactory.php b/src/Symfony/Component/Validator/Mapping/Factory/LazyLoadingMetadataFactory.php index 74ce3571d95ab..61f5e009cfe9b 100644 --- a/src/Symfony/Component/Validator/Mapping/Factory/LazyLoadingMetadataFactory.php +++ b/src/Symfony/Component/Validator/Mapping/Factory/LazyLoadingMetadataFactory.php @@ -87,7 +87,7 @@ public function getMetadataFor(mixed $value): MetadataInterface } $cacheItem = $this->cache?->getItem($this->escapeClassName($class)); - if ($cacheItem && $cacheItem->isHit()) { + if ($cacheItem?->isHit()) { $metadata = $cacheItem->get(); // Include constraints from the parent class diff --git a/src/Symfony/Component/Validator/Mapping/MemberMetadata.php b/src/Symfony/Component/Validator/Mapping/MemberMetadata.php index 8de2d5ef1591b..428e16a46d775 100644 --- a/src/Symfony/Component/Validator/Mapping/MemberMetadata.php +++ b/src/Symfony/Component/Validator/Mapping/MemberMetadata.php @@ -141,8 +141,6 @@ public function isPrivate(object|string $objectOrClassName): bool /** * Returns the reflection instance for accessing the member's value. - * - * @return \ReflectionMethod|\ReflectionProperty */ public function getReflectionMember(object|string $objectOrClassName): \ReflectionMethod|\ReflectionProperty { diff --git a/src/Symfony/Component/Validator/Validation.php b/src/Symfony/Component/Validator/Validation.php index 169984bbcebd4..3df02e118c4b9 100644 --- a/src/Symfony/Component/Validator/Validation.php +++ b/src/Symfony/Component/Validator/Validation.php @@ -51,7 +51,7 @@ public static function createIsValidCallable(Constraint|ValidatorInterface $cons $validator = null; } - $validator = $validator ?? self::createValidator(); + $validator ??= self::createValidator(); return static function (mixed $value, ConstraintViolationListInterface &$violations = null) use ($constraints, $validator): bool { $violations = $validator->validate($value, $constraints); diff --git a/src/Symfony/Component/VarDumper/Caster/Caster.php b/src/Symfony/Component/VarDumper/Caster/Caster.php index 53f4461d0df80..517138b393b14 100644 --- a/src/Symfony/Component/VarDumper/Caster/Caster.php +++ b/src/Symfony/Component/VarDumper/Caster/Caster.php @@ -61,7 +61,7 @@ public static function castObject(object $obj, string $class, bool $hasDebugInfo if ($a) { static $publicProperties = []; - $debugClass = $debugClass ?? get_debug_type($obj); + $debugClass ??= get_debug_type($obj); $i = 0; $prefixedKeys = []; diff --git a/src/Symfony/Component/VarDumper/Tests/Dumper/ServerDumperTest.php b/src/Symfony/Component/VarDumper/Tests/Dumper/ServerDumperTest.php index 447d4856f7329..ff4727538399c 100644 --- a/src/Symfony/Component/VarDumper/Tests/Dumper/ServerDumperTest.php +++ b/src/Symfony/Component/VarDumper/Tests/Dumper/ServerDumperTest.php @@ -37,6 +37,9 @@ public function testDumpForwardsToWrappedDumperWhenServerIsUnavailable() $dumper->dump($data); } + /** + * @group transient-on-macos + */ public function testDump() { $wrappedDumper = $this->createMock(DataDumperInterface::class); diff --git a/src/Symfony/Component/VarDumper/Tests/Server/ConnectionTest.php b/src/Symfony/Component/VarDumper/Tests/Server/ConnectionTest.php index 70629a221569a..ee89d74d0af3d 100644 --- a/src/Symfony/Component/VarDumper/Tests/Server/ConnectionTest.php +++ b/src/Symfony/Component/VarDumper/Tests/Server/ConnectionTest.php @@ -22,6 +22,9 @@ class ConnectionTest extends TestCase { private const VAR_DUMPER_SERVER = 'tcp://127.0.0.1:9913'; + /** + * @group transient-on-macos + */ public function testDump() { $cloner = new VarCloner(); diff --git a/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php b/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php index 37dad66cfe2cb..18d892f2fe6a0 100644 --- a/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php +++ b/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php @@ -73,7 +73,7 @@ protected function findPlaces(Definition $definition, Marking $marking = null): if (\in_array($place, $definition->getInitialPlaces(), true)) { $attributes['style'] = 'filled'; } - if ($marking && $marking->has($place)) { + if ($marking?->has($place)) { $attributes['color'] = '#FF0000'; $attributes['shape'] = 'doublecircle'; } diff --git a/src/Symfony/Component/Workflow/Dumper/MermaidDumper.php b/src/Symfony/Component/Workflow/Dumper/MermaidDumper.php index 67d296ea0ed2a..da11298ec9fe8 100644 --- a/src/Symfony/Component/Workflow/Dumper/MermaidDumper.php +++ b/src/Symfony/Component/Workflow/Dumper/MermaidDumper.php @@ -73,7 +73,7 @@ public function dump(Definition $definition, Marking $marking = null, array $opt $place, $meta->getPlaceMetadata($place), \in_array($place, $definition->getInitialPlaces()), - null !== $marking && $marking->has($place) + $marking?->has($place) ?? false ); $output[] = $placeNode; diff --git a/src/Symfony/Component/Workflow/Dumper/PlantUmlDumper.php b/src/Symfony/Component/Workflow/Dumper/PlantUmlDumper.php index f6b2536372019..9f109545a8f89 100644 --- a/src/Symfony/Component/Workflow/Dumper/PlantUmlDumper.php +++ b/src/Symfony/Component/Workflow/Dumper/PlantUmlDumper.php @@ -200,7 +200,7 @@ private function getState(string $place, Definition $definition, Marking $markin $output = "state $placeEscaped". (\in_array($place, $definition->getInitialPlaces(), true) ? ' '.self::INITIAL : ''). - ($marking && $marking->has($place) ? ' '.self::MARKED : ''); + ($marking?->has($place) ? ' '.self::MARKED : ''); $backgroundColor = $workflowMetadata->getMetadata('bg_color', $place); if (null !== $backgroundColor) { diff --git a/src/Symfony/Component/Workflow/Tests/EventListener/GuardListenerTest.php b/src/Symfony/Component/Workflow/Tests/EventListener/GuardListenerTest.php index a767ae5e5a537..f8907ed4e5de9 100644 --- a/src/Symfony/Component/Workflow/Tests/EventListener/GuardListenerTest.php +++ b/src/Symfony/Component/Workflow/Tests/EventListener/GuardListenerTest.php @@ -137,7 +137,7 @@ public function testGuardExpressionBlocks() private function createEvent(Transition $transition = null) { $subject = new Subject(); - $transition = $transition ?? new Transition('name', 'from', 'to'); + $transition ??= new Transition('name', 'from', 'to'); $workflow = $this->createMock(WorkflowInterface::class); diff --git a/src/Symfony/Component/Yaml/Command/LintCommand.php b/src/Symfony/Component/Yaml/Command/LintCommand.php index f71bb449167d0..243260ea2bd02 100644 --- a/src/Symfony/Component/Yaml/Command/LintCommand.php +++ b/src/Symfony/Component/Yaml/Command/LintCommand.php @@ -11,8 +11,8 @@ namespace Symfony\Component\Yaml\Command; -use Symfony\Component\Console\CI\GithubActionReporter; use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\CI\GithubActionReporter; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Completion\CompletionInput; use Symfony\Component\Console\Completion\CompletionSuggestions; diff --git a/src/Symfony/Contracts/Cache/CacheTrait.php b/src/Symfony/Contracts/Cache/CacheTrait.php index d245df651f5c4..9ac5a6df38f53 100644 --- a/src/Symfony/Contracts/Cache/CacheTrait.php +++ b/src/Symfony/Contracts/Cache/CacheTrait.php @@ -43,7 +43,7 @@ public function delete(string $key): bool private function doGet(CacheItemPoolInterface $pool, string $key, callable $callback, ?float $beta, array &$metadata = null, LoggerInterface $logger = null): mixed { - if (0 > $beta = $beta ?? 1.0) { + if (0 > $beta ??= 1.0) { throw new class(sprintf('Argument "$beta" provided to "%s::get()" must be a positive number, %f given.', static::class, $beta)) extends \InvalidArgumentException implements InvalidArgumentException { }; } @@ -58,7 +58,7 @@ private function doGet(CacheItemPoolInterface $pool, string $key, callable $call if ($recompute = $ctime && $expiry && $expiry <= ($now = microtime(true)) - $ctime / 1000 * $beta * log(random_int(1, \PHP_INT_MAX) / \PHP_INT_MAX)) { // force applying defaultLifetime to expiry $item->expiresAt(null); - $logger && $logger->info('Item "{key}" elected for early recomputation {delta}s before its expiration', [ + $logger?->info('Item "{key}" elected for early recomputation {delta}s before its expiration', [ 'key' => $key, 'delta' => sprintf('%.1f', $expiry - $now), ]);