0
votes

I am testing my zf2 restful api by sending an OPTIONS command to it but its going right into the action defined in the router and not the options() method.

Router:

'router' => array(
    'routes' => array(
        'edatafeed' => array(
            'type'    => 'Zend\Mvc\Router\Http\Literal',
            'options' => array(
                'route'    => '/api',
                'defaults' => array(
                    '__NAMESPACE__'    => 'Application\Controller',
                ),
            ),
            'may_terminate' => true,
            'child_routes' => array(
                'default' => array(
                    'type'    => 'Segment',
                    'options' => array(
                        'route'    => '/:controller[/:action][/]',
                        'constraints' => array(
                            'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        ),
                        'defaults' => array(
                        ),
                    ),
                ),
            ),
        ),
    ),
),

Controller:

class SomeController extends ApiController
{
    protected $dm;

    private function getDm()
    {
        $this->dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
    }

    public function executeAction()
    {
        return new JsonModel(array(
            'ok' => false,
            'data' => null,
        ));
    }
}

ApiController:

class ApiController extends AbstractRestfulController
{

    protected function methodNotAllowed()
    {
        $this->response->setStatusCode(405);
        throw new \Exception('Method Not Allowed');
    }

    public function options()
    {
        $response = $this->getResponse();
        $headers  = $response->getHeaders();

        $headers->addHeaderLine('Allow', implode(',', array(
            'GET',
            'POST',
        )))
        ->addHeaderLine('Content-Type','application/json; charset=utf-8');
        return $response;
    }
}

When I sent an OPTIONS command to /api/some/execute it goes right into the execute action and not into the options method. Is there something I'm missing in the routing? I thought that sending any OPTIONS command would route it to options().

Thanks

2

2 Answers

0
votes

So it seems that the AbstractRestfulController actually checks to see if the request is to a custom action before checking the request method type. So since I defined an action called "execute" it routes straight to executeAction() before checking if its an OPTIONS command. I had to override the onDispatch() method in my ApiController class and only route to my custom method if its a GET, POST, or UPDATE command. Otherwise route to appropriate method type method.

This is the code I modified:

    // RESTful methods
    $method = strtolower($request->getMethod());

    // Was an "action" requested?
    $action  = $routeMatch->getParam('action', false);
    if ($action &&
        ($method == 'get' || $method == 'post' || $method == 'update')) {
        // Handle arbitrary methods, ending in Action
        $method = static::getMethodFromAction($action);
        if (! method_exists($this, $method)) {
            $method = 'notFoundAction';
        }
        $return = $this->$method();
        $e->setResult($return);
        return $return;
    }

Hope this helps someone else in the future.

0
votes

I've had this problem and solve it as follows:

class ApiRestfullController extends AbstractRestfulController {

    protected $allowedCollectionMethods = array(
        'POST',
        'GET'
    );

    public function setEventManager(EventManagerInterface $events) {
        parent::setEventManager($events);

        $events->attach('dispatch', function ($e) {
            $this->checkOptions($e);
        }, 10);
    }

    public function checkOptions($e) {
        $response = $this->getResponse();
        $request = $e->getRequest();
        $method = $request->getMethod();

        if (!in_array($method, $this->allowedCollectionMethods)) {
            $this->methodNotAllowed();
            return $response;
        }
    }

    public function methodNotAllowed() {
        $this->response->setStatusCode(
            \Zend\Http\PhpEnvironment\Response::STATUS_CODE_405
        );
        throw new Exception('Method Not Allowed');
    }
}

I hope this will help solve the problem.