Skip to content
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

Add assert type #37

Merged
merged 21 commits into from
Jun 21, 2024
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ jobs:
run: composer update --prefer-dist --no-progress --no-suggest --prefer-stable

- name: Run test suite
run: php -dpcov.enabled=1 -dpcov.exclude="~vendor~" vendor/bin/phpunit --testsuite unit,integration --coverage-clover ./.coverage/coverage.xml
run: php -dpcov.enabled=1 -dpcov.exclude="~vendor~" vendor/bin/phpunit --coverage-clover ./.coverage/coverage.xml

- name: Check coverage
run: test ! -f ./.coverage/coverage.xml || php vendor/bin/phpfci inspect ./.coverage/coverage.xml --exit-code-on-failure --reportText
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ Fluent assertion methods, inspired by `webmozart/assert`:
- `nonEmptyArray`
- `nonEmptyString`
- `isInstanceOf`
- `type`
- `fileExists`
- `file`
- `directory`
Expand Down
18 changes: 14 additions & 4 deletions extension.neon
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
services:
-
class: DR\Utils\PHPStan\ArraysReturnExtension
tags:
- phpstan.broker.dynamicStaticMethodReturnTypeExtension
-
class: DR\Utils\PHPStan\Extension\ArraysRemoveTypesReturnExtension
tags:
- phpstan.broker.dynamicStaticMethodReturnTypeExtension
-
class: DR\Utils\PHPStan\Extension\AssertTypeReturnExtension
tags:
- phpstan.broker.dynamicStaticMethodReturnTypeExtension
-
class: DR\Utils\PHPStan\Extension\AssertTypeTypeSpecifyingExtension
tags:
- phpstan.typeSpecifier.staticMethodTypeSpecifyingExtension
-
class: DR\Utils\PHPStan\Lib\TypeNarrower
9 changes: 4 additions & 5 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
services:
-
class: DR\Utils\PHPStan\ArraysReturnExtension
tags:
- phpstan.broker.dynamicStaticMethodReturnTypeExtension
includes:
- extension.neon

parameters:
level: max
treatPhpDocTypesAsCertain: false
paths:
- src
- tests
excludePaths:
- tests/Integration/PHPStan/data
21 changes: 20 additions & 1 deletion src/Assert.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
use Stringable;

use function file_exists;
use function get_debug_type;
use function implode;
use function in_array;
use function is_bool;
use function is_callable;
use function is_dir;
Expand Down Expand Up @@ -169,7 +172,6 @@ public static function integer(mixed $value, ?string $message = null): int

/**
* Assert the value is a numeric value. See is_numeric
*
* @template T
* @phpstan-assert numeric-string $value
*
Expand Down Expand Up @@ -241,6 +243,23 @@ public static function stringable(mixed $value, ?string $message = null): string
return $value;
}

/**
* Assert value is at least one of the given types
* @template T
* @param T $value
* @param string[] $types
*
* @return T;
*/
public static function type(mixed $value, array $types, ?string $message = null): mixed
{
if (in_array(get_debug_type($value), $types, true) === false) {
throw ExceptionFactory::createException('in type (' . implode(',', $types) . ')', $value, $message);
}

return $value;
}

