phpstan-drupal
phpstan-drupal copied to clipboard
Determine return value from `\Drupal\Core\Config\Config::get`
Feature request
\Drupal\Core\Config\Config::get returns mixed.
Given the following code in a functional test:
$theme = $this->config('system.theme')->get('default');
$this->assertStringContainsString('foo', $theme);
When I analyze it with phpstan level 9 I get:
Parameter #2 $haystack of method PHPUnit\Framework\Assert::assertStringContainsString() expects string, mixed given.
However we have config schema for system.theme that says that default is a string. Perhaps we can figure this out in phpstan-drupal so we don't need to make assertions about the data. However it might not be wise to do this. If we put the same code in to a kernel test then $theme is in fact null, so phpstan is right to complain about it.
The one hard part I foresee: I'm pretty sure the typed config manager is stateful. If it doesn't rely on the database at all and only plugin discovery maybe we can make this work
Why not contribute a method(s) to the class in Drupal that returns explicit types, and even throws an exception if the type is not a match? It seems like methods for scalar types like Config::getString() should be feasible? The caller is responsible for knowing what type to expect.
@simesy interesting idea, I just came across this in Symfony's ParameterBag class.
https://github.com/symfony/http-foundation/blob/7.1/ParameterBag.php#L125-L152
Just a side note, now that constraints are also applicable to config entities, we can go even crazier stuff and parse those as well and tell PHPStan that something is not string, but an enum or such.