Skip to content
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
6 changes: 6 additions & 0 deletions extension.neon
Original file line number Diff line number Diff line change
Expand Up @@ -305,3 +305,9 @@ services:
tags: [phpstan.doctrine.typeDescriptor]
arguments:
uuidTypeName: Ramsey\Uuid\Doctrine\UuidBinaryOrderedTimeType

# Doctrine Collection
-
class: PHPStan\Type\Doctrine\Collection\FirstTypeSpecifyingExtension
tags:
- phpstan.typeSpecifier.methodTypeSpecifyingExtension
75 changes: 75 additions & 0 deletions src/Type/Doctrine/Collection/FirstTypeSpecifyingExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Doctrine\Collection;

use PhpParser\Node\Expr\MethodCall;
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\Reflection\ParametersAcceptorSelector;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\MethodTypeSpecifyingExtension;
use PHPStan\Type\TypeCombinator;

final class FirstTypeSpecifyingExtension implements MethodTypeSpecifyingExtension, TypeSpecifierAwareExtension
{

private const COLLECTION_CLASS = 'Doctrine\Common\Collections\Collection';
private const IS_EMPTY_METHOD_NAME = 'isEmpty';
private const FIRST_METHOD_NAME = 'first';

/** @var TypeSpecifier */
private $typeSpecifier;

public function getClass(): string
{
return self::COLLECTION_CLASS;
}

public function isMethodSupported(
MethodReflection $methodReflection,
MethodCall $node,
TypeSpecifierContext $context
): bool
{
return (
$methodReflection->getDeclaringClass()->getName() === self::COLLECTION_CLASS
|| $methodReflection->getDeclaringClass()->isSubclassOf(self::COLLECTION_CLASS)
)
&& $methodReflection->getName() === self::IS_EMPTY_METHOD_NAME;
}

public function specifyTypes(
MethodReflection $methodReflection,
MethodCall $node,
Scope $scope,
TypeSpecifierContext $context
): SpecifiedTypes
{
$classReflection = $methodReflection->getDeclaringClass();
$methodVariants = $classReflection->getNativeMethod(self::FIRST_METHOD_NAME)->getVariants();

if ($context->truthy()) {
return $this->typeSpecifier->create(
new MethodCall($node->var, self::FIRST_METHOD_NAME),
new ConstantBooleanType(false),
$context
);
}

return $this->typeSpecifier->create(
new MethodCall($node->var, self::FIRST_METHOD_NAME),
TypeCombinator::remove(ParametersAcceptorSelector::selectSingle($methodVariants)->getReturnType(), new ConstantBooleanType(false)),
$context
);
}

public function setTypeSpecifier(TypeSpecifier $typeSpecifier): void
{
$this->typeSpecifier = $typeSpecifier;
}

}