/**
* Assert value is a class-string
* @template T
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
<?php
declare(strict_types=1);

namespace DR\Utils\PHPStan;
namespace DR\Utils\PHPStan\Extension;

use DR\Utils\Arrays;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\ClassConstFetch;
use DR\Utils\PHPStan\Lib\TypeNarrower;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\String_;
use PHPStan\Analyser\Scope;
use PHPStan\PhpDoc\TypeStringResolver;
use PHPStan\Reflection\MethodReflection;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\ArrayType;
Expand All @@ -20,9 +15,9 @@
use PHPStan\Type\Type;
use PHPStan\Type\UnionType;

class ArraysReturnExtension implements DynamicStaticMethodReturnTypeExtension
class ArraysRemoveTypesReturnExtension implements DynamicStaticMethodReturnTypeExtension
{
public function __construct(private readonly TypeStringResolver $typeStringResolver)
public function __construct(private readonly TypeNarrower $typeNarrower)
{
}

Expand Down Expand Up @@ -50,7 +45,7 @@ public function getTypeFromStaticMethodCall(MethodReflection $methodReflection,
$types = $this->getItemTypes($arrayType);

// convert the disallowed types as string to phpstan types
$disallowedStanTypes = $this->getDisallowedTypes($disallowedTypes);
$disallowedStanTypes = $this->typeNarrower->getTypesFromStringArray($disallowedTypes);

$allowedStanTypes = [];
foreach ($types as $index => $type) {
Expand Down Expand Up @@ -78,27 +73,6 @@ public function getTypeFromStaticMethodCall(MethodReflection $methodReflection,
);
}

/**
* @return Type[]
*/
private function getDisallowedTypes(Arg $arrayArgument): array
{
/** @var Array_ $disallowedTypesValue */
$disallowedTypesValue = $arrayArgument->value;
$disallowedStanTypes = [];
foreach ($disallowedTypesValue->items as $item) {
if ($item?->value instanceof String_) {
// type definition is string, convert to type object
$disallowedStanTypes[] = $this->typeStringResolver->resolve($item->value->value);
} elseif ($item?->value instanceof ClassConstFetch && $item->value->class instanceof Name) {
// type definition is class-string, convert to type object
$disallowedStanTypes[] = $this->typeStringResolver->resolve($item->value->class->toString());
}
}

return $disallowedStanTypes;
}

/**
* @return Type[]
*/
Expand Down
39 changes: 39 additions & 0 deletions src/PHPStan/Extension/AssertTypeReturnExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);

namespace DR\Utils\PHPStan\Extension;

use DR\Utils\Assert;
use DR\Utils\PHPStan\Lib\TypeNarrower;
use PhpParser\Node\Expr\StaticCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\DynamicStaticMethodReturnTypeExtension;
use PHPStan\Type\Type;

class AssertTypeReturnExtension implements DynamicStaticMethodReturnTypeExtension
{
public function __construct(private readonly TypeNarrower $typeNarrower)
{
}

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

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

/**
* @inheritDoc
*/
public function getTypeFromStaticMethodCall(MethodReflection $methodReflection, StaticCall $methodCall, Scope $scope): Type
{
[$item, $allowedTypes] = $methodCall->getArgs();

return $this->typeNarrower->narrow($item, $allowedTypes, $scope);
}
}
71 changes: 71 additions & 0 deletions src/PHPStan/Extension/AssertTypeTypeSpecifyingExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

declare(strict_types=1);

namespace DR\Utils\PHPStan\Extension;

use DR\Utils\Assert;
use DR\Utils\PHPStan\Lib\TypeNarrower;
use PhpParser\Node\Expr\StaticCall;
use PHPStan\Analyser\Scope;
use PHPStan\Analyser\SpecifiedTypes;
use PHPStan\Analyser\TypeSpecifier;
use PHPStan\Analyser\TypeSpecifierAwareExtension;
use PHPStan\Analyser\TypeSpecifierContext;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\StaticMethodTypeSpecifyingExtension;

/**
* Extension to ensure the types are narrowed to int|null for example:
* <code>
* Assert::type($value, ['int', 'null']);
* </code>
* @see \PHPStan\Type\PHPUnit\Assert\AssertStaticMethodTypeSpecifyingExtension as an example
*/
class AssertTypeTypeSpecifyingExtension implements StaticMethodTypeSpecifyingExtension, TypeSpecifierAwareExtension
{
private TypeSpecifier $typeSpecifier;

/**
* @codeCoverageIgnore Will only be hit during initialisation
*/
public function __construct(private readonly TypeNarrower $typeNarrower)
{
}

/**
* @codeCoverageIgnore Will only be hit during initialisation
*/
public function setTypeSpecifier(TypeSpecifier $typeSpecifier): void
{
$this->typeSpecifier = $typeSpecifier;
}

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

/**
* @inheritDoc
*/
public function isStaticMethodSupported(MethodReflection $staticMethodReflection, StaticCall $node, TypeSpecifierContext $context): bool
{
return $staticMethodReflection->getName() === 'type';
}

/**
* @inheritDoc
*/
public function specifyTypes(
MethodReflection $staticMethodReflection,
StaticCall $node,
Scope $scope,
TypeSpecifierContext $context
): SpecifiedTypes {
[$item, $allowedTypes] = $node->getArgs();
$type = $this->typeNarrower->narrow($item, $allowedTypes, $scope);

return $this->typeSpecifier->create($item->value, $type, TypeSpecifierContext::createTruthy());
}
}
63 changes: 63 additions & 0 deletions src/PHPStan/Lib/TypeNarrower.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

