Skip to content

Resolve config types #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions extension.neon
Original file line number Diff line number Diff line change
@@ -1,23 +1,31 @@
parameters:
laravel:
configPaths: []
customBindings: []
morphMap: []

parametersSchema:
laravel: structure([
configPaths: listOf(string())
customBindings: arrayOf(string())
morphMap: arrayOf(string())
])

services:
- class: Recoded\PHPStanLaravel\Extensions\Container\AppResolveFunctionDynamicReturnType
tags: [phpstan.broker.dynamicFunctionReturnTypeExtension]
- class: Recoded\PHPStanLaravel\Extensions\Contracts\Config\RepositoryGetDynamicReturnType
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]
- class: Recoded\PHPStanLaravel\Extensions\Contracts\Container\ContainerDynamicReturnType
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]
- class: Recoded\PHPStanLaravel\Extensions\Eloquent\BuilderCollectionDynamicReturnType
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]
- class: Recoded\PHPStanLaravel\Extensions\StubExtension
tags: [phpstan.stubFilesExtension]
- class: Recoded\PHPStanLaravel\ConfigHelper
arguments:
configPaths: %laravel.configPaths%
parser: @currentPhpVersionSimpleDirectParser
- class: Recoded\PHPStanLaravel\DependencyRegistry
arguments:
customBindings: %laravel.customBindings%
Expand Down
146 changes: 146 additions & 0 deletions src/ConfigHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
<?php

declare(strict_types=1);

namespace Recoded\PHPStanLaravel;

use PhpParser\Node\Stmt\Return_;
use PHPStan\Analyser\ScopeContext;
use PHPStan\Analyser\ScopeFactory;
use PHPStan\File\FileHelper;
use PHPStan\Parser\Parser;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\MixedType;
use PHPStan\Type\NullType;
use PHPStan\Type\Type;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RegexIterator;

final class ConfigHelper
{
/**
* @var array<string, array<array-key, mixed>>
*/
private array $structure;

/**
* Create a new ConfigHelper instance.
*
* @param list<string> $configPaths
* @param \PHPStan\Parser\Parser $parser
* @param \PHPStan\Analyser\ScopeFactory $scopeFactory
* @param \PHPStan\File\FileHelper $fileHelper
* @return void
*/
public function __construct(
private array $configPaths,
private Parser $parser,
private ScopeFactory $scopeFactory,
private FileHelper $fileHelper,
) {
//
}

private function load(): void
{
$paths = array_map($this->fileHelper->absolutizePath(...), $this->configPaths);

foreach ($paths as $path) {
/** @var iterable<int, \SplFileInfo> $files */
$files = new RegexIterator(
new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)),
'/\.php$/i',
);

foreach ($files as $file) {
$statements = $this->parser->parseFile($file->getPathname());

if (count($statements) !== 1 || !array_values($statements)[0] instanceof Return_) {
continue;
}

if (array_values($statements)[0]->expr === null) {
continue;
}

$configScope = $this->scopeFactory->create(ScopeContext::create($file->getPathname()));

$type = $configScope->getType(array_values($statements)[0]->expr);

if (!$type->isConstantArray()->yes()) {
continue;
}

/** @var \PHPStan\Type\Constant\ConstantArrayType $type */

$configName = $file->getBasename('.php');

$this->structure[$configName] = array_merge_recursive(
$this->structure[$configName] ?? [],
$this->parseArray($type),
);
}
}
}

/**
* @param \PHPStan\Type\Constant\ConstantArrayType $array
* @return array<string, mixed>
*/
private function parseArray(ConstantArrayType $array): array
{
$keys = $array->getKeyTypes();
$values = $array->getValueTypes();

$parsed = [];

foreach ($keys as $index => $keyType) {
$valueType = $values[$index];

if ($valueType->isConstantArray()->yes()) {
/** @var \PHPStan\Type\Constant\ConstantArrayType $valueType */

if (!(new IntegerType())->isSuperTypeOf($valueType->getKeyType())->yes()) {
$valueType = $this->parseArray($valueType);
}
}

foreach ($keyType->getConstantStrings() as $keyString) {
$parsed[$keyString->getValue()] = $valueType;
}
}

return $parsed;
}

