Skip to content
Open
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
13 changes: 13 additions & 0 deletions extension.neon
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,19 @@ services:
factory: PHPStan\Type\Symfony\Form\FormInterfaceDynamicReturnTypeExtension
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]

# #[AsFormType] classes as form types
-
class: PHPStan\Type\Symfony\Form\AsFormTypeHelper
-
factory: PHPStan\Type\Symfony\Form\AsFormTypeDynamicReturnTypeExtension(Symfony\Component\Form\FormFactoryInterface)
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]
-
factory: PHPStan\Type\Symfony\Form\AsFormTypeDynamicReturnTypeExtension(Symfony\Bundle\FrameworkBundle\Controller\AbstractController)
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]
-
class: PHPStan\Type\Symfony\Form\AsFormTypeIgnoreErrorExtension
tags: [phpstan.ignoreErrorExtension]

# Command::getHelper() return type
-
factory: PHPStan\Type\Symfony\CommandGetHelperDynamicReturnTypeExtension
Expand Down
6 changes: 6 additions & 0 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ parameters:
count: 1
path: tests/Symfony/RequiredAutowiringExtensionTest.php

-
message: '#^Accessing PHPStan\\Rules\\Methods\\CallMethodsRule\:\:class is not covered by backward compatibility promise\. The class might change in a minor PHPStan version\.$#'
identifier: phpstanApi.classConstant
count: 1
path: tests/Type/Symfony/AsFormTypeIgnoreErrorExtensionTest.php

-
message: '#^Accessing PHPStan\\Rules\\Comparison\\ImpossibleCheckTypeMethodCallRule\:\:class is not covered by backward compatibility promise\. The class might change in a minor PHPStan version\.$#'
identifier: phpstanApi.classConstant
Expand Down
59 changes: 59 additions & 0 deletions src/Type/Symfony/Form/AsFormTypeDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Symfony\Form;

use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\Generic\GenericObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function strpos;

final class AsFormTypeDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension
{

/** @var class-string */
private string $className;

private AsFormTypeHelper $helper;

/**
* @param class-string $className
*/
public function __construct(string $className, AsFormTypeHelper $helper)
{
$this->className = $className;
$this->helper = $helper;
}

public function getClass(): string
{
return $this->className;
}

public function isMethodSupported(MethodReflection $methodReflection): bool
{
return isset(AsFormTypeHelper::TYPE_ARGUMENT_POSITIONS[$methodReflection->getName()]);
}

public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type
{
$dataClassType = $this->helper->findDataClassType($methodCall, $scope);
if ($dataClassType === null) {
return null;
}

$returnClass = strpos($methodReflection->getName(), 'Builder') !== false
? 'Symfony\Component\Form\FormBuilderInterface'
: 'Symfony\Component\Form\FormInterface';

if (!$this->helper->getDataType($methodCall, $scope)->isNull()->no()) {
$dataClassType = TypeCombinator::addNull($dataClassType);
}

return new GenericObjectType($returnClass, [$dataClassType]);
}

}
101 changes: 101 additions & 0 deletions src/Type/Symfony/Form/AsFormTypeHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Symfony\Form;

use PhpParser\Node\Arg;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Identifier;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\NullType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;

final class AsFormTypeHelper
{

public const TYPE_ARGUMENT_POSITIONS = [
'create' => 0,
'createNamed' => 1,
'createBuilder' => 0,
'createNamedBuilder' => 1,
'createForm' => 0,
];

private ReflectionProvider $reflectionProvider;

public function __construct(ReflectionProvider $reflectionProvider)
{
$this->reflectionProvider = $reflectionProvider;
}

public function findDataClassType(MethodCall $methodCall, Scope $scope): ?Type
{
$typeArg = $this->findArgument($methodCall, 'type', 0);
if ($typeArg === null) {
return null;
}

$calledOnType = $scope->getType($methodCall->var);
if (
!(new ObjectType('Symfony\Component\Form\FormFactoryInterface'))->isSuperTypeOf($calledOnType)->yes()
&& !(new ObjectType('Symfony\Bundle\FrameworkBundle\Controller\AbstractController'))->isSuperTypeOf($calledOnType)->yes()
) {
return null;
}

$dataClassType = $scope->getType($typeArg->value)->getClassStringObjectType();
$classReflections = $dataClassType->getObjectClassReflections();
if ($classReflections === []) {
return null;
}

foreach ($classReflections as $classReflection) {
if (!$this->hasAsFormTypeAttribute($classReflection)) {
return null;
}
}

return $dataClassType;
}

public function getDataType(MethodCall $methodCall, Scope $scope): Type
{
$dataArg = $this->findArgument($methodCall, 'data', 1);

return $dataArg !== null ? $scope->getType($dataArg->value) : new NullType();
}

private function findArgument(MethodCall $methodCall, string $name, int $offset): ?Arg
{
if (!$methodCall->name instanceof Identifier || !isset(self::TYPE_ARGUMENT_POSITIONS[$methodCall->name->name])) {
return null;
}

$position = self::TYPE_ARGUMENT_POSITIONS[$methodCall->name->name] + $offset;
foreach ($methodCall->getArgs() as $i => $arg) {
if ($arg->name !== null ? $arg->name->name === $name : $i === $position) {
return $arg;
}
}

return null;
}

private function hasAsFormTypeAttribute(ClassReflection $classReflection): bool
{
foreach ($classReflection->getAttributes() as $attribute) {
if (!$this->reflectionProvider->hasClass($attribute->getName())) {
continue;
}

if ($this->reflectionProvider->getClass($attribute->getName())->is('Symfony\Component\Form\Attribute\AsFormType')) {
return true;
}
}

return false;
}

}
41 changes: 41 additions & 0 deletions src/Type/Symfony/Form/AsFormTypeIgnoreErrorExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Symfony\Form;

