Skip to content

chore: disable treat phpdoc type as certain for phpstan #7250

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

Merged
merged 1 commit into from
Jun 30, 2025
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
5 changes: 1 addition & 4 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ parameters:
- tests
- tests/Fixtures/app/console
inferPrivatePropertyTypeFromConstructor: true
treatPhpDocTypesAsCertain: false
symfony:
containerXmlPath: tests/Fixtures/app/var/cache/test/AppKernelTestDebugContainer.xml
constantHassers: false
Expand Down Expand Up @@ -112,11 +113,7 @@ parameters:
identifier: void.pure
-
identifier: varTag.nativeType
-
identifier: isset.offset
-
identifier: trait.unused
-
identifier: instanceof.alwaysTrue
-
identifier: catch.neverThrown
5 changes: 0 additions & 5 deletions src/Doctrine/Odm/State/LinksHandlerTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
use ApiPlatform\State\Util\StateOptionsTrait;
use Doctrine\ODM\MongoDB\Aggregation\Builder;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Doctrine\Persistence\ManagerRegistry;

/**
Expand Down Expand Up @@ -94,10 +93,6 @@ private function buildAggregation(string $toClass, array $links, array $identifi

$classMetadata = $manager->getClassMetadata($aggregationClass);

if (!$classMetadata instanceof ClassMetadata) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getClassMetadata returns always a ClassMetadata according to the native return type.

Yes, objectManager only has phpdoc for doctrine/persistence < 4, but here we always has a documentManager and this one use native type since 2.0
https://github.com/doctrine/mongodb-odm/blob/cdae04333cc592e3c0d388aa6745d1d486aed6e3/lib/Doctrine/ODM/MongoDB/DocumentManager.php#L282

throw new RuntimeException(\sprintf('The class metadata for "%s" must be an instance of "%s".', $aggregationClass, ClassMetadata::class));
}

$aggregation = $previousAggregationBuilder;
if ($aggregationClass !== $previousAggregationClass) {
$aggregation = $manager->createAggregationBuilder($aggregationClass);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public function create(string $resourceClass, string $property, array $options =

if ($doctrineClassMetadata instanceof ClassMetadata && \in_array($property, $doctrineClassMetadata->getFieldNames(), true)) {
$fieldMapping = $doctrineClassMetadata->getFieldMapping($property);
if (class_exists(FieldMapping::class) && $fieldMapping instanceof FieldMapping) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As soon as FieldMapping exists, it's the return type of the method.

if (class_exists(FieldMapping::class)) {
$propertyMetadata = $propertyMetadata->withDefault($fieldMapping->default ?? $propertyMetadata->getDefault());
} else {
$propertyMetadata = $propertyMetadata->withDefault($fieldMapping['options']['default'] ?? $propertyMetadata->getDefault());
Expand Down
2 changes: 1 addition & 1 deletion src/Doctrine/Orm/State/CollectionProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
$manager = $this->managerRegistry->getManagerForClass($entityClass);

$repository = $manager->getRepository($entityClass);
if (!method_exists($repository, 'createQueryBuilder')) { // @phpstan-ignore-line function.alreadyNarrowedType
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is now no error with treatPhpdocAsCertain: false

if (!method_exists($repository, 'createQueryBuilder')) {
throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
}

Expand Down
2 changes: 1 addition & 1 deletion src/Doctrine/Orm/State/ItemProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
}

$repository = $manager->getRepository($entityClass);
if (!method_exists($repository, 'createQueryBuilder')) { // @phpstan-ignore-line function.alreadyNarrowedType
if (!method_exists($repository, 'createQueryBuilder')) {
throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
}

Expand Down
5 changes: 2 additions & 3 deletions src/Elasticsearch/State/ItemProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
namespace ApiPlatform\Elasticsearch\State;

use ApiPlatform\Elasticsearch\Serializer\DocumentNormalizer;
use ApiPlatform\Metadata\Exception\RuntimeException;
use ApiPlatform\Metadata\InflectorInterface;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Util\Inflector;
Expand Down Expand Up @@ -49,9 +48,9 @@
public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?object
{
$resourceClass = $operation->getClass();
$options = $operation->getStateOptions() instanceof Options ? $operation->getStateOptions() : new Options(index: $this->getIndex($operation));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here options was always an Options.

  • Phpstan knows
  • PHPStorm doesn't

So I rewrite the code to help phpstorm understand it and avoid the false positive for phpstan

$options = $operation->getStateOptions();

Check warning on line 51 in src/Elasticsearch/State/ItemProvider.php

View check run for this annotation

Codecov / codecov/patch

src/Elasticsearch/State/ItemProvider.php#L51

Added line #L51 was not covered by tests
if (!$options instanceof Options) {
throw new RuntimeException(\sprintf('The "%s" provider was called without "%s".', self::class, Options::class));
$options = new Options(index: $this->getIndex($operation));

Check warning on line 53 in src/Elasticsearch/State/ItemProvider.php

View check run for this annotation

Codecov / codecov/patch

src/Elasticsearch/State/ItemProvider.php#L53

Added line #L53 was not covered by tests
}

$params = [
Expand Down
2 changes: 1 addition & 1 deletion src/Metadata/ApiResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -1026,7 +1026,7 @@ class: $class,
}

/**
* @return Operations<HttpOperation>
* @return Operations<HttpOperation>|null
*/
public function getOperations(): ?Operations
{
Expand Down
2 changes: 1 addition & 1 deletion src/Metadata/Tests/Resource/OperationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@

$this->assertSame($operation->getShortName(), 'test');
$this->assertSame($operation->canRead(), false);
$this->assertSame($operation instanceof CollectionOperationInterface, true);
$this->assertInstanceOf(CollectionOperationInterface::class, $operation);

Check warning on line 39 in src/Metadata/Tests/Resource/OperationTest.php

View check run for this annotation

Codecov / codecov/patch

src/Metadata/Tests/Resource/OperationTest.php#L39

Added line #L39 was not covered by tests
}

#[\PHPUnit\Framework\Attributes\DataProvider('operationProvider')]
Expand Down
6 changes: 3 additions & 3 deletions src/OpenApi/Factory/OpenApiFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@
$openapiAttribute = $operation->getOpenapi();

// Operation ignored from OpenApi
if ($operation instanceof HttpOperation && false === $openapiAttribute) {
if (false === $openapiAttribute) {
continue;
}

Expand Down Expand Up @@ -386,7 +386,7 @@
$existingResponses = $openapiOperation->getResponses() ?: [];
$overrideResponses = $operation->getExtraProperties()[self::OVERRIDE_OPENAPI_RESPONSES] ?? $this->openApiOptions->getOverrideResponses();
$errors = null;
if ($operation instanceof HttpOperation && null !== ($errors = $operation->getErrors())) {
if (null !== ($errors = $operation->getErrors())) {
/** @var array<class-string|string, Error> */
$errorOperations = [];
foreach ($errors as $error) {
Expand Down Expand Up @@ -629,7 +629,7 @@
}

// Operation ignored from OpenApi
if ($operation instanceof HttpOperation && (false === $operation->getOpenapi() || $operation->getOpenapi() instanceof Webhook)) {
if (false === $operation->getOpenapi() || $operation->getOpenapi() instanceof Webhook) {

Check warning on line 632 in src/OpenApi/Factory/OpenApiFactory.php

View check run for this annotation

Codecov / codecov/patch

src/OpenApi/Factory/OpenApiFactory.php#L632

Added line #L632 was not covered by tests
continue;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -909,7 +909,7 @@ protected function getAttributeValue(object $object, string $attribute, ?string

$data = $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
$context['data'] = $data;
$context['type'] = ($nullable && $type instanceof Type) ? Type::nullable($type) : $type;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We already check $type instanceof CollectionType before

$context['type'] = $nullable ? Type::nullable($type) : $type;

if ($this->tagCollector) {
$this->tagCollector->collect($context);
Expand Down
2 changes: 1 addition & 1 deletion src/Serializer/Tests/AbstractItemNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1204,7 +1204,7 @@
$errors = [];
$actual = $normalizer->denormalize($data, Dummy::class, null, ['not_normalizable_value_exceptions' => &$errors]);
$this->assertEmpty($actual->relatedDummies);
$this->assertCount(1, $errors); // @phpstan-ignore-line method.impossibleType (false positive)
$this->assertCount(1, $errors);

Check warning on line 1207 in src/Serializer/Tests/AbstractItemNormalizerTest.php

View check run for this annotation

Codecov / codecov/patch

src/Serializer/Tests/AbstractItemNormalizerTest.php#L1207

Added line #L1207 was not covered by tests
$this->assertInstanceOf(NotNormalizableValueException::class, $errors[0]);
$this->assertSame('relatedDummies[0]', $errors[0]->getPath());
$this->assertSame('Invalid IRI "wrong".', $errors[0]->getMessage());
Expand Down
2 changes: 1 addition & 1 deletion src/State/Provider/DeserializeProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
throw new UnsupportedMediaTypeHttpException('Format not supported.');
}

if ($operation instanceof HttpOperation && null === ($serializerContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE] ?? null)) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is

if (!$operation instanceof HttpOperation || !($request = $context['request'] ?? null)) {
            return $this->decorated?->provide($operation, $uriVariables, $context);
        }

before

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've also improved HttpOperation detection recently with 4dc91a0 don't hesitate if you find things that needs type definition improvement (we can always track them in a separated issue)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is another PHPStan failure to fix since the recent symfony release
#7255

if (null === ($serializerContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE] ?? null)) {
$method = $operation->getMethod();
$assignObjectToPopulate = 'POST' === $method
|| 'PATCH' === $method
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -629,7 +629,6 @@ private function registerGraphQlConfiguration(ContainerBuilder $container, array

$loader->load('graphql.xml');

// @phpstan-ignore-next-line because PHPStan uses the container of the test env cache and in test the parameter kernel.bundles always contains the key TwigBundle
if (!class_exists(Environment::class) || !isset($container->getParameter('kernel.bundles')['TwigBundle'])) {
if ($graphiqlEnabled) {
throw new RuntimeException(\sprintf('GraphiQL interfaces depend on Twig. Please activate TwigBundle for the %s environnement or disable GraphiQL.', $container->getParameter('kernel.environment')));
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Controller/MainController.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public function __invoke(Request $request): Response
{
$operation = $this->initializeOperation($request);

if (!$operation || !$operation instanceof HttpOperation) {
if (!$operation instanceof HttpOperation) {
throw new RuntimeException('Not an HTTP API operation.');
}

Expand Down
3 changes: 1 addition & 2 deletions src/Symfony/EventListener/DeserializeListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

namespace ApiPlatform\Symfony\EventListener;

use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\State\ProviderInterface;
use ApiPlatform\State\SerializerContextBuilderInterface;
Expand Down Expand Up @@ -62,7 +61,7 @@ public function onKernelRequest(RequestEvent $event): void
return;
}

if (null === $operation->canDeserialize() && $operation instanceof HttpOperation) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$this->initializeOperation always returns a HttpOperation and it use native return type.

Same idea for all the following $operation instanceof HttpOperation

if (null === $operation->canDeserialize()) {
$operation = $operation->withDeserialize(\in_array($method, ['POST', 'PUT', 'PATCH'], true));
}

Expand Down
3 changes: 1 addition & 2 deletions src/Symfony/EventListener/ReadListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

use ApiPlatform\Metadata\Exception\InvalidIdentifierException;
use ApiPlatform\Metadata\Exception\InvalidUriVariableException;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\UriVariablesConverterInterface;
use ApiPlatform\Metadata\Util\CloneTrait;
Expand Down Expand Up @@ -73,7 +72,7 @@ public function onKernelRequest(RequestEvent $event): void
}

$uriVariables = [];
if (!$request->attributes->has('exception') && $operation instanceof HttpOperation) {
if (!$request->attributes->has('exception')) {
try {
$uriVariables = $this->getOperationUriVariables($operation, $request->attributes->all(), $operation->getClass());
} catch (InvalidIdentifierException|InvalidUriVariableException $e) {
Expand Down
3 changes: 1 addition & 2 deletions src/Symfony/EventListener/WriteListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
use ApiPlatform\Metadata\Error;
use ApiPlatform\Metadata\Exception\InvalidIdentifierException;
use ApiPlatform\Metadata\Exception\InvalidUriVariableException;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\UriVariablesConverterInterface;
use ApiPlatform\Metadata\Util\ClassInfoTrait;
Expand Down Expand Up @@ -70,7 +69,7 @@ public function onKernelView(ViewEvent $event): void
}

$uriVariables = $request->attributes->get('_api_uri_variables') ?? [];
if (!$uriVariables && !$operation instanceof Error && $operation instanceof HttpOperation) {
if (!$uriVariables && !$operation instanceof Error) {
try {
$uriVariables = $this->getOperationUriVariables($operation, $request->attributes->all(), $operation->getClass());
} catch (InvalidIdentifierException|InvalidUriVariableException $e) {
Expand Down
Loading