minor #42165 Simplify some code with null coalesce operator (javiereguiluz)
This PR was squashed before being merged into the 4.4 branch.
Discussion
----------
Simplify some code with null coalesce operator
| Q | A
| ------------- | ---
| Branch? | 4.4
| Bug fix? | no
| New feature? | no
| Deprecations? | no
| Tickets | -
| License | MIT
| Doc PR | -
For your consideration. There are many other possible usages of null coalesce operator, but the result is not very readable ... so this PR only contains the changes where the result is clearly better.
Commits
-------
17ad5b75fa
Simplify some code with null coalesce operator
This commit is contained in:
commit
20d3d843ad
|
@ -54,7 +54,7 @@ class ContainerAwareEventManager extends EventManager
|
|||
return;
|
||||
}
|
||||
|
||||
$eventArgs = null === $eventArgs ? EventArgs::getEmptyInstance() : $eventArgs;
|
||||
$eventArgs = $eventArgs ?? EventArgs::getEmptyInstance();
|
||||
|
||||
if (!isset($this->initialized[$eventName])) {
|
||||
$this->initializeListeners($eventName);
|
||||
|
|
|
@ -163,7 +163,7 @@ class UniqueEntityValidator extends ConstraintValidator
|
|||
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)
|
||||
|
|
|
@ -278,10 +278,6 @@ EOT
|
|||
|
||||
$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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -134,7 +134,7 @@ class JsonDescriptor extends Descriptor
|
|||
|
||||
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 = [])
|
||||
|
|
|
@ -258,7 +258,7 @@ class MarkdownDescriptor extends Descriptor
|
|||
|
||||
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) {
|
||||
|
|
|
@ -442,7 +442,7 @@ class TextDescriptor extends Descriptor
|
|||
|
||||
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);
|
||||
|
|
|
@ -88,7 +88,7 @@ class XmlDescriptor extends Descriptor
|
|||
|
||||
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 = [])
|
||||
|
|
|
@ -144,7 +144,7 @@ trait ControllerTrait
|
|||
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;
|
||||
}
|
||||
|
|
|
@ -141,7 +141,7 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
|
|||
}
|
||||
|
||||
$this->values[$key] = $value;
|
||||
$this->expiries[$key] = null !== $expiry ? $expiry : \PHP_INT_MAX;
|
||||
$this->expiries[$key] = $expiry ?? \PHP_INT_MAX;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
|
|
@ -172,7 +172,7 @@ trait RedisTrait
|
|||
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)) {
|
||||
|
|
|
@ -53,6 +53,6 @@ final class ConsoleErrorEvent extends ConsoleEvent
|
|||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -143,7 +143,7 @@ class MergeExtensionConfigurationParameterBag extends EnvPlaceholderParameterBag
|
|||
*/
|
||||
public function getEnvPlaceholders(): array
|
||||
{
|
||||
return null !== $this->processedEnvPlaceholders ? $this->processedEnvPlaceholders : parent::getEnvPlaceholders();
|
||||
return $this->processedEnvPlaceholders ?? parent::getEnvPlaceholders();
|
||||
}
|
||||
|
||||
public function getUnusedEnvPlaceholders(): array
|
||||
|
|
|
@ -1630,7 +1630,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
|
|||
*/
|
||||
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;
|
||||
|
|
|
@ -34,7 +34,7 @@ class IntegerToLocalizedStringTransformer extends NumberToLocalizedStringTransfo
|
|||
@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;
|
||||
}
|
||||
|
||||
|
|
|
@ -62,6 +62,6 @@ class TextType extends AbstractType implements DataTransformerInterface
|
|||
*/
|
||||
public function reverseTransform($data)
|
||||
{
|
||||
return null === $data ? '' : $data;
|
||||
return $data ?? '';
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1371,7 +1371,7 @@ class Request
|
|||
$this->format = $this->attributes->get('_format');
|
||||
}
|
||||
|
||||
return null === $this->format ? $default : $this->format;
|
||||
return $this->format ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -94,10 +94,6 @@ class RequestStack
|
|||
{
|
||||
$pos = \count($this->requests) - 2;
|
||||
|
||||
if (!isset($this->requests[$pos])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->requests[$pos];
|
||||
return $this->requests[$pos] ?? null;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -176,7 +176,7 @@ class ResponseHeaderBag extends HeaderBag
|
|||
*/
|
||||
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)
|
||||
|
|
|
@ -163,6 +163,6 @@ class MetadataBag implements SessionBagInterface
|
|||
{
|
||||
$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');
|
||||
}
|
||||
}
|
||||
|
|
|
@ -60,7 +60,7 @@ class DebugHandlersListener implements EventSubscriberInterface
|
|||
|
||||
$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;
|
||||
|
|
|
@ -156,11 +156,7 @@ class Profile
|
|||
*/
|
||||
public function getTime()
|
||||
{
|
||||
if (null === $this->time) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return $this->time;
|
||||
return $this->time ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -709,7 +709,7 @@ EOF
|
|||
$bundle
|
||||
->expects($this->any())
|
||||
->method('getName')
|
||||
->willReturn(null === $bundleName ? \get_class($bundle) : $bundleName)
|
||||
->willReturn($bundleName ?? \get_class($bundle))
|
||||
;
|
||||
|
||||
$bundle
|
||||
|
|
|
@ -142,8 +142,8 @@ abstract class IntlDateFormatter
|
|||
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();
|
||||
|
|
|
@ -933,7 +933,7 @@ abstract class AbstractIntlDateFormatterTest extends TestCase
|
|||
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;
|
||||
|
|
|
@ -95,7 +95,7 @@ final class GitRepository
|
|||
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;
|
||||
|
|
|
@ -260,7 +260,7 @@ class DummyReceiver implements ReceiverInterface
|
|||
{
|
||||
$val = array_shift($this->deliveriesOfEnvelopes);
|
||||
|
||||
return null === $val ? [] : $val;
|
||||
return $val ?? [];
|
||||
}
|
||||
|
||||
public function ack(Envelope $envelope): void
|
||||
|
|
|
@ -66,9 +66,9 @@ class PhpDocExtractor implements PropertyDescriptionExtractorInterface, Property
|
|||
$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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -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;
|
||||
|
||||
|
|
|
@ -58,7 +58,7 @@ class RememberMeListener extends AbstractListener implements ListenerInterface
|
|||
}
|
||||
|
||||
$this->catchExceptions = $catchExceptions;
|
||||
$this->sessionStrategy = null === $sessionStrategy ? new SessionAuthenticationStrategy(SessionAuthenticationStrategy::MIGRATE) : $sessionStrategy;
|
||||
$this->sessionStrategy = $sessionStrategy ?? new SessionAuthenticationStrategy(SessionAuthenticationStrategy::MIGRATE);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -99,7 +99,7 @@ class ExceptionListenerTest extends TestCase
|
|||
$listener->onKernelException($event);
|
||||
|
||||
$this->assertNull($event->getResponse());
|
||||
$this->assertSame(null === $eventException ? $exception : $eventException, $event->getThrowable()->getPrevious());
|
||||
$this->assertSame($eventException ?? $exception, $event->getThrowable()->getPrevious());
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -122,7 +122,7 @@ class ExceptionListenerTest extends TestCase
|
|||
|
||||
$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());
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -139,7 +139,7 @@ class ExceptionListenerTest extends TestCase
|
|||
$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());
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -156,7 +156,7 @@ class ExceptionListenerTest extends TestCase
|
|||
$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()
|
||||
|
|
|
@ -112,10 +112,10 @@ class File extends Constraint
|
|||
];
|
||||
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));
|
||||
}
|
||||
|
|
|
@ -60,7 +60,7 @@ class FileValidator extends ConstraintValidator
|
|||
$binaryFormat = $constraint->binaryFormat;
|
||||
} else {
|
||||
$limitInBytes = $iniLimitSize;
|
||||
$binaryFormat = null === $constraint->binaryFormat ? true : $constraint->binaryFormat;
|
||||
$binaryFormat = $constraint->binaryFormat ?? true;
|
||||
}
|
||||
|
||||
[, $limitAsString, $suffix] = $this->factorizeSizes(0, $limitInBytes, $binaryFormat);
|
||||
|
|
|
@ -365,11 +365,7 @@ class ClassMetadata extends GenericMetadata implements ClassMetadataInterface
|
|||
*/
|
||||
public function getPropertyMetadata($property)
|
||||
{
|
||||
if (!isset($this->members[$property])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->members[$property];
|
||||
return $this->members[$property] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -63,7 +63,7 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
|
|||
*/
|
||||
public function setOutput($output)
|
||||
{
|
||||
$prev = null !== $this->outputStream ? $this->outputStream : $this->lineDumper;
|
||||
$prev = $this->outputStream ?? $this->lineDumper;
|
||||
|
||||
if (\is_callable($output)) {
|
||||
$this->outputStream = null;
|
||||
|
|
|
@ -153,7 +153,7 @@ class HtmlDumper extends CliDumper
|
|||
*/
|
||||
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;
|
||||
|
@ -964,7 +964,7 @@ EOHTML
|
|||
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;
|
||||
}
|
||||
|
||||
|
|
Reference in New Issue