phpstan-drupal icon indicating copy to clipboard operation
phpstan-drupal copied to clipboard

Determine return value from `\Drupal\Core\Config\Config::get`

Open mstrelan opened this issue 1 year ago • 4 comments

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.

mstrelan avatar May 02 '24 01:05 mstrelan

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

mglaman avatar May 04 '24 19:05 mglaman

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 avatar Jun 11 '24 05:06 simesy

@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

mstrelan avatar Jul 08 '24 00:07 mstrelan

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.

mxr576 avatar Sep 11 '24 09:09 mxr576