phpstan / phpstan-symfony

Symfony extension for PHPStan
MIT License
698 stars 89 forks source link

Narrow type for Extension::getConfiguration if class exists #384

Closed RobertMe closed 6 months ago

RobertMe commented 6 months ago

The base extension class automatically creates a Configuration instance when a Configuration class exists in the namespace of the extension. But PHPStan obviously doesn't understand this behaviour and always assumes that getConfiguration() returns ConfigurationInterface|null meaning that the default pattern to get and parse the configuration reports an error.

I.e.:

namespace Foo;

class SomeExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container): void
    {
        $configuration = $this->getConfiguration($configs, $container);
        $config = $this->processConfiguration($configuration, $configs);
    }
}

results in an error because processConfiguration() doesn't accept ConfigurationInterface|null. But when a Configuration class exists in the same namespace as the Extension class (so Foo\Extension) an instance of it is returned.

This DynamicReturnTypeExtension overrides the return type of Extension::getConfiguration() so it automatically narrows the return type in case getConfiguration() is not overriden and a Configuration class exists. So that in the given example getConfiguration() doesn't return ConfigurationInterface|null anymore but Foo\Configuration and there is no error on calling processConfiguration().

ondrejmirtes commented 6 months ago

Thank you!