public function get(string $path, Type $default = new NullType()): Type
{
if (!isset($this->structure)) {
$this->load();
}

$parts = explode('.', $path);

$value = $this->structure;

foreach ($parts as $part) {
if (!array_key_exists($part, $value)) {
return $default;
}

$value = $value[$part];

if (is_array($value)) {
// TODO support returning entire config
}

if ($value instanceof Type) {
return $value;
}
}

return new MixedType();
}
}
60 changes: 60 additions & 0 deletions src/Extensions/Contracts/Config/RepositoryGetDynamicReturnType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

declare(strict_types=1);

namespace Recoded\PHPStanLaravel\Extensions\Contracts\Config;

use Illuminate\Contracts\Config\Repository;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use Recoded\PHPStanLaravel\ConfigHelper;

final class RepositoryGetDynamicReturnType implements DynamicMethodReturnTypeExtension
{
/**
* Create a new extension instance.
*
* @param \Recoded\PHPStanLaravel\ConfigHelper $configHelper
* @return void
*/
public function __construct(
private ConfigHelper $configHelper,
) {
//
}

public function getClass(): string
{
return Repository::class;
}

public function isMethodSupported(MethodReflection $methodReflection): bool
{
return $methodReflection->getName() === 'get';
}

public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type
{
if ($methodCall->getArgs() === []) {
return null;
}

$firstArg = array_values($methodCall->getArgs())[0];
$firstArgType = $scope->getType($firstArg->value);

if ($firstArgType->getConstantStrings() === []) {
return null;
}

$types = array_map(function (ConstantStringType $string) {
return $this->configHelper->get($string->getValue());
}, $firstArgType->getConstantStrings());

return TypeCombinator::union(...$types);
}
}
34 changes: 34 additions & 0 deletions tests/Types/Contracts/Config/RepositoryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php declare(strict_types = 1);

namespace Tests\Types\Contracts\Config;

use PHPStan\Testing\TypeInferenceTestCase;
use PHPUnit\Framework\Attributes\DataProvider;

final class RepositoryTest extends TypeInferenceTestCase
{
/**
* @return iterable<string, mixed[]>
*/
public static function fileAsserts(): iterable
{
yield from self::gatherAssertTypes(__DIR__ . '/../../data/contracts/config/repository.php');
}

#[DataProvider('fileAsserts')]
public function testFileAsserts(
string $assertType,
string $file,
mixed ...$args,
): void {
$this->assertFileAsserts($assertType, $file, ...$args);
}

public static function getAdditionalConfigFiles(): array
{
return [
__DIR__ . '/../../../../extension.neon',
__DIR__ . '/config.neon',
];
}
}
4 changes: 4 additions & 0 deletions tests/Types/Contracts/Config/config.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
parameters:
laravel:
configPaths:
- %rootDir%/../../../tests/Types/Contracts/Config/config
9 changes: 9 additions & 0 deletions tests/Types/Contracts/Config/config/app.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

return [
'name' => 'test',
'iteration' => 15,
'nested' => [
'other' => 'settings',
],
];
13 changes: 13 additions & 0 deletions tests/Types/data/contracts/config/repository.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

use function PHPStan\Testing\assertType;

/** @var \Illuminate\Contracts\Config\Repository $repository */
/** @var string $dynamicPath */
/** @var string|'test' $partiallyDynamicPath */

assertType('\'test\'', $repository->get('app.name'));
assertType('15', $repository->get('app.iteration'));
assertType('\'settings\'', $repository->get('app.nested.other'));
assertType('mixed', $repository->get($dynamicPath));
assertType('mixed', $repository->get($partiallyDynamicPath));