function AutowireTest::testCoreControllerAutowiring

Same name in other branches
  1. 11.x core/tests/Drupal/KernelTests/Core/DependencyInjection/AutowireTest.php \Drupal\KernelTests\Core\DependencyInjection\AutowireTest::testCoreControllerAutowiring()

Tests that core controllers are autowired where possible.

File

core/tests/Drupal/KernelTests/Core/DependencyInjection/AutowireTest.php, line 131

Class

AutowireTest
Tests auto-wiring services.

Namespace

Drupal\KernelTests\Core\DependencyInjection

Code

public function testCoreControllerAutowiring() : void {
    $services = [];
    $aliases = [];
    $filenames = array_map(fn($module) => "core/modules/{$module[0]}/{$module[0]}.services.yml", $this->coreModuleListDataProvider());
    $filenames[] = 'core/core.services.yml';
    foreach (array_filter($filenames, 'file_exists') as $filename) {
        foreach (Yaml::decode(file_get_contents($filename))['services'] as $id => $service) {
            if (is_string($service)) {
                $aliases[$id] = substr($service, 1);
            }
        }
    }
    $controllers = [];
    $filenames = array_map(fn($module) => "core/modules/{$module[0]}/{$module[0]}.routing.yml", $this->coreModuleListDataProvider());
    foreach (array_filter($filenames, 'file_exists') as $filename) {
        foreach (Yaml::decode(file_get_contents($filename)) as $route) {
            if (isset($route['defaults']['_controller'])) {
                [
                    $class,
                ] = explode('::', $route['defaults']['_controller'], 2);
                $controllers[$class] = $class;
            }
        }
    }
    $autowire = [];
    foreach ($controllers as $controller) {
        if (!is_subclass_of($controller, ControllerBase::class)) {
            continue;
        }
        if (!method_exists($controller, '__construct') || !method_exists($controller, 'create')) {
            continue;
        }
        if ((new \ReflectionClass($controller))->getMethod('create')->class !== ltrim($controller, '\\')) {
            continue;
        }
        $constructor = new \ReflectionMethod($controller, '__construct');
        foreach ($constructor->getParameters() as $pos => $parameter) {
            $interface = (string) $parameter->getType();
            if (!isset($aliases[$interface])) {
                continue 2;
            }
        }
        $autowire[] = $controller;
    }
    $this->assertEmpty($autowire, 'The following core controllers can be autowired. Remove the create() method:' . PHP_EOL . implode(PHP_EOL, $autowire));
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.