Skip to content

Commit

Permalink
minor #44597 Make use of the nullsafe operator (derrabus)
Browse files Browse the repository at this point in the history
This PR was merged into the 6.1 branch.

Discussion
----------

Make use of the nullsafe operator

| Q             | A
| ------------- | ---
| Branch?       | 6.1
| Bug fix?      | no
| New feature?  | no
| Deprecations? | no
| Tickets       | N/A
| License       | MIT
| Doc PR        | N/A

PHP 8 introduced a nullsafe operator which allows us to simplify some of our code.

I have used a PhpStorm inspection to automate the change. I did some minor adjustments afterwards where the fixer left unnecessary paranthesis or local variables.

Commits
-------

d58449d Make use of the nullsafe operator
  • Loading branch information
fabpot committed Dec 13, 2021
2 parents 23f374b + d58449d commit ff4af00
Show file tree
Hide file tree
Showing 68 changed files with 139 additions and 339 deletions.
8 changes: 2 additions & 6 deletions src/Symfony/Bridge/Doctrine/Logger/DbalLogger.php
Expand Up @@ -37,9 +37,7 @@ public function __construct(LoggerInterface $logger = null, Stopwatch $stopwatch
*/
public function startQuery($sql, array $params = null, array $types = null): void
{
if (null !== $this->stopwatch) {
$this->stopwatch->start('doctrine', 'doctrine');
}
$this->stopwatch?->start('doctrine', 'doctrine');

if (null !== $this->logger) {
$this->log($sql, null === $params ? [] : $this->normalizeParams($params));
Expand All @@ -51,9 +49,7 @@ public function startQuery($sql, array $params = null, array $types = null): voi
*/
public function stopQuery(): void
{
if (null !== $this->stopwatch) {
$this->stopwatch->stop('doctrine');
}
$this->stopwatch?->stop('doctrine');
}

/**
Expand Down
Expand Up @@ -30,9 +30,6 @@ public function __construct(ManagerRegistry $registry)

public function initialize(object $object)
{
$manager = $this->registry->getManagerForClass(\get_class($object));
if (null !== $manager) {
$manager->initializeObject($object);
}
$this->registry->getManagerForClass(\get_class($object))?->initializeObject($object);
}
}
4 changes: 1 addition & 3 deletions src/Symfony/Bridge/Twig/Command/LintCommand.php
Expand Up @@ -230,9 +230,7 @@ private function renderException(SymfonyStyle $output, string $template, Error $
{
$line = $exception->getTemplateLine();

if ($githubReporter) {
$githubReporter->error($exception->getRawMessage(), $file, $line <= 0 ? null : $line);
}
$githubReporter?->error($exception->getRawMessage(), $file, $line <= 0 ? null : $line);

if ($file) {
$output->text(sprintf('<error> ERROR </error> in %s (line %s)', $file, $line));
Expand Down
Expand Up @@ -55,9 +55,7 @@ public function warmUp(string $cacheDir): array
try {
$this->dumpExtension($extension, $generator);
} catch (\Exception $e) {
if ($this->logger) {
$this->logger->warning('Failed to generate ConfigBuilder for extension {extensionClass}.', ['exception' => $e, 'extensionClass' => \get_class($extension)]);
}
$this->logger?->warning('Failed to generate ConfigBuilder for extension {extensionClass}.', ['exception' => $e, 'extensionClass' => \get_class($extension)]);
}
}

Expand Down
Expand Up @@ -70,7 +70,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}

$secrets = $this->vault->list($reveal);
$localSecrets = null !== $this->localVault ? $this->localVault->list($reveal) : null;
$localSecrets = $this->localVault?->list($reveal);

$rows = [];

Expand Down
Expand Up @@ -27,9 +27,7 @@ public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('test');

if ($this->customConfig) {
$this->customConfig->addConfiguration($treeBuilder->getRootNode());
}
$this->customConfig?->addConfiguration($treeBuilder->getRootNode());

return $treeBuilder;
}
Expand Down
Expand Up @@ -110,9 +110,7 @@ public function collect(Request $request, Response $response, \Throwable $except

$logoutUrl = null;
try {
if (null !== $this->logoutUrlGenerator) {
$logoutUrl = $this->logoutUrlGenerator->getLogoutPath();
}
$logoutUrl = $this->logoutUrlGenerator?->getLogoutPath();
} catch (\Exception $e) {
// fail silently when the logout URL cannot be generated
}
Expand Down
Expand Up @@ -71,9 +71,7 @@ public function panelAction(Request $request, string $token): Response
{
$this->denyAccessIfProfilerDisabled();

if (null !== $this->cspHandler) {
$this->cspHandler->disableCsp();
}
$this->cspHandler?->disableCsp();

$panel = $request->query->get('panel');
$page = $request->query->get('page', 'home');
Expand Down Expand Up @@ -172,9 +170,7 @@ public function searchBarAction(Request $request): Response
{
$this->denyAccessIfProfilerDisabled();

if (null !== $this->cspHandler) {
$this->cspHandler->disableCsp();
}
$this->cspHandler?->disableCsp();

if (!$request->hasSession()) {
$ip =
Expand Down Expand Up @@ -224,9 +220,7 @@ public function searchResultsAction(Request $request, string $token): Response
{
$this->denyAccessIfProfilerDisabled();

if (null !== $this->cspHandler) {
$this->cspHandler->disableCsp();
}
$this->cspHandler?->disableCsp();

$profile = $this->profiler->loadProfile($token);

Expand Down Expand Up @@ -312,9 +306,7 @@ public function phpinfoAction(): Response
{
$this->denyAccessIfProfilerDisabled();

if (null !== $this->cspHandler) {
$this->cspHandler->disableCsp();
}
$this->cspHandler?->disableCsp();

ob_start();
phpinfo();
Expand All @@ -336,9 +328,7 @@ public function xdebugAction(): Response
throw new NotFoundHttpException('Xdebug must be installed in version 3.');
}

if (null !== $this->cspHandler) {
$this->cspHandler->disableCsp();
}
$this->cspHandler?->disableCsp();

ob_start();
xdebug_info();
Expand All @@ -358,9 +348,7 @@ public function openAction(Request $request): Response
throw new NotFoundHttpException('The base dir should be set.');
}

if ($this->profiler) {
$this->profiler->disable();
}
$this->profiler?->disable();

$file = $request->query->get('file');
$line = $request->query->get('line');
Expand Down
8 changes: 2 additions & 6 deletions src/Symfony/Component/Console/Command/Command.php
Expand Up @@ -421,9 +421,7 @@ public function getNativeDefinition(): InputDefinition
public function addArgument(string $name, int $mode = null, string $description = '', mixed $default = null): static
{
$this->definition->addArgument(new InputArgument($name, $mode, $description, $default));
if (null !== $this->fullDefinition) {
$this->fullDefinition->addArgument(new InputArgument($name, $mode, $description, $default));
}
$this->fullDefinition?->addArgument(new InputArgument($name, $mode, $description, $default));

return $this;
}
Expand All @@ -442,9 +440,7 @@ public function addArgument(string $name, int $mode = null, string $description
public function addOption(string $name, string|array $shortcut = null, int $mode = null, string $description = '', mixed $default = null): static
{
$this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default));
if (null !== $this->fullDefinition) {
$this->fullDefinition->addOption(new InputOption($name, $shortcut, $mode, $description, $default));
}
$this->fullDefinition?->addOption(new InputOption($name, $shortcut, $mode, $description, $default));

return $this;
}
Expand Down
Expand Up @@ -79,7 +79,7 @@ public static function getSubscribedEvents(): array

private static function getInputString(ConsoleEvent $event): ?string
{
$commandName = $event->getCommand() ? $event->getCommand()->getName() : null;
$commandName = $event->getCommand()?->getName();
$input = $event->getInput();

if ($input instanceof \Stringable) {
Expand Down
Expand Up @@ -189,9 +189,7 @@ public function getNotCalledListeners(Request $request = null): array
try {
$allListeners = $this->getListeners();
} catch (\Exception $e) {
if (null !== $this->logger) {
$this->logger->info('An exception was thrown while getting the uncalled listeners.', ['exception' => $e]);
}
$this->logger?->info('An exception was thrown while getting the uncalled listeners.', ['exception' => $e]);

// unable to retrieve the uncalled listeners
return [];
Expand Down Expand Up @@ -308,9 +306,7 @@ private function postProcess(string $eventName): void
}

if ($listener->wasCalled()) {
if (null !== $this->logger) {
$this->logger->debug('Notified event "{event}" to listener "{listener}".', $context);
}
$this->logger?->debug('Notified event "{event}" to listener "{listener}".', $context);
} else {
$this->callStack->detach($listener);
}
Expand All @@ -320,9 +316,7 @@ private function postProcess(string $eventName): void
}

if ($listener->stoppedPropagation()) {
if (null !== $this->logger) {
$this->logger->debug('Listener "{listener}" stopped propagation of the event "{event}".', $context);
}
$this->logger?->debug('Listener "{listener}" stopped propagation of the event "{event}".', $context);

$skipped = true;
}
Expand Down
Expand Up @@ -93,7 +93,7 @@ public function getInfo(string $eventName): array

return [
'event' => $eventName,
'priority' => null !== $this->priority ? $this->priority : (null !== $this->dispatcher ? $this->dispatcher->getListenerPriority($eventName, $this->listener) : null),
'priority' => $this->priority ?? $this->dispatcher?->getListenerPriority($eventName, $this->listener),
'pretty' => $this->pretty,
'stub' => $this->stub,
];
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/Form/FormFactory.php
Expand Up @@ -91,8 +91,8 @@ public function createBuilderForProperty(string $class, string $property, mixed

$type = $typeGuess ? $typeGuess->getType() : TextType::class;

$maxLength = $maxLengthGuess ? $maxLengthGuess->getValue() : null;
$pattern = $patternGuess ? $patternGuess->getValue() : null;
$maxLength = $maxLengthGuess?->getValue();
$pattern = $patternGuess?->getValue();

if (null !== $pattern) {
$options = array_replace_recursive(['attr' => ['pattern' => $pattern]], $options);
Expand Down
12 changes: 3 additions & 9 deletions src/Symfony/Component/Form/ResolvedFormType.php
Expand Up @@ -115,9 +115,7 @@ public function createView(FormInterface $form, FormView $parent = null): FormVi
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
if (null !== $this->parent) {
$this->parent->buildForm($builder, $options);
}
$this->parent?->buildForm($builder, $options);

$this->innerType->buildForm($builder, $options);

Expand All @@ -131,9 +129,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
if (null !== $this->parent) {
$this->parent->buildView($view, $form, $options);
}
$this->parent?->buildView($view, $form, $options);

$this->innerType->buildView($view, $form, $options);

Expand All @@ -147,9 +143,7 @@ public function buildView(FormView $view, FormInterface $form, array $options)
*/
public function finishView(FormView $view, FormInterface $form, array $options)
{
if (null !== $this->parent) {
$this->parent->finishView($view, $form, $options);
}
$this->parent?->finishView($view, $form, $options);

$this->innerType->finishView($view, $form, $options);

Expand Down
4 changes: 1 addition & 3 deletions src/Symfony/Component/HttpClient/AmpHttpClient.php
Expand Up @@ -160,9 +160,7 @@ public function reset()
foreach ($pushedResponses as [$pushedUrl, $pushDeferred]) {
$pushDeferred->fail(new CancelledException());

if ($this->logger) {
$this->logger->debug(sprintf('Unused pushed response: "%s"', $pushedUrl));
}
$this->logger?->debug(sprintf('Unused pushed response: "%s"', $pushedUrl));
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/Symfony/Component/HttpClient/CurlHttpClient.php
Expand Up @@ -268,21 +268,21 @@ public function request(string $method, string $url, array $options = []): Respo
unset($this->multi->pushedResponses[$url]);

if (self::acceptPushForRequest($method, $options, $pushedResponse)) {
$this->logger && $this->logger->debug(sprintf('Accepting pushed response: "%s %s"', $method, $url));
$this->logger?->debug(sprintf('Accepting pushed response: "%s %s"', $method, $url));

// Reinitialize the pushed response with request's options
$ch = $pushedResponse->handle;
$pushedResponse = $pushedResponse->response;
$pushedResponse->__construct($this->multi, $url, $options, $this->logger);
} else {
$this->logger && $this->logger->debug(sprintf('Rejecting pushed response: "%s"', $url));
$this->logger?->debug(sprintf('Rejecting pushed response: "%s"', $url));
$pushedResponse = null;
}
}

if (!$pushedResponse) {
$ch = curl_init();
$this->logger && $this->logger->info(sprintf('Request: "%s %s"', $method, $url));
$this->logger?->info(sprintf('Request: "%s %s"', $method, $url));
}

foreach ($curlopts as $opt => $value) {
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/HttpClient/Internal/AmpClientState.php
Expand Up @@ -200,11 +200,11 @@ private function handlePush(Request $request, Promise $response, array $options)
if ($this->maxPendingPushes <= \count($this->pushedResponses[$authority] ?? [])) {
$fifoUrl = key($this->pushedResponses[$authority]);
unset($this->pushedResponses[$authority][$fifoUrl]);
$this->logger && $this->logger->debug(sprintf('Evicting oldest pushed response: "%s"', $fifoUrl));
$this->logger?->debug(sprintf('Evicting oldest pushed response: "%s"', $fifoUrl));
}

$url = (string) $request->getUri();
$this->logger && $this->logger->debug(sprintf('Queueing pushed response: "%s"', $url));
$this->logger?->debug(sprintf('Queueing pushed response: "%s"', $url));
$this->pushedResponses[$authority][] = [$url, $deferred, $request, $response, [
'proxy' => $options['proxy'],
'bindto' => $options['bindto'],
Expand Down
8 changes: 4 additions & 4 deletions src/Symfony/Component/HttpClient/Internal/CurlClientState.php
Expand Up @@ -115,7 +115,7 @@ private function handlePush($parent, $pushed, array $requestHeaders, int $maxPen
}

if (!isset($headers[':method']) || !isset($headers[':scheme']) || !isset($headers[':authority']) || !isset($headers[':path'])) {
$this->logger && $this->logger->debug(sprintf('Rejecting pushed response from "%s": pushed headers are invalid', $origin));
$this->logger?->debug(sprintf('Rejecting pushed response from "%s": pushed headers are invalid', $origin));

return \CURL_PUSH_DENY;
}
Expand All @@ -126,19 +126,19 @@ private function handlePush($parent, $pushed, array $requestHeaders, int $maxPen
// but this is a MUST in the HTTP/2 RFC; let's restrict pushes to the original host,
// ignoring domains mentioned as alt-name in the certificate for now (same as curl).
if (!str_starts_with($origin, $url.'/')) {
$this->logger && $this->logger->debug(sprintf('Rejecting pushed response from "%s": server is not authoritative for "%s"', $origin, $url));
$this->logger?->debug(sprintf('Rejecting pushed response from "%s": server is not authoritative for "%s"', $origin, $url));

return \CURL_PUSH_DENY;
}

if ($maxPendingPushes <= \count($this->pushedResponses)) {
$fifoUrl = key($this->pushedResponses);
unset($this->pushedResponses[$fifoUrl]);
$this->logger && $this->logger->debug(sprintf('Evicting oldest pushed response: "%s"', $fifoUrl));
$this->logger?->debug(sprintf('Evicting oldest pushed response: "%s"', $fifoUrl));
}

$url .= $headers[':path'][0];
$this->logger && $this->logger->debug(sprintf('Queueing pushed response: "%s"', $url));
$this->logger?->debug(sprintf('Queueing pushed response: "%s"', $url));

$this->pushedResponses[$url] = new PushedResponse(new CurlResponse($this, $pushed), $headers, $this->openHandles[(int) $parent][1] ?? [], $pushed);

Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/HttpClient/NativeHttpClient.php
Expand Up @@ -176,7 +176,7 @@ public function request(string $method, string $url, array $options = []): Respo
$this->multi->dnsCache = $options['resolve'] + $this->multi->dnsCache;
}

$this->logger && $this->logger->info(sprintf('Request: "%s %s"', $method, implode('', $url)));
$this->logger?->info(sprintf('Request: "%s %s"', $method, implode('', $url)));

if (!isset($options['normalized_headers']['user-agent'])) {
$options['headers'][] = 'User-Agent: Symfony HttpClient/Native';
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/HttpClient/Response/NativeResponse.php
Expand Up @@ -126,7 +126,7 @@ private function open(): void
throw new TransportException($msg);
}

$this->logger && $this->logger->info(sprintf('%s for "%s".', $msg, $url ?? $this->url));
$this->logger?->info(sprintf('%s for "%s".', $msg, $url ?? $this->url));
});

try {
Expand Down Expand Up @@ -162,7 +162,7 @@ private function open(): void
break;
}

$this->logger && $this->logger->info(sprintf('Redirecting: "%s %s"', $this->info['http_code'], $url ?? $this->url));
$this->logger?->info(sprintf('Redirecting: "%s %s"', $this->info['http_code'], $url ?? $this->url));
}
} catch (\Throwable $e) {
$this->close();
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/HttpClient/TraceableHttpClient.php
Expand Up @@ -65,7 +65,7 @@ public function request(string $method, string $url, array $options = []): Respo
}
};

return new TraceableResponse($this->client, $this->client->request($method, $url, $options), $content, null === $this->stopwatch ? null : $this->stopwatch->start("$method $url", 'http_client'));
return new TraceableResponse($this->client, $this->client->request($method, $url, $options), $content, $this->stopwatch?->start("$method $url", 'http_client'));
}

/**
Expand Down
Expand Up @@ -36,9 +36,7 @@ public function __construct(LoggerInterface $logger = null)
public function getController(Request $request): callable|false
{
if (!$controller = $request->attributes->get('_controller')) {
if (null !== $this->logger) {
$this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing.');
}
$this->logger?->warning('Unable to look for the controller as the "_controller" parameter is missing.');

return false;
}
Expand Down

0 comments on commit ff4af00

Please sign in to comment.