Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Simplify some code with null coalesce operator #42165

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 1 commit into from
Jul 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function dispatchEvent($eventName, EventArgs $eventArgs = null)
return;
}

$eventArgs = null === $eventArgs ? EventArgs::getEmptyInstance() : $eventArgs;
$eventArgs = $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 @@ -163,7 +163,7 @@ public function validate($entity, Constraint $constraint)
return;
}

$errorPath = null !== $constraint->errorPath ? $constraint->errorPath : $fields[0];
$errorPath = $constraint->errorPath ?? $fields[0];
$invalidValue = $criteria[$errorPath] ?? $criteria[$fields[0]];

$this->context->buildViolation($constraint->message)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -278,10 +278,6 @@ private function getPublicDirectory(ContainerInterface $container): string

$composerConfig = json_decode(file_get_contents($composerFilePath), true);

if (isset($composerConfig['extra']['public-dir'])) {
return $composerConfig['extra']['public-dir'];
}

return $defaultPublicDir;
return $composerConfig['extra']['public-dir'] ?? $defaultPublicDir;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ protected function describeContainerAlias(Alias $alias, array $options = [], Con

protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = [])
{
$this->writeData($this->getEventDispatcherListenersData($eventDispatcher, \array_key_exists('event', $options) ? $options['event'] : null), $options);
$this->writeData($this->getEventDispatcherListenersData($eventDispatcher, $options['event'] ?? null), $options);
}

protected function describeCallable($callable, array $options = [])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ protected function describeContainerEnvVars(array $envs, array $options = [])

protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = [])
{
$event = \array_key_exists('event', $options) ? $options['event'] : null;
$event = $options['event'] ?? null;

$title = 'Registered listeners';
if (null !== $event) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,7 @@ protected function describeContainerEnvVars(array $envs, array $options = [])

protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = [])
{
$event = \array_key_exists('event', $options) ? $options['event'] : null;
$event = $options['event'] ?? null;

if (null !== $event) {
$title = sprintf('Registered Listeners for "%s" Event', $event);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ protected function describeContainerAlias(Alias $alias, array $options = [], Con

protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = [])
{
$this->writeDocument($this->getEventDispatcherListenersDocument($eventDispatcher, \array_key_exists('event', $options) ? $options['event'] : null));
$this->writeDocument($this->getEventDispatcherListenersDocument($eventDispatcher, $options['event'] ?? null));
}

protected function describeCallable($callable, array $options = [])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ protected function json($data, int $status = 200, array $headers = [], array $co
protected function file($file, string $fileName = null, string $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse
{
$response = new BinaryFileResponse($file);
$response->setContentDisposition($disposition, null === $fileName ? $response->getFile()->getFilename() : $fileName);
$response->setContentDisposition($disposition, $fileName ?? $response->getFile()->getFilename());

return $response;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Cache/Adapter/ArrayAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ public function save(CacheItemInterface $item)
}

$this->values[$key] = $value;
$this->expiries[$key] = null !== $expiry ? $expiry : \PHP_INT_MAX;
$this->expiries[$key] = $expiry ?? \PHP_INT_MAX;

return true;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Cache/Traits/RedisTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ public static function createConnection($dsn, array $options = [])
if (null === $params['class'] && !isset($params['redis_sentinel']) && \extension_loaded('redis')) {
$class = $params['redis_cluster'] ? \RedisCluster::class : (1 < \count($hosts) ? \RedisArray::class : \Redis::class);
} else {
$class = null === $params['class'] ? \Predis\Client::class : $params['class'];
$class = $params['class'] ?? \Predis\Client::class;
}

if (is_a($class, \Redis::class, true)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,6 @@ public function setExitCode(int $exitCode): void

public function getExitCode(): int
{
return null !== $this->exitCode ? $this->exitCode : (\is_int($this->error->getCode()) && 0 !== $this->error->getCode() ? $this->error->getCode() : 1);
return $this->exitCode ?? (\is_int($this->error->getCode()) && 0 !== $this->error->getCode() ? $this->error->getCode() : 1);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ public function freezeAfterProcessing(Extension $extension, ContainerBuilder $co
*/
public function getEnvPlaceholders(): array
{
return null !== $this->processedEnvPlaceholders ? $this->processedEnvPlaceholders : parent::getEnvPlaceholders();
return $this->processedEnvPlaceholders ?? parent::getEnvPlaceholders();
}

public function getUnusedEnvPlaceholders(): array
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1630,7 +1630,7 @@ private function callMethod($service, array $call, array &$inlineServices)
*/
private function shareService(Definition $definition, $service, ?string $id, array &$inlineServices)
{
$inlineServices[null !== $id ? $id : spl_object_hash($definition)] = $service;
$inlineServices[$id ?? spl_object_hash($definition)] = $service;

if (null !== $id && $definition->isShared()) {
$this->services[$id] = $service;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function __construct($grouping = false, $roundingMode = self::ROUND_DOWN,
@trigger_error(sprintf('Passing a precision as the first value to %s::__construct() is deprecated since Symfony 4.2 and support for it will be dropped in 5.0.', __CLASS__), \E_USER_DEPRECATED);

$grouping = $roundingMode;
$roundingMode = null !== $locale ? $locale : self::ROUND_DOWN;
$roundingMode = $locale ?? self::ROUND_DOWN;
$locale = null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,6 @@ public function transform($data)
*/
public function reverseTransform($data)
{
return null === $data ? '' : $data;
return $data ?? '';
}
}
2 changes: 1 addition & 1 deletion src/Symfony/Component/HttpFoundation/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -1371,7 +1371,7 @@ public function getRequestFormat($default = 'html')
$this->format = $this->attributes->get('_format');
}

return null === $this->format ? $default : $this->format;
return $this->format ?? $default;
}

/**
Expand Down
6 changes: 1 addition & 5 deletions src/Symfony/Component/HttpFoundation/RequestStack.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,6 @@ public function getParentRequest()
{
$pos = \count($this->requests) - 2;

if (!isset($this->requests[$pos])) {
return null;
}

return $this->requests[$pos];
return $this->requests[$pos] ?? null;
}
}
2 changes: 1 addition & 1 deletion src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ public function hasCacheControlDirective($key)
*/
public function getCacheControlDirective($key)
{
return \array_key_exists($key, $this->computedCacheControl) ? $this->computedCacheControl[$key] : null;
return $this->computedCacheControl[$key] ?? null;
}

public function setCookie(Cookie $cookie)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,6 @@ private function stampCreated(int $lifetime = null): void
{
$timeStamp = time();
$this->meta[self::CREATED] = $this->meta[self::UPDATED] = $this->lastUsed = $timeStamp;
$this->meta[self::LIFETIME] = (null === $lifetime) ? ini_get('session.cookie_lifetime') : $lifetime;
$this->meta[self::LIFETIME] = $lifetime ?? ini_get('session.cookie_lifetime');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public function __construct(callable $exceptionHandler = null, LoggerInterface $

$this->exceptionHandler = $exceptionHandler;
$this->logger = $logger;
$this->levels = null === $levels ? \E_ALL : $levels;
$this->levels = $levels ?? \E_ALL;
$this->throwAt = \is_int($throwAt) ? $throwAt : (null === $throwAt ? null : ($throwAt ? \E_ALL : null));
$this->scream = $scream;
$this->fileLinkFormat = $fileLinkFormat;
Expand Down
6 changes: 1 addition & 5 deletions src/Symfony/Component/HttpKernel/Profiler/Profile.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,7 @@ public function setUrl($url)
*/
public function getTime()
{
if (null === $this->time) {
return 0;
}

return $this->time;
return $this->time ?? 0;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/HttpKernel/Tests/KernelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -709,7 +709,7 @@ protected function getBundle($dir = null, $parent = null, $className = null, $bu
$bundle
->expects($this->any())
->method('getName')
->willReturn(null === $bundleName ? \get_class($bundle) : $bundleName)
->willReturn($bundleName ?? \get_class($bundle))
;

$bundle
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,8 @@ public function __construct(?string $locale, ?int $datetype, ?int $timetype, $ti
throw new MethodArgumentValueNotImplementedException(__METHOD__, 'calendar', $calendar, 'Only the GREGORIAN calendar is supported');
}

$this->datetype = null !== $datetype ? $datetype : self::FULL;
$this->timetype = null !== $timetype ? $timetype : self::FULL;
$this->datetype = $datetype ?? self::FULL;
$this->timetype = $timetype ?? self::FULL;

if ('' === ($pattern ?? '')) {
$pattern = $this->getDefaultPattern();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -933,7 +933,7 @@ protected function getDefaultDateFormatter($pattern = null)
protected function getDateTime($timestamp, $timeZone)
{
$dateTime = new \DateTime();
$dateTime->setTimestamp(null === $timestamp ? time() : $timestamp);
$dateTime->setTimestamp($timestamp ?? time());
$dateTime->setTimezone(new \DateTimeZone($timeZone ?: getenv('TZ') ?: 'UTC'));

return $dateTime;
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Intl/Util/GitRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ private static function exec(string $command, string $customErrorMessage = null)
exec(sprintf('%s 2>&1', $command), $output, $result);

if (0 !== $result) {
throw new RuntimeException(null !== $customErrorMessage ? $customErrorMessage : sprintf('The "%s" command failed.', $command));
throw new RuntimeException($customErrorMessage ?? sprintf('The "%s" command failed.', $command));
}

return $output;
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Messenger/Tests/WorkerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ public function get(): iterable
{
$val = array_shift($this->deliveriesOfEnvelopes);

return null === $val ? [] : $val;
return $val ?? [];
}

public function ack(Envelope $envelope): void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,9 @@ public function __construct(DocBlockFactoryInterface $docBlockFactory = null, ar
$this->docBlockFactory = $docBlockFactory ?: DocBlockFactory::createInstance();
$this->contextFactory = new ContextFactory();
$this->phpDocTypeHelper = new PhpDocTypeHelper();
$this->mutatorPrefixes = null !== $mutatorPrefixes ? $mutatorPrefixes : ReflectionExtractor::$defaultMutatorPrefixes;
$this->accessorPrefixes = null !== $accessorPrefixes ? $accessorPrefixes : ReflectionExtractor::$defaultAccessorPrefixes;
$this->arrayMutatorPrefixes = null !== $arrayMutatorPrefixes ? $arrayMutatorPrefixes : ReflectionExtractor::$defaultArrayMutatorPrefixes;
$this->mutatorPrefixes = $mutatorPrefixes ?? ReflectionExtractor::$defaultMutatorPrefixes;
$this->accessorPrefixes = $accessorPrefixes ?? ReflectionExtractor::$defaultAccessorPrefixes;
$this->arrayMutatorPrefixes = $arrayMutatorPrefixes ?? ReflectionExtractor::$defaultArrayMutatorPrefixes;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTyp
*/
public function __construct(array $mutatorPrefixes = null, array $accessorPrefixes = null, array $arrayMutatorPrefixes = null, bool $enableConstructorExtraction = true, int $accessFlags = self::ALLOW_PUBLIC)
{
$this->mutatorPrefixes = null !== $mutatorPrefixes ? $mutatorPrefixes : self::$defaultMutatorPrefixes;
$this->accessorPrefixes = null !== $accessorPrefixes ? $accessorPrefixes : self::$defaultAccessorPrefixes;
$this->arrayMutatorPrefixes = null !== $arrayMutatorPrefixes ? $arrayMutatorPrefixes : self::$defaultArrayMutatorPrefixes;
$this->mutatorPrefixes = $mutatorPrefixes ?? self::$defaultMutatorPrefixes;
$this->accessorPrefixes = $accessorPrefixes ?? self::$defaultAccessorPrefixes;
$this->arrayMutatorPrefixes = $arrayMutatorPrefixes ?? self::$defaultArrayMutatorPrefixes;
$this->enableConstructorExtraction = $enableConstructorExtraction;
$this->accessFlags = $accessFlags;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public function __construct(TokenStorageInterface $tokenStorage, RememberMeServi
}

$this->catchExceptions = $catchExceptions;
$this->sessionStrategy = null === $sessionStrategy ? new SessionAuthenticationStrategy(SessionAuthenticationStrategy::MIGRATE) : $sessionStrategy;
$this->sessionStrategy = $sessionStrategy ?? new SessionAuthenticationStrategy(SessionAuthenticationStrategy::MIGRATE);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public function testAccessDeniedExceptionFullFledgedAndWithoutAccessDeniedHandle
$listener->onKernelException($event);

$this->assertNull($event->getResponse());
$this->assertSame(null === $eventException ? $exception : $eventException, $event->getThrowable()->getPrevious());
$this->assertSame($eventException ?? $exception, $event->getThrowable()->getPrevious());
}

/**
Expand All @@ -122,7 +122,7 @@ public function testAccessDeniedExceptionFullFledgedAndWithoutAccessDeniedHandle

$this->assertEquals('Unauthorized', $event->getResponse()->getContent());
$this->assertEquals(401, $event->getResponse()->getStatusCode());
$this->assertSame(null === $eventException ? $exception : $eventException, $event->getThrowable()->getPrevious());
$this->assertSame($eventException ?? $exception, $event->getThrowable()->getPrevious());
}

/**
Expand All @@ -139,7 +139,7 @@ public function testAccessDeniedExceptionFullFledgedAndWithAccessDeniedHandlerAn
$listener->onKernelException($event);

$this->assertEquals('error', $event->getResponse()->getContent());
$this->assertSame(null === $eventException ? $exception : $eventException, $event->getThrowable()->getPrevious());
$this->assertSame($eventException ?? $exception, $event->getThrowable()->getPrevious());
}

/**
Expand All @@ -156,7 +156,7 @@ public function testAccessDeniedExceptionNotFullFledged(\Exception $exception, \
$listener->onKernelException($event);

$this->assertEquals('OK', $event->getResponse()->getContent());
$this->assertSame(null === $eventException ? $exception : $eventException, $event->getThrowable()->getPrevious());
$this->assertSame($eventException ?? $exception, $event->getThrowable()->getPrevious());
}

public function testLogoutException()
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/Validator/Constraints/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,10 @@ private function normalizeBinaryFormat($maxSize)
];
if (ctype_digit((string) $maxSize)) {
$this->maxSize = (int) $maxSize;
$this->binaryFormat = null === $this->binaryFormat ? false : $this->binaryFormat;
$this->binaryFormat = $this->binaryFormat ?? false;
} elseif (preg_match('/^(\d++)('.implode('|', array_keys($factors)).')$/i', $maxSize, $matches)) {
$this->maxSize = $matches[1] * $factors[$unit = strtolower($matches[2])];
$this->binaryFormat = null === $this->binaryFormat ? 2 === \strlen($unit) : $this->binaryFormat;
$this->binaryFormat = $this->binaryFormat ?? (2 === \strlen($unit));
} else {
throw new ConstraintDefinitionException(sprintf('"%s" is not a valid maximum size.', $this->maxSize));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public function validate($value, Constraint $constraint)
$binaryFormat = $constraint->binaryFormat;
} else {
$limitInBytes = $iniLimitSize;
$binaryFormat = null === $constraint->binaryFormat ? true : $constraint->binaryFormat;
$binaryFormat = $constraint->binaryFormat ?? true;
}

[, $limitAsString, $suffix] = $this->factorizeSizes(0, $limitInBytes, $binaryFormat);
Expand Down
6 changes: 1 addition & 5 deletions src/Symfony/Component/Validator/Mapping/ClassMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -365,11 +365,7 @@ public function hasPropertyMetadata($property)
*/
public function getPropertyMetadata($property)
{
if (!isset($this->members[$property])) {
return [];
}

return $this->members[$property];
return $this->members[$property] ?? [];
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/VarDumper/Dumper/AbstractDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public function __construct($output = null, string $charset = null, int $flags =
*/
public function setOutput($output)
{
$prev = null !== $this->outputStream ? $this->outputStream : $this->lineDumper;
$prev = $this->outputStream ?? $this->lineDumper;

if (\is_callable($output)) {
$this->outputStream = null;
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public function dump(Data $data, $output = null, array $extraDisplayOptions = []
*/
protected function getDumpHeader()
{
$this->headerIsDumped = null !== $this->outputStream ? $this->outputStream : $this->lineDumper;
$this->headerIsDumped = $this->outputStream ?? $this->lineDumper;

if (null !== $this->dumpHeader) {
return $this->dumpHeader;
Expand Down Expand Up @@ -964,7 +964,7 @@ protected function dumpLine($depth, $endOfValue = false)
if (-1 === $this->lastDepth) {
$this->line = sprintf($this->dumpPrefix, $this->dumpId, $this->indentPad).$this->line;
}
if ($this->headerIsDumped !== (null !== $this->outputStream ? $this->outputStream : $this->lineDumper)) {
if ($this->headerIsDumped !== ($this->outputStream ?? $this->lineDumper)) {
$this->line = $this->getDumpHeader().$this->line;
}

Expand Down