json && beforeExecuteRoute

Hi, i'm trying to response with a json when, inside the beforeExecuteRoute, a condition is not satisfied. I not able to stop the execution and sent a json response. Now i'm doing this:

    public function beforeExecuteRoute()
    {
        $this->view->disable();

        $allowedIp = $this->getAllowedServer();
        foreach ($allowedIp as $key => $ip) {
            if ($_SERVER['SERVER_ADDR'] === $ip){
                return true;
            }
        }

        $this->response->setContentType('application/json');
        $this->response->setJsonContent(array(
            'status' => 'error',
            'message' => 'Access denied'
        ));

        return $this->response;
    }

it not work with 'exit' either 'retunr false'

Do you have some suggestions?

Thank you.

I'm not sure beforeExecuteRoute() can return the response like that. I don't usually bother with $this->response and just do the work manually because Phalcon's not really saving any work.

You should also be careful about disabling the view - you're doing that before you check the condition, so even if the condition is satisfied, the view will still be disabled. Also, you can just use in_array() instead of your for loop.

public function beforeExecuteRoute()
{  
    if(in_array($_SERVER['SERVER_ADDR'],$this->getAllowedServer())){
        return TRUE;
    }
    else{
        $this->view->disable();
        header('Content-type: text/json');
        echo json_encode([  'status'=>'error',
                            'message'=>'Access denied'
        ]);
        exit();
    }
}

Thank you for your answer but i prefered to use phalcon logic and a dedicated action:

 public function beforeExecuteRoute()
{
    $this->view->disable();

    if ($this->dispatcher-> getActionName() === 'jsonresponse' || in_array($this->getClientIp(), $this->geAllowedServer())){
        return true;
    } else {
        $this->dispatcher->forward([
            'controller' => 'cat',
            'action' => 'jsonresponse',
            "params" => array(
                "status" => "error",
                "message" => "Access denied"
            )
        ]);
        return false;
    }    
}


public function jsonResponseAction($status, $message)
{
    return $this->setJsonResponse($status, $message);
}