Unverified Commit fc389ed0 authored by Alex Pott's avatar Alex Pott
Browse files

Issue #3464426 by dcam, kksandr, alexpott: AutowireTrait and autowire for...

Issue #3464426 by dcam, kksandr, alexpott: AutowireTrait and autowire for services behave differently for nullable types

(cherry picked from commit 8cd685b9)
parent 642eb99e
Loading
Loading
Loading
Loading
Loading
+4 −0
Original line number Diff line number Diff line
@@ -34,6 +34,10 @@ public static function create(ContainerInterface $container) {
        }

        if (!$container->has($service)) {
          if ($parameter->allowsNull()) {
            $args[] = NULL;
            continue;
          }
          throw new AutowiringFailedException($service, sprintf('Cannot autowire service "%s": argument "$%s" of method "%s::_construct()", you should configure its value explicitly.', $service, $parameter->getName(), static::class));
        }

+21 −0
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\system_test\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\dblog\Logger\DbLog;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

/**
 * A controller that specifies an optional dependency.
 */
class OptionalServiceSystemTestController extends ControllerBase {

  public function __construct(
    #[Autowire('logger.dblog')]
    public readonly ?DbLog $dbLog,
  ) {}

}
+15 −0
Original line number Diff line number Diff line
@@ -4,8 +4,10 @@

namespace Drupal\KernelTests\Core\Controller;

use Drupal\dblog\Logger\DbLog;
use Drupal\KernelTests\KernelTestBase;
use Drupal\system_test\Controller\BrokenSystemTestController;
use Drupal\system_test\Controller\OptionalServiceSystemTestController;
use Drupal\system_test\Controller\SystemTestController;
use Symfony\Component\DependencyInjection\Exception\AutowiringFailedException;

@@ -52,4 +54,17 @@ public function testCreateException(): void {
    $this->container->get('class_resolver')->getInstanceFromDefinition(BrokenSystemTestController::class);
  }

  /**
   * @covers ::create
   */
  public function testCreateOptional(): void {
    $service = $this->container->get('class_resolver')->getInstanceFromDefinition(OptionalServiceSystemTestController::class);
    $this->assertInstanceOf(OptionalServiceSystemTestController::class, $service);
    $this->assertNull($service->dbLog);
    $this->container->get('module_installer')->install(['dblog']);
    $service = $this->container->get('class_resolver')->getInstanceFromDefinition(OptionalServiceSystemTestController::class);
    $this->assertInstanceOf(OptionalServiceSystemTestController::class, $service);
    $this->assertInstanceOf(DbLog::class, $service->dbLog);
  }

}