use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Error;
use PHPStan\Analyser\IgnoreErrorExtension;
use PHPStan\Analyser\Scope;
use PHPStan\Type\TypeCombinator;
use function strpos;

final class AsFormTypeIgnoreErrorExtension implements IgnoreErrorExtension
{

private AsFormTypeHelper $helper;

public function __construct(AsFormTypeHelper $helper)
{
$this->helper = $helper;
}

public function shouldIgnore(Error $error, Node $node, Scope $scope): bool
{
if ($error->getIdentifier() !== 'argument.type' || !$node instanceof MethodCall) {
return false;
}

$dataClassType = $this->helper->findDataClassType($node, $scope);
if ($dataClassType === null) {
return false;
}

if (TypeCombinator::addNull($dataClassType)->accepts($this->helper->getDataType($node, $scope), true)->no()) {
return false;
}

return strpos($error->getMessage(), '$type of method') !== false;
}

}
82 changes: 82 additions & 0 deletions tests/Type/Symfony/AsFormTypeIgnoreErrorExtensionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Symfony;

use PHPStan\Rules\Methods\CallMethodsRule;
use PHPStan\Rules\Rule;
use PHPStan\Testing\RuleTestCase;
use const PHP_VERSION_ID;

/**
* @extends RuleTestCase<CallMethodsRule>
*/
class AsFormTypeIgnoreErrorExtensionTest extends RuleTestCase
{

protected function getRule(): Rule
{
return self::getContainer()->getByType(CallMethodsRule::class);
}

public function testRule(): void
{
if (PHP_VERSION_ID < 80000) {
self::markTestSkipped('Test requires PHP 8.0.');
}

$this->analyse([__DIR__ . '/data/form_as_form_type.php'], [
[
'Parameter #1 $type of method Symfony\Component\Form\FormFactoryInterface::create() expects class-string<Symfony\Component\Form\FormTypeInterface<FormAsFormType\Data>>, \'FormAsFormType\\\\ContactDto\' given.',
140,
],
[
'Parameter #3 $options of method Symfony\Component\Form\FormFactoryInterface::create() expects array<string, mixed>, string given.',
141,
],
[
'Parameter #1 $name of method Symfony\Component\Form\FormFactoryInterface::createNamed() expects string, array given.',
142,
],
[
'Parameter #1 $type of method Symfony\Component\Form\FormFactoryInterface::create() expects class-string<Symfony\Component\Form\FormTypeInterface<mixed>>, \'FormAsFormType\\\\ChildOfOpenDto\' given.',
143,
],
[
'Parameter #1 $type of method Symfony\Component\Form\FormFactoryInterface::create() expects class-string<Symfony\Component\Form\FormTypeInterface<mixed>>, \'FormAsFormType\\\\OtherAttributeDto\' given.',
144,
],
[
'Parameter #1 $type of method Symfony\Component\Form\FormFactoryInterface::create() expects class-string<Symfony\Component\Form\FormTypeInterface<mixed>>, \'FormAsFormType\\\\UnknownAttributeDto\' given.',
145,
],
[
'Parameter #1 $type of method Symfony\Component\Form\FormFactoryInterface::create() expects class-string<Symfony\Component\Form\FormTypeInterface<mixed>>, \'FormAsFormType\\\\NotAFormType\' given.',
146,
],
[
'Parameter #1 $type of method Symfony\Component\Form\FormFactoryInterface::create() expects class-string<Symfony\Component\Form\FormTypeInterface<mixed>>, \'FormAsFormType\\\\ContactDto\'|\'FormAsFormType\\\\NotAFormType\' given.',
147,
],
[
'Parameter #1 $type of method FormAsFormType\OtherFactory::create() expects class-string<Symfony\Component\Form\FormTypeInterface<mixed>>, \'FormAsFormType\\\\ContactDto\' given.',
148,
],
[
'Parameter #1 $type of method Symfony\Bundle\FrameworkBundle\Controller\AbstractController::createForm() expects class-string<Symfony\Component\Form\FormTypeInterface<mixed>>, \'FormAsFormType\\\\NotAFormType\' given.',
161,
],
[
'Cannot call method undefinedMethod() on FormAsFormType\ContactDto|null.',
166,
],
]);
}

public static function getAdditionalConfigFiles(): array
{
return [
__DIR__ . '/../../../extension.neon',
];
}

}
5 changes: 5 additions & 0 deletions tests/Type/Symfony/ExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use function class_exists;
use function interface_exists;
use function strpos;
use const PHP_VERSION_ID;

class ExtensionTest extends TypeInferenceTestCase
{
Expand Down Expand Up @@ -69,6 +70,10 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/data/cache.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/form_data_type.php');

if (PHP_VERSION_ID >= 80000) {
yield from $this->gatherAssertTypes(__DIR__ . '/data/form_as_form_type.php');
}

yield from $this->gatherAssertTypes(__DIR__ . '/data/extension/with-configuration/WithConfigurationExtension.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/extension/without-configuration/WithoutConfigurationExtension.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/extension/anonymous/AnonymousExtension.php');
Expand Down
Loading