Cannot respond with 404 in HEAD request

531 Views Asked by At

I'm unable to respond with a 404 not found when implementing a HEAD request in apigility. Apigility handles HEAD request with the same resource method as GET requests by default. This is the fetch($id) method.

My resource looks like this:

class MyResource extends AbstractResourceListener implements ResourceInterface
{
    public function fetch($id)
    {
        $entity = $this->getEntityById($id, false);
        if ($entity === null) {
            return new ApiProblemResponse(new ApiProblem(404, 'Entity with ID ' . $id . ' not found'));
        }

        return $entity;
    }
}

When accessing the resource with a REST client using a HEAD I get a 200 OK. I can confirm the ApiProblemResponse is returned from the method. Requesting the resource using a GET I get a 404 response as expected.

It seems to be related to the handling of HEAD and GET in the AbstractRestfulController. Here is a code snippet of the related code:

case 'get':
    $id = $this->getIdentifier($routeMatch, $request);
    if ($id !== false) {
        $action = 'get';
        $return = $this->get($id);
        break;
    }
    $action = 'getList';
    $return = $this->getList();
    break;
// HEAD
case 'head':
    $id = $this->getIdentifier($routeMatch, $request);
    if ($id === false) {
        $id = null;
    }
    $action = 'head';
    $this->head($id);
    $response = $e->getResponse();
    $response->setContent('');
    $return = $response;
    break;

In the get implementation the result from the resourceListener method is returned as the application response. This seems correct to me. In the head implementation the MvcEvent response is used, thus ignoring the ApiProblemResponse I return from the resourceListener. I'm unable to access the MvcEvent from my ResourceListener.

Does anyone have a solution to be able to return a 404 for a HEAD request?

0

There are 0 best solutions below