declare(strict_types=1);

namespace DR\Utils\PHPStan\Lib;

use PhpParser\Node\Arg;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\String_;
use PHPStan\Analyser\Scope;
use PHPStan\PhpDoc\TypeStringResolver;
use PHPStan\Type\NeverType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;

class TypeNarrower
{
public function __construct(private readonly TypeStringResolver $typeStringResolver)
{
}

public function narrow(Arg $item, Arg $allowedTypes, Scope $scope): Type
{
// convert the disallowed types as string to phpstan types
$allowedStanTypes = $this->getTypesFromStringArray($allowedTypes);
$type = match (true) {
count($allowedStanTypes) === 0 => new NeverType(),
count($allowedStanTypes) === 1 => reset($allowedStanTypes),
default => new UnionType($allowedStanTypes),
};

return TypeCombinator::intersect($scope->getType($item->value), $type);
}

/**
* @param Arg $arg arg of type Array
*
* @return Type[]
*/
public function getTypesFromStringArray(Arg $arg): array
{
$argValue = $arg->value;
if ($argValue instanceof Array_ === false) {
return [];
}

$types = [];
foreach ($argValue->items as $item) {
if ($item?->value instanceof String_) {
// type definition is string, convert to type object
$types[] = $this->typeStringResolver->resolve($item->value->value);
} elseif ($item?->value instanceof ClassConstFetch && $item->value->class instanceof Name) {
// type definition is class-string, convert to type object
$types[] = $this->typeStringResolver->resolve($item->value->class->toString());
}
}

return $types;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
namespace DR\Utils\Tests\Integration\PHPStan;

use DR\Utils\Assert;
use DR\Utils\PHPStan\ArraysReturnExtension;
use DR\Utils\PHPStan\Extension\ArraysRemoveTypesReturnExtension;
use DR\Utils\PHPStan\Lib\TypeNarrower;
use PHPStan\Testing\TypeInferenceTestCase;
use PHPUnit\Framework\Attributes\CoversClass;

#[CoversClass(ArraysReturnExtension::class)]
class ArraysReturnExtensionTest extends TypeInferenceTestCase
#[CoversClass(ArraysRemoveTypesReturnExtension::class)]
#[CoversClass(TypeNarrower::class)]
class ArraysRemoveTypeReturnExtensionTest extends TypeInferenceTestCase
{
public function testFileAsserts(): void
{
Expand Down
35 changes: 35 additions & 0 deletions tests/Integration/PHPStan/AssertTypeExtensionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);

namespace DR\Utils\Tests\Integration\PHPStan;

use DR\Utils\Assert;
use DR\Utils\PHPStan\Extension\AssertTypeReturnExtension;
use DR\Utils\PHPStan\Extension\AssertTypeTypeSpecifyingExtension;
use DR\Utils\PHPStan\Lib\TypeNarrower;
use PHPStan\Testing\TypeInferenceTestCase;
use PHPUnit\Framework\Attributes\CoversClass;

#[CoversClass(AssertTypeReturnExtension::class)]
#[CoversClass(AssertTypeTypeSpecifyingExtension::class)]
#[CoversClass(TypeNarrower::class)]
class AssertTypeExtensionTest extends TypeInferenceTestCase
{
public function testFileAsserts(): void
{
$results = self::gatherAssertTypes(__DIR__ . '/data/AssertTypeAssertions.php');
foreach ($results as $result) {
$assertType = Assert::string(array_shift($result));
$file = Assert::string(array_shift($result));
$this->assertFileAsserts($assertType, $file, ...$result);
}
}

/**
* @return string[]
*/
public static function getAdditionalConfigFiles(): array
{
return [dirname(__DIR__, 3) . '/extension.neon'];
}
}
Loading