Handle the request

@param  MvcEvent $e
@return mixed
426006
public function onDispatch(MvcEvent $e)
    {
        try {
            parent::onDispatch($e);
        } catch (\Exception $e) {
            return $this->getResponse()->setStatusCode(500)->setContent($e->__toString());
        }
    }
999946
public function prepareException(MvcEvent $e)
    {
        if ($e->getRequest() instanceof Request) {
            $error = $e->getError();
            if (!empty($error) && !$e->getResult() instanceof Response) {
                switch ($error) {
                    case Application::ERROR_CONTROLLER_NOT_FOUND:
                    case Application::ERROR_CONTROLLER_INVALID:
                    case Application::ERROR_ROUTER_NO_MATCH:
                        // Specifically not handling these
                        return;

                    case Application::ERROR_EXCEPTION:
                    default:
                        /** @var Exception $exception */
                        $exception = $e->getParam('exception');
                        // Filter exceptions that we must except
                        foreach ($this->whoopsConfig['blacklist'] as $except) {
                            if ($exception instanceof $except) {
                                return;
                            }
                        }

                        if ($this->whoopsConfig['handler']['options_type'] === 'prettyPage') {
                            $response = $e->getResponse();
                            if (!$response || $response->getStatusCode() === 200) {
                                header('HTTP/1.0 500 Internal Server Error', true, 500);
                            }
                            ob_clean();
                        }

                        $this->run->handleException($e->getParam('exception'));
                        break;
                }
            }
        }
    }
1090346
public function handle($e)
	{
		$this->logException($e);

		if ($this->isExceptionHalting($e))
		{
			if (ob_get_contents() !== false) ob_end_flush();
			if($this->_showStackTrace) echo "\n".$e->__toString()."\n\n";
			exit(self::EXIT_CODE);
		}
	}
57444
protected function config(MvcEvent $event)
    {
        $appConfig = $event->getApplication()->getServiceManager()->get('config');
        $config = array_key_exists(self::CONFIG_KEY, $appConfig) ? $appConfig[self::CONFIG_KEY] : array();
        
        if (array_key_exists('template', $config)) {
            $this->setTemplate($config['template']);
        }
        
        if (array_key_exists('renderLayout', $config)) {
            $this->setRenderLayout($config['renderLayout']);
        }
    }
1200827
public function onRoute(MvcEvent $event)
    {
        $authService = $this->authService;

        $match = $event->getRouteMatch();
        if (!$authService->isAllowed(new PermResource(['route_match' => $match]), null))
            $authService->riseException();
    }
883215
public function onCorsPreflight(MvcEvent $event)
    {
        // Reset state flag
        $this->isPreflight = false;

        /** @var $request HttpRequest */
        $request = $event->getRequest();

        if (! $request instanceof HttpRequest) {
            return;
        }

        try {
            $isCorsRequest = $this->corsService->isCorsRequest($request);
        } catch (InvalidOriginException $exception) {
            /** @var HttpResponse $response */
            $response = $event->getResponse();
            $response->setStatusCode(400);
            $response->setReasonPhrase($exception->getMessage());
            return $response;
        }

        // If this isn't a preflight, done
        if (! $isCorsRequest || ! $this->corsService->isPreflightRequest($request)) {
            return;
        }

        // Preflight -- return a response now!
        $this->isPreflight = true;

        return $this->corsService->createPreflightCorsResponseWithRouteOptions($request, $event->getRouteMatch());
    }
1019419
public function onDispatch(MvcEvent $e)
    {
        $routeMatch = $e->getRouteMatch();
        if (!$routeMatch) {
            /**
             * @todo Determine requirements for when route match is missing.
             *       Potentially allow pulling directly from request metadata?
             */
            throw new \Zend\Mvc\Exception\DomainException('Missing route matches; unsure how to retrieve action');
        }

        $action = $routeMatch->getParam('action', null);

        if ($action) {
            $action = strtolower($action);
        }

        switch ($action) {
            case 'process':
                $message = $routeMatch->getParam('message', null);

                if($message instanceof MessageInterface) {
                    $result = $this->process($message);
                } else {
                    throw new \InvalidArgumentException(
                        'Missing or invalid message type: must be an instace of '. MessageInterface::class
                    );
                }
                break;

            case 'send':
            case 'receive':
            case 'await':

                $queue = $routeMatch->getParam('queue', null);

                if (is_string($queue)) {
                    $queue = $this->getServiceLocator()->get($queue);
                }

                if (!$queue instanceof QueueClientInterface) {
                    throw new \InvalidArgumentException(
                        'Invalid queue param type: must be a string or an instace of '. QueueClientInterface::class
                    );
                }

                if ($action === 'send') {

                    $message = $routeMatch->getParam('message', null);
                    $parameters = $routeMatch->getParam('sendParameters', null);

                    if ($parameters === null) {
                        $params = null;
                    } else if ($parameters instanceof SendParametersInterface) {
                        $params = $parameters;
                    } else if (is_string($parameters)) {
                        $params = new SendParameters();
                        $params->fromString($parameters);
                    } else if (is_array($parameters)) {
                        $params = new SendParameters();
                        $params->fromArray($parameters);
                    } else {
                        throw new \InvalidArgumentException(
                            'Invalid sendParameters param type: must be null, an array, a string or an instace of '. SendParametersInterface::class
                        );
                    }

                    $result = $this->send($queue, $message, $params);
                } else {

                    $parameters = $routeMatch->getParam('receiveParameters', null);

                    if ($parameters === null) {
                        $params = null;
                    } else if ($parameters instanceof ReceiveParametersInterface) {
                        $params = $parameters;
                    } else if (is_string($parameters)) {
                        $params = new ReceiveParameters();
                        $params->fromString($parameters);
                    } else if (is_array($parameters)) {
                        $params = new ReceiveParameters();
                        $params->fromArray($parameters);
                    } else {
                        throw new \InvalidArgumentException(
                            'Invalid receiveParameters param type: must be null, an array, a string or an instace of '. QueueClientInterface::class
                        );
                    }

                    if ($action === 'receive') {
                        $maxMessages = (int) $routeMatch->getParam('maxMessages', 1);
                        $result = $this->receive($queue, $maxMessages, $params);
                    } else {
                        $result = $this->await($queue, $params);
                    }
                }
                break;

            default:
                throw new \InvalidArgumentException(
                    sprintf('Invalid action "%s". Only "process", "send", "receive", "await" are allowed', $action)
                );
        }


        $e->setResult($result);

        return $result;
    }
