8000 Add more nullsafe operators by nicolas-grekas · Pull Request #44659 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

Add more nullsafe operators #44659

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 24 commits into from
Dec 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
ee211c4
[VarDumper] add more "transient-on-macos" groups
nicolas-grekas Dec 15, 2021
6617be4
[HttpKernel] fix how configuring log-level and status-code by excepti…
nicolas-grekas Dec 15, 2021
6bcc3cb
Revert "feature #41989 [Cache] make `LockRegistry` use semaphores whe…
nicolas-grekas Dec 16, 2021
b968514
[Cache] disable lock on CLI
nicolas-grekas Dec 16, 2021
06b25c7
[HttpClient] Fix tracing requests made after calling withOptions()
nicolas-grekas Dec 16, 2021
981cb0c
Remove pointless assignment
derrabus Dec 16, 2021
6312ef2
minor #44674 [Messenger] Remove pointless assignment (derrabus)
nicolas-grekas Dec 16, 2021
d737dab
fix merge
nicolas-grekas Dec 16, 2021
6e3b711
CS fixes
nicolas-grekas Dec 16, 2021
f1914c0
minor #44679 CS fixes (nicolas-grekas)
nicolas-grekas Dec 16, 2021
311dc83
bug #44669 [Cache] disable lock on CLI (nicolas-grekas)
nicolas-grekas Dec 16, 2021
0812726
[Cache] Fix saving items with no expiration through ProxyAdapter
sbelyshkin Dec 12, 2021
aaa18df
bug #44577 [Cache] Fix proxy no expiration to the Redis (Sergey Belys…
nicolas-grekas Dec 16, 2021
7e26952
Merge branch '4.4' into 5.3
nicolas-grekas Dec 16, 2021
ad3010b
[5.3] cs fixes
nicolas-grekas Dec 16, 2021
f190e9e
bug #44671 [HttpClient] Fix tracing requests made after calling withO…
nicolas-grekas Dec 16, 2021
61be138
Merge branch '5.3' into 5.4
nicolas-grekas Dec 16, 2021
b6d4480
[5.4] cs fixes
nicolas-grekas Dec 16, 2021
eb60956
bug #44667 [Cache] Revert "feature #41989 make `LockRegistry` use se…
nicolas-grekas Dec 16, 2021
646c33f
bug #44649 [HttpKernel] fix how configuring log-level and status-code…
nicolas-grekas Dec 16, 2021
eb749ec
Merge branch '5.4' into 6.0
nicolas-grekas Dec 16, 2021
d5534b0
[6.0] cs fixes
nicolas-grekas Dec 16, 2021
5eb8777
Merge branch '6.0' into 6.1
nicolas-grekas Dec 16, 2021
56f908a
Add more nullsafe operators
nicolas-grekas Dec 16, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
])
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bridge/Doctrine/Validator/DoctrineLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bridge/Twig/AppVariable.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public function getSession(): ?Session
}
$request = $this->getRequest();

return $request && $request->hasSession() ? $request->getSession() : null;
return $request?->hasSession() ? $request->getSession() : null;
}

/**
Expand Down
6 changes: 0 additions & 6 deletions src/Symfony/Bridge/Twig/UndefinedCallableHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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])) {
Expand All @@ -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])) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@
class WorkflowDumpCommand extends Command
{
/**
* string is the service id
* string is the service id.
*
* @var array<string, Definition>
*/
private array $workflows = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
2 changes: 0 additions & 2 deletions src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
2 changes: 0 additions & 2 deletions src/Symfony/Bundle/FrameworkBundle/Test/TestContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Cache/Adapter/AbstractAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
14 changes: 7 additions & 7 deletions src/Symfony/Component/Cache/Adapter/ArrayAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 3 additions & 3 deletions src/Symfony/Component/Cache/Adapter/ChainAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/Cache/Adapter/PhpFilesAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down Expand Up @@ -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])) {
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Cache/Adapter/ProxyAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
10 changes: 5 additions & 5 deletions src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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) {
Expand All @@ -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) {
Expand All @@ -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);

Expand Down Expand Up @@ -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]];
Expand Down
1 change: 0 additions & 1 deletion src/Symfony/Component/Cache/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
55 changes: 15 additions & 40 deletions src/Symfony/Component/Cache/LockRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -76,41 +76,33 @@ 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);
}

while (true) {
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);

Expand All @@ -125,41 +117,28 @@ 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:{}}");
$signalingCallback = $signalingCallback ?? function () use ($signalingException) { throw $signalingException; };

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;
} catch (\Exception $e) {
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()]);
}
}

Expand All @@ -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;
}
Expand Down
Loading
0