/** * Injects the node into the global MVC-Event-instance. * * @param MvcEvent $event */ public function injectMatchedNode(MvcEvent $event) { $routeMatch = $event->getRouteMatch(); /* @var $routeMatch \Zend\Mvc\Router\Http\RouteMatch */ $name = $routeMatch->getMatchedRouteName(); $serviceLocator = $event->getApplication()->getServiceManager(); $node = $serviceLocator->get('NodeService')->getNode(str_replace('node-', '', $name)); if (false != $node) { $event->setParam('matchedNode', $node); // Update access counter if enabled if (true == $serviceLocator->get('NodeOptions')->getEnableAccessCounter()) { $sessionContainer = new Container('node_access'); $node->setNodeAccessDate(date('Y-m-d H:i:s')); if (false == $sessionContainer->{$node->getNodeId()}) { $node->setNodeAccessCount($node->getNodeAccessCount() + 1); $sessionContainer->{$node->getNodeId()} = 1; } $serviceLocator->get('NodeService')->saveNode($node); } // Redirect if it's a Redirect-Node... if ('redirect' == $node->getNodeType()) { $response = $event->getResponse(); $response->setStatusCode($node->getNodeRedirectCode()); $response->getHeaders()->addHeaderLine('Location', $node->getNodeRedirectTarget()); $response->sendHeaders(); } } else { $event->setParam('matchedNode', null); } }
public function testDoesNotLimitDispatchErrorEventToOnlyOneListener() { $eventManager = new EventManager(); $application = $this->prophesize(Application::class); $application->getEventManager()->willReturn($eventManager); $event = new MvcEvent(); $event->setApplication($application->reveal()); $guard = new DummyGuard(); $guard->attach($eventManager); $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function (MvcEvent $event) { $event->setParam('first-listener', true); }); $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function (MvcEvent $event) { $event->setParam('second-listener', true); }); // attach listener with lower priority than DummyGuard $eventManager->attach(MvcEvent::EVENT_ROUTE, function (MvcEvent $event) { $this->fail('should not be called, because guard should stop propagation'); }, DummyGuard::EVENT_PRIORITY - 1); $event->setName(MvcEvent::EVENT_ROUTE); $eventManager->triggerEvent($event); $this->assertTrue($event->getParam('first-listener')); $this->assertTrue($event->getParam('second-listener')); $this->assertTrue($event->propagationIsStopped()); }
public function onDispatch(MvcEvent $e) { $routeMatch = $e->getRouteMatch(); $contentNegotiationParams = $e->getParam('ZFContentNegotiationParameterData'); if ($contentNegotiationParams) { $routeParameters = $contentNegotiationParams->getRouteParams(); } else { $routeParameters = $routeMatch->getParams(); } $parameterMatcher = new ParameterMatcher($e); // match route params to dispatchable parameters if ($this->wrappedCallable instanceof \Closure) { $callable = $this->wrappedCallable; } elseif (is_array($this->wrappedCallable) && is_callable($this->wrappedCallable)) { $callable = $this->wrappedCallable; } elseif (is_object($this->wrappedCallable) || is_null($this->wrappedCallable)) { $action = $routeMatch->getParam('action', 'not-found'); $method = static::getMethodFromAction($action); $callable = is_null($this->wrappedCallable) && get_class($this) != __CLASS__ ? $this : $this->wrappedCallable; if (!method_exists($callable, $method)) { $method = 'notFoundAction'; } $callable = [$callable, $method]; } else { throw new \Exception('RPC Controller Not Understood'); } $dispatchParameters = $parameterMatcher->getMatchedParameters($callable, $routeParameters); $result = call_user_func_array($callable, $dispatchParameters); $e->setParam('ZFContentNegotiationFallback', ['Zend\\View\\Model\\JsonModel' => ['application/json']]); $e->setResult($result); }
/** * {@inheritDoc} */ public function isAuthorized(MvcEvent $event) { $service = $this->getAuthorizationService(); $match = $event->getRouteMatch(); $controller = $match->getParam('controller'); $action = $match->getParam('action'); $request = $event->getRequest(); $method = $request instanceof HttpRequest ? strtolower($request->getMethod()) : null; if ($service->isAllowed($this->getResourceName($controller)) || $service->isAllowed($this->getResourceName($controller, $action)) || $method && $service->isAllowed($this->getResourceName($controller, $method))) { return true; } $event->setParam('controller', $controller); $event->setParam('action', $action); $errorMessage = sprintf('You are not authorized to access %s:%s', $controller, $action); throw new UnauthorizedException($errorMessage, 403); }
public function testProcessPostRequestReturnsToken() { $request = new Request(); $request->setMethod('post'); $parameters = new ParameterDataContainer(); $parameters->setBodyParam('format', 'ZIP'); $event = new MvcEvent(); $event->setParam('ZFContentNegotiationParameterData', $parameters); $request->getHeaders()->addHeaderLine('Content-Type', 'application/json'); $request->getHeaders()->addHeaderLine('Accept', 'application/json'); $this->controller->setRequest($request); $this->controller->setEvent($event); $cwd = getcwd(); chdir(__DIR__ . '/TestAsset'); $result = $this->controller->indexAction(); chdir($cwd); $this->assertInternalType('array', $result); $this->assertTrue(isset($result['token'])); $this->assertTrue(isset($result['format'])); $package = sys_get_temp_dir() . '/apigility_' . $result['token'] . '.' . $result['format']; $this->assertTrue(file_exists($package)); return $result; }
private function createMvcEventWithException() { $mvcEvent = new MvcEvent(); $exception = new Exception('foo'); $mvcEvent->setParam('exception', $exception); return $mvcEvent; }
protected function terminateEvent(MvcEvent $event, $error, \Exception $exception) { $eventManager = $event->getApplication()->getEventManager(); $event->setError($error); $event->setParam('exception', $exception); $event->stopPropagation(true); $eventManager->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event); }
/** * Event callback to be triggered on dispatch, causes application error triggering * in case of failed authorization check * * @param MvcEvent $event * * @return void */ public function onRoute(MvcEvent $event) { /* @var $service \BjyAuthorize\Service\Authorize */ $service = $this->serviceLocator->get('BjyAuthorize\\Service\\Authorize'); $match = $event->getRouteMatch(); $routeName = $match->getMatchedRouteName(); if ($service->isAllowed('route/' . $routeName)) { return; } $event->setError(static::ERROR); $event->setParam('route', $routeName); $event->setParam('identity', $service->getIdentity()); $event->setParam('exception', new UnauthorizedException('You are not authorized to access ' . $routeName)); /* @var $app \Zend\Mvc\Application */ $app = $event->getTarget(); $app->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event); }
public function testExecute_WhenExceptionIsNotFromAPI() { $exception = new \Exception(); $event = new MvcEvent(); $event->setParam('exception', $exception); $this->loggerMock->expects($this->once())->method('crit')->with($exception); $this->testedObject->execute($event); }
public function testCanCreateFromCustomException() { $httpExceptionListener = new HttpExceptionListener([\InvalidArgumentException::class => Exception\Client\NotFoundException::class]); $this->event->setParam('exception', new \InvalidArgumentException('An error')); $httpExceptionListener->onDispatchError($this->event); $this->assertInstanceOf(Response::class, $this->event->getResponse()); $this->assertEquals('An error', $this->event->getResponse()->getReasonPhrase()); $this->assertTrue($this->event->propagationIsStopped()); }
public function testOnError_WithApiException() { $event = new MvcEvent(); $event->setError("The resource doesn't support the specified HTTP verb."); $event->setParam('exception', new MethodNotAllowedException()); $event->setResponse(new Response()); $result = $this->testedObject->onError($event); $this->assertInstanceOf(JsonModel::class, $result); }
public function testFillEvent() { $event = new MvcEvent(); $event->setParam('exception', new Exception\UnauthorizedException()); $response = new HttpResponse(); $event->setResponse($response); $listener = new ErrorListener(); $listener->onError($event); }
public function testCatchesUnknownErrorTypes() { $exception = new \Exception(); $event = new MvcEvent(); $event->setParam('exception', $exception)->setError('custom_error'); $this->strategy->prepareExceptionViewModel($event); $response = $event->getResponse(); $this->assertTrue($response->isServerError()); }
public function loadPage(MvcEvent $e) { $match = $e->getRouteMatch(); $pageId = $match->getParam('page-id', null); if (null !== $pageId && is_numeric($pageId)) { $em = $this->doctrine->getEntityManager(); $page = $em->find('Zcmf\\Application\\Model\\Page', $pageId); $e->setParam('page', $page); } }
public function onRoute(MvcEvent $event) { $err = RouteGuard::ERROR; $service = $this->serviceLocator->get('BjyAuthorize\\Service\\Authorize'); /* @var $match \Zend\Mvc\Router\RouteMatch */ $match = $event->getRouteMatch(); $routeName = $match->getMatchedRouteName(); $privilege = $match->getParam('xelax_admin_privilege'); $privilegeParts = explode('/', $privilege); if (empty($privilege) || array_pop($privilegeParts) == 'subroute' || $service->isAllowed('xelax-route/' . $routeName, $privilege)) { return; } $event->setError($err); $event->setParam('route', $routeName); $event->setParam('identity', $service->getIdentity()); $event->setParam('exception', new UnAuthorizedException('You are not authorized to access ' . $routeName)); /* @var $app \Zend\Mvc\Application */ $app = $event->getTarget(); $app->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event); }
public function registerShutdownError(MvcEvent $e) { register_shutdown_function(function () use($e) { $error = error_get_last(); if ($error != null && $error["type"] != E_DEPRECATED) { $exception = new \ErrorException($error['message'], 0, 1, $error['file'], $error['line']); $e->setParam('exception', $exception); $e->getApplication()->getEventManager()->trigger('dispatch.error', $e); } }); }
public function testHelperInvokationReturnsParamFromRouteIfPresentOrFromEventOrDefault() { $e = new MvcEvent(); $routeMatch = new RouteMatch(array('testParam1' => 'routeValue')); $e->setRouteMatch($routeMatch); $e->setParam('testParam2', 'eventValue'); $helper = new Helper($e); $this->assertEquals('routeValue', $helper('testParam1')); $this->assertEquals('eventValue', $helper('testParam2')); $this->assertEquals('defaultValue', $helper('testParam3', 'defaultValue')); }
public function testEventHandlerNotCallLogger() { $this->moduleOptions = new ModuleOptions(); $this->listener->setModuleOptions($this->moduleOptions); $this->moduleOptions->setExceptionsLoggingEnabled(false); $mvcEvent = new MvcEvent(); $exception = new Exception('a message'); $mvcEvent->setParam('exception', $exception); $this->listener->onError($mvcEvent); $this->assertCount(0, $this->writer->events); }
/** * Capture Error converted to exception, then trigger a dispatch error * @param MvcEvent $e */ public function onEvent(MvcEvent $event) { $exception = ErrorHandler::stop(); if ($exception instanceof \Exception) { $event->setError(Application::ERROR_EXCEPTION); $event->setParam('exception', $exception); $this->getEventManager()->trigger($event::EVENT_DISPATCH_ERROR, $event); } elseif (!$event->getError() && $event->getResponse()->getStatusCode() == 404) { $event->setError(Application::ERROR_CONTROLLER_CANNOT_DISPATCH); $this->getEventManager()->trigger($event::EVENT_DISPATCH_ERROR, $event); } }
public function onDispatch(MvcEvent $event) { /* @var $routeMatch RouteMatch */ $routeMatch = $event->getRouteMatch(); /* @var $injector DoctrineObjectInjector */ $injector = $this->serviceLocator->get(DoctrineObjectInjector::class); $keysToRemove = array('controller', 'action'); $params = $routeMatch->getParams(); foreach ($params as $key => $value) { if (in_array($key, $keysToRemove)) { unset($params[$key]); } } try { $arguments = $injector->makeArguments($routeMatch->getParam('controller'), $routeMatch->getParam('action'), $params); $event->setParam('__method_arguments', $arguments); } catch (EntityNotFoundException $e) { $event->getRouteMatch()->setParam('action', 'not-found'); $event->setParam('__method_arguments', []); } }
public function testFillEvent() { $response = new HttpResponse(); $mvcEvent = new MvcEvent(); $mvcEvent->setParam('exception', new UnauthorizedException()); $mvcEvent->setResponse($response); $options = new UnauthorizedStrategyOptions(['template' => 'error/403']); $unauthorizedStrategy = new UnauthorizedStrategy($options); $unauthorizedStrategy->onError($mvcEvent); $this->assertEquals(403, $mvcEvent->getResponse()->getStatusCode()); $this->assertInstanceOf('Zend\\View\\Model\\ModelInterface', $mvcEvent->getResult()); }
/** * Method that tries to load cached routes and speed up the matching * * @param MvcEvent $event */ public function routeLoad(MvcEvent $event) { $request = $event->getRequest(); if (!($request instanceof HttpRequest && $request->isGet() && $request->getQuery()->count() == 0)) { // We do not cache route match for requests that can produce // different match. return; } $event->setParam('route-cacheable', true); // check if we have data in our cache $path = $request->getUri()->getPath(); $services = $event->getApplication()->getServiceManager(); $cacheName = $services->get(RouterCacheOptions::class)->getCache(); $cache = $services->get($cacheName); $cacheKey = $this->getCacheKey($path); $cachedData = $cache->getItem($cacheKey); if ($cachedData) { $event->setParam('route-cached', true); $router = $event->getRouter(); $router->addRoute($cachedData['name'], $cachedData['spec'], round(PHP_INT_MAX / 2)); } }
/** * @param MvcEvent $e * @return mixed|\Zend\Http\Response|ViewModelInterface */ public function onDispatch(MvcEvent $e) { if (!empty($this->options['allowedMethods']) && !in_array($this->sebaksRequest->getMethod(), $this->options['allowedMethods'])) { return $this->error->methodNotAllowed(); } $e->setParam('sebaksRequest', $this->sebaksRequest); $e->setParam('sebaksResponse', $this->sebaksResponse); $routeName = $e->getRouteMatch()->getMatchedRouteName(); $this->getEventManager()->trigger("dispatch.{$routeName}.pre", $e); $this->controller->dispatch($this->sebaksRequest, $this->sebaksResponse); $this->getEventManager()->trigger("dispatch.{$routeName}.post", $e); $criteriaErrors = $this->sebaksResponse->getCriteriaErrors(); if (!empty($criteriaErrors)) { return $this->error->notFoundByRequestedCriteria($criteriaErrors); } $changesErrors = $this->sebaksResponse->getChangesErrors(); $redirectTo = $this->sebaksResponse->getRedirectTo(); if (empty($changesErrors) && !empty($redirectTo)) { if (is_array($redirectTo)) { if (!isset($redirectTo['route'])) { throw new \RuntimeException('Missing required parameter route'); } $routeParams = isset($redirectTo['params']) ? $redirectTo['params'] : []; $routeOptions = isset($redirectTo['options']) ? $redirectTo['options'] : []; return $this->redirect()->toRoute($redirectTo['route'], $routeParams, $routeOptions); } else { return $this->redirect()->toRoute($redirectTo); } } if (!empty($changesErrors)) { $result = $this->error->changesErrors($changesErrors); if ($result instanceof Response) { return $result; } } $this->viewModel->setVariables($this->sebaksResponse->toArray()); $e->setResult($this->viewModel); return $this->viewModel; }
/** * {@inheritDoc} */ public function isAuthorized(MvcEvent $event) { $service = $this->getAuthorizationService(); $match = $event->getRouteMatch(); $routeName = $match->getMatchedRouteName(); $action = $match->getParam('action'); if ($service->isAllowed('route/' . $routeName) || $service->isAllowed('route/' . $routeName, $action)) { return true; } $event->setParam('route', $routeName); $errorMessage = sprintf('You are not authorized to access %s', $routeName); throw new UnauthorizedException($errorMessage, 403); }
/** * Event callback to be triggered on dispatch, causes application error triggering * in case of failed authorization check * * @param MvcEvent $event * * @return void */ public function onDispatch(MvcEvent $event) { /* @var $service \BjyAuthorize\Service\Authorize */ $service = $this->serviceLocator->get('BjyAuthorize\\Service\\Authorize'); $match = $event->getRouteMatch(); $controller = $match->getParam('controller'); $action = $match->getParam('action'); $request = $event->getRequest(); $method = $request instanceof HttpRequest ? strtolower($request->getMethod()) : null; $authorized = $service->isAllowed($this->getResourceName($controller)) || $service->isAllowed($this->getResourceName($controller, $action)) || $method && $service->isAllowed($this->getResourceName($controller, $method)); if ($authorized) { return; } $event->setError(static::ERROR); $event->setParam('identity', $service->getIdentity()); $event->setParam('controller', $controller); $event->setParam('action', $action); $errorMessage = sprintf("You are not authorized to access %s:%s", $controller, $action); $event->setParam('exception', new UnAuthorizedException($errorMessage)); /* @var $app \Zend\Mvc\ApplicationInterface */ $app = $event->getTarget(); $app->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event); }
/** * * @param MvcEvent $event */ protected function triggerForbiddenEvent(MvcEvent $event) { $event->setError('route-forbidden'); $event->setParam('exception', new UnauthorizedException('You are forbidden!', 403)); $event->stopPropagation(true); if ($this->hasErrorViewModel()) { $event->setViewModel($this->errorView); } $response = $event->getResponse(); $response->setStatusCode(403); $event->setResponse($response); $application = $event->getApplication(); $eventManager = $application->getEventManager(); $eventManager->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event); }
public function onDispatch(MvcEvent $event) { $app = $event->getTarget(); $aclService = $this->serviceLocator->get('CivAccess\\AclService'); $authService = $this->serviceLocator->get('CivAccess\\AuthService'); $match = $event->getRouteMatch(); $resource = $match->getParam('controller'); $privilege = $match->getParam('action'); // Check access. $role = $authService->hasIdentity() ? (string) $authService->getIdentity()->getId() : 'guest'; $authorized = $aclService->isAllowed($role, $resource, $privilege); // If authorized, no action is required. if ($authorized) { return; } // If not authorized, setup an exception and trigger a dispatch error. $errorMessage = sprintf("You are not authorized to access %s:%s", $resource, $privilege); $event->setError(static::ERROR); $event->setParam('role', $role); $event->setParam('resource', $resource); $event->setParam('privilege', $privilege); $event->setParam('exception', new UnAuthorizedException($errorMessage)); $app->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event); }
/** * Adjust the filter options for Crypt filter adapters * * @param MvcEvent $e */ public function onRoute(MvcEvent $e) { $request = $e->getRequest(); if (!method_exists($request, 'isPut') || !$request->isPut()) { // Not an HTTP request, or not a PUT request; nothing to do return; } $matches = $e->getRouteMatch(); if (!$matches) { // No route matches; nothing to do return; } $controller = $matches->getParam('controller', false); if ($controller !== 'ZF\\Apigility\\Admin\\Controller\\InputFilter') { // Not the InputFilter controller; nothing to do return; } $data = $e->getParam('ZFContentNegotiationParameterData', false); if (!$data) { // No data; nothing to do return; } if ($data instanceof ParameterDataContainer) { $data = $data->getBodyParams(); } if (!isset($data['filters'])) { // No filters passed; nothing to do return; } foreach ($data['filters'] as $key => $filter) { if (!isset($filter['name'])) { continue; } $filter = $filter['name']; $class = new ReflectionClass($filter); // If filter implements CompressionAlgorithmInterface or EncryptionAlgorithmInterface, // we change the filter's name to the parent, and we add the adapter param to filter's name. if ($class->implementsInterface('Zend\\Filter\\Compress\\CompressionAlgorithmInterface') || $class->implementsInterface('Zend\\Filter\\Encrypt\\EncryptionAlgorithmInterface')) { $name = substr($filter, 0, strrpos($filter, '\\')); $adapter = substr($filter, strrpos($filter, '\\') + 1); $data['filters'][$key]['name'] = $name; $data['filters'][$key]['options']['adapter'] = $adapter; } } // Inject altered data back into event $e->setParam('ZFContentNegotiationParameterData', $data); return true; }
protected function processResult(MvcEvent $event, $return) { if ($return instanceof ApiProblem) { return new ApiProblemResponse($return); } if (!$return instanceof HalEntity && !$return instanceof HalCollection) { return $return; } // Set the fallback content negotiation to use HalJson. $event->setParam('ZFContentNegotiationFallback', 'HalJson'); // Use content negotiation for creating the view model $viewModel = new ContentNegotiationViewModel(array('payload' => $return)); $viewModel->setTerminal(true); $event->setResult($viewModel); return $viewModel; }
/** * @param MvcEvent $event */ public function checkDeactivatedUser(MvcEvent $event) { $routeName = $event->getRouteMatch()->getMatchedRouteName(); $allowedRoutes = ['auth-logout']; // do nothing for allowed routes if (in_array($routeName, $allowedRoutes)) { return; } $auth = $event->getApplication()->getServiceManager()->get('AuthenticationService'); // check for inactive user if ($auth->hasIdentity() && !$auth->getUser()->isActive()) { // set event error & throw dispach error $event->setError('User inactive'); $event->setParam('exception', new UserDeactivatedException()); return $event->getTarget()->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event)->last(); } }