210394
public function preDispatch(MvcEvent $e)
    {
        if ('calculate' == $this->params()->fromQuery('do')) {
            return;
        }
        $routeMatch = $e->getRouteMatch();
        $action = $routeMatch->getParam('action');
	    $services = $e->getApplication()->getServiceManager();
        if (in_array($action, array('edit', 'approval', 'completion'))) {
            $jobEvents = $services->get('Jobs/Events');
            $mailSender = $services->get('Jobs/Listener/MailSender');

            $mailSender->attach($jobEvents);
        }
    }
1160302
public function onDispatch(MvcEvent $e)
    {
        $request = $e->getRequest();
        if (!$request instanceof HttpRequest) {
            throw new RuntimeException('CRUD controller from CmsCommon can only handle HTTP requests');
        }

        $action = $this->params()->fromRoute('action', 'not-found');
        $method = static::getMethodFromAction($action);

        if (!method_exists($this, $method)) {
            $method = 'notFoundAction';
        }

        $object = null;
        if ($action === static::ACTION_READ ||
            $action === static::ACTION_UPDATE ||
            $action === static::ACTION_DELETE
        ) {
            $options = $this->getOptions();
            $id = $this->params()->fromRoute($options->getIdentifierKey());

            if (null === $id) {
                $this->flashMessenger()->addWarningMessage(sprintf(
                    $this->translate('An identifier must be provided to %s an object'),
                    $this->translate($action)
                ));

                return $this->redirectToBaseRoute();
            }

            if (!($object = $this->getDomainService()->getMapper()->find($id))) {
                $this->flashMessenger()->addWarningMessage($this->translate('An object cannot be found'));
                return $this->redirectToBaseRoute();
            }
        }

        $data = $this->getData($object);

        // Return early if getData method returned a response
        if ($data instanceof ResponseInterface) {
            $actionResponse = $data;
        } else {
            switch ($action) {
                case static::ACTION_READ:
                case static::ACTION_DELETE:
                    $actionResponse = $this->$method($data, $object);
                    break;
                case static::ACTION_UPDATE:
                    $actionResponse = $this->$method($data, $object);
                    break;
                default:
                    $actionResponse = $this->$method($data);
            }
        }

        $e->setResult($actionResponse);
    }
1359996
public function onBootstrap(MvcEvent $e)
    {
        $config = $e->getApplication()->getServiceManager()->get('Config');
        if (!empty($config[$this->configKey])) {
            $phpSettings = (array) $config[$this->configKey];
            foreach($phpSettings as $key => $value) {
                @ini_set($key, $value);
            }
        }
    }
980500
protected function runHandlers($e)
    {
        /** @var \League\BooBoo\Handler\HandlerInterface $handler */
        foreach (array_reverse($this->handlerStack) as $handler) {
            $handledException = $handler->handle($e);
            if ($handledException instanceof \Exception) {
                $e = $handledException;
            }
        }

        return $e;
    }
658888
public static function handler (\Exception $e) {
    try {
      $project = PSC::getProject();
    } catch (\Exception $noProjet) {
      $project = NULL;
    }
    
    $format = PHP_SAPI === 'cli' ? 'text' : 'html';
    
    $text = self::getExceptionText($e, $format, $project);
    
    print $text;
    
    PSC::getEnvironment()->getErrorHandler()->handleCaughtException($e);
  }
