'API Platform disable read

I have a project with API Platform and an Entity :

#[ApiResource(
    itemOperations: [
        'get',
        'put',
        'patch',
        'delete',
        'random' => [
            'method' => 'get',
            'path' => '/cards/random',
            'controller' => CardRandomController::class,
            "read" => false,
            "openapi_context" => [
                "parameters" => [
                    "id" => [
                        "name" => "id",
                        "in" => "path",
                        "required" => false,
                    ]
                ]
            ]
        ]
    ],
    denormalizationContext: ["groups" => "card:write"],
    normalizationContext: ["groups" => "card:read"]
)]
class Card
{ /* ... */ }

My controller :

class CardRandomController extends AbstractController
{
    public function __construct(private CardRepository $repository){}

    public function __invoke(): ?Card
    {
        $card = $this->repository->findRandom();
        return $card;
    }
}

It seems like I disabled the read listener, but still when I request /api/cards/random I get :

{
    "@context": "\/api\/contexts\/Error",
    "@type": "hydra:Error",
    "hydra:title": "An error occurred",
    "hydra:description": "Not Found",
    "trace": [
        {
            "namespace": "",
            "short_class": "",
            "class": "",
            "type": "",
            "function": "",
            "file": "D:\\workspace\\php\\mtg-edition-game\\vendor\\api-platform\\core\\src\\EventListener\\ReadListener.php",
            "line": 116,
            "args": []
        },
        /* ... */
    ]
}

I tried clearing the cache, but nothing will change. Strangely enough, if I change the route to /api/random/{id} and I request any pattern matching (e.g /api/random/foo) I have what I want (a random result). Still, that feels very weird to get this 404, is there something I'm missing ?



Solution 1:[1]

Okay, I don't really know why, but putting the custom operation before get in the attribute does the trick.

#[ApiResource(
    itemOperations: [
        'random' => [
            'method' => 'get',
            'path' => '/cards/random',
            'controller' => CardRandomController::class,
            'read' => false,
        ],
        'get',
        'put',
        'patch',
        'delete',
    ],
    denormalizationContext: ["groups" => "card:write"],
    normalizationContext: ["groups" => "card:read"]
)]
class Card { /* ... */ }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Altherius