<?php

namespace Velis\Mvc;

use Phalcon\Di\Injectable;
use Phalcon\Events\Event;
use Phalcon\Mvc\Dispatcher;

/**
 * MVC Dispatcher annotation plugin
 * @author Franczak Paweł <pawel.franczak@velis.pl>
 */
class Annotation extends Injectable
{
    private $doExecuteRequest = true;

    public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
    {
        $annotations = $this->annotations->getMethod(
            $dispatcher->getControllerClass(),
            $dispatcher->getActiveMethod()
        );

        if ($annotations->has('Method')) {
            $this->validatingMethodTypes($annotations->get('Method'));
        }

        return $this->doExecuteRequest;
    }


    private function validatingMethodTypes($annotation)
    {
        $allowMethods = $annotation->getArguments();
        $incomingMethod = $this->request->getMethod();

        if (!in_array($incomingMethod, $allowMethods)) {
            $this->view->disable();
            $this->response->setStatusCode(405, 'Error');
            echo json_encode([
                    'errors' => [
                        'message' => "Method Not Allowed",
                        'code'    => 405
                    ]
                ]);
            $this->doExecuteRequest = false;
        }
    }
}