757986
public function onDispatchedListener(MvcEvent $event)
    {
        $data = $event->getTarget()->getData();
        $config = [];
        try {
            $config = $event->getApplication()->getServiceManager()->get('ApplicationConfig');
        } catch (\Psr\Container\ContainerExceptionInterface $e) {
            //todo
        }
        $data['env'] = isset($config['application']['env']) ? $config['application']['env'] : 'development';


        if (BaseController::RESPONSE_JSON == $data[BaseController::RS_KEY_TYPE] ||
            BaseController::RESPONSE_PLAIN == $data[BaseController::RS_KEY_TYPE]
        ) {
            $response = $event->getResponse();
            if (!$response instanceof Response) {
                $response = new Response();
            }

            $contentType = new ContentType();
            $contentType->setCharset('UTF-8');

            $content = '';

            if (BaseController::RESPONSE_JSON == $data[BaseController::RS_KEY_TYPE]) {
                $contentType->setMediaType('application/json');

                $content = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
            }

            if (BaseController::RESPONSE_PLAIN == $data[BaseController::RS_KEY_TYPE]) {
                $contentType->setMediaType('text/plain');
                $data = $data[BaseController::RS_KEY_DATA];
                if (!$data instanceof \stdClass) {
                    $content = '';
                } else {
                    if (isset($data->content)) {
                        $content = $data->content;
                    } else {
                        $data = json_decode(json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE), true);
                        $content = implode('', $data);
                    }
                }
            }

            $response->getHeaders()->addHeader($contentType);
            $response->setContent($content);

            $event->setResult($response); //Stop render event

            return;
        }


        $request = $event->getRequest();
        if (!$request instanceof Request) {
            throw new RuntimeException('The request is invalid', 1001);
        }

        if ($request->isXmlHttpRequest()) {
            $result = $event->getResult();
            if ($result)
            if (!$result instanceof ViewModel) {
                $result = new ViewModel();
            }

            $result->setTerminal(true); //Disabled layout
            $result->setVariables($data);

            $event->setViewModel($result);
            $event->setResult($result);
        } else {
            $model = $event->getViewModel();
            $model->setVariables($data);
            if ($model->hasChildren()) {
                foreach($model->getChildren() as $child) {
                    if ($child instanceof ViewModel) {
                        $child->setVariables($data);
                    }
                }
            }
        }

    }
717259
public function onRoute(MvcEvent $event)
    {
        $authService = $this->authService;

        $resource  = new PermResource();
        $match     = $event->getRouteMatch();
        $routeName = $match->getMatchedRouteName();
        $resource->setRouteName($routeName);

        if ($authService->isAllowed($resource, null))
            // Authorized User with Access
            return ;

        $authService->riseException(new AccessDeniedException());
    }
839407
public function finishEvent(MvcEvent $event)
    {
        $matchRoute = $event->getRouteMatch();

        if (empty($matchRoute)) {
            return null;
        }

        /** @var \Rcm\EventListener\EventFinishListener $eventFinishListener */
        $eventFinishListener = $this->serviceLocator->get(
            \Rcm\EventListener\EventFinishListener::class
        );

        $return = $eventFinishListener->processRcmResponses($event);

        if (!empty($return)) {
            return $return;
        }

        return null;
    }
1057176
public function dispatchError(\Zend\Mvc\MvcEvent $e)
    {
        $error = $e->getError();
        if (empty($error)) {
            return;
        }

        // Do nothing if the result is a response object
        $result = $e->getResult();
        if ($result instanceof \Zend\Stdlib\ResponseInterface) {
            return;
        }

        switch ($error) {
            case \Zend\Mvc\Application::ERROR_CONTROLLER_NOT_FOUND:
            case \Zend\Mvc\Application::ERROR_CONTROLLER_INVALID:
            case \Zend\Mvc\Application::ERROR_ROUTER_NO_MATCH:
            case 'error-route-unauthorized':
                // Specifically not handling these
                return;

            case \Zend\Mvc\Application::ERROR_EXCEPTION:
                $exception = $e->getParam('exception');
                if (!($exception instanceof \Exception)) {
                    return;
                }
                $msg = '';
                $prev = $exception->getPrevious();
                while ($prev !== null) {
                    $msg .= PHP_EOL.'Previous: '.$prev->getMessage().' in '.
                             $prev->getFile().' in line '.$prev->getLine().
                             '.';
                    $prev = $prev->getPrevious();
                }
                $this->log(ErrorLogger::ERR,
                        'Dispatch: '.$exception->getMessage().' in '.
                                 $exception->getFile().' in line '.
                                 $exception->getLine().'.'.$msg.PHP_EOL.
                                 'Trace:'.PHP_EOL.
                                 $exception->getTraceAsString());
                break;
            default:
                $this->log(ErrorLogger::ERR,
                'Erro desconhecido no dispatch: '.$error);
                break;

        }
    }
811790
public function onDispatchError( MvcEvent $event )
    {
        /* @var $exception \Exception  */
        $exception = $event->getParam( 'exception' );

        if ( $exception && $exception instanceof Exception )
        {
            $this->exceptionHandler( $exception, false );
        }

        if ( $this->response )
        {
            $event->stopPropagation();
            return $this->response;
        }
    }