Skip to content

Undefined array offsets in SerializerContextBuilderInterface::createFromRequest with PHPStan #7471

@eliot488995568

Description

@eliot488995568

API Platform version(s) affected: 4.2.2

Description

In src/State/SerializerContextBuilderInterface.php

Phpstan annotation return type need to define some special key or phpstan throw error because he cannot access to offset like 'groups'.
image

https://api-platform.com/docs/core/serialization/#changing-the-serialization-context-dynamically

//  File AbstractAdminContextBuilder.php who implements SerializerContextBuilderInterface
#[\Override]
public function createFromRequest(Request $request, bool $normalization, ?array $extractedAttributes = null): array
{
    $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
    $resourceClass = $context['resource_class'] ?? null;
    $operation = $context['operation'] ?? null;
    $isItemOperation = $operation instanceof Get
        || $operation instanceof Patch
        || $operation instanceof Put;

    if ($resourceClass === $this->getApplicableResourceClass()) {
        if (!isset($context['groups'])) {
            $context['groups'] = [];
        }
        if (is_string($context['groups'])) {
            $context['groups'] = [$context['groups']];
        }
        if ($this->authorizationChecker->isGranted('ROLE_INVITED_USER')) {
            if ($normalization) {
                $context['groups'][] = 'timestamp:read';
                $context['groups'][] = 'blamable:read';
                $context['groups'][] = 'thing:read:user';
                $context['groups'][] = $this->getBaseSerializationGroup().':read:user';
                if ($isItemOperation) {
                    $context['groups'][] = 'thing:single:read:user';
                    $context['groups'][] = $this->getBaseSerializationGroup().':single:read:user';
                }
...

How to reproduce
Use PHPStan with configuration level: max
Create a custom class implementing SerializerContextBuilderInterface and override the createFromRequest method.
Inside this method, try to access specific context keys such as 'groups'.
Run PHPStan analysis: it will report errors.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions