Пример #1
0
 /**
  * @param array $params
  * @return string
  * @throws Exception\RenderingException if current result is a routing
  *     failure.
  */
 private function generateUriFromResult(array $params)
 {
     if ($this->result->isFailure()) {
         throw new Exception\RenderingException('Attempting to use matched result when routing failed; aborting');
     }
     $name = $this->result->getMatchedRouteName();
     $params = array_merge($this->result->getMatchedParams(), $params);
     return $this->router->generateUri($name, $params);
 }
 protected function setUp()
 {
     $this->config = [['name' => 'agreements', 'path' => '/agreements[/{agreement_id}]', 'middleware' => AgreementAction::class, 'allowed_methods' => ['GET', 'DELETE', 'PATCH', 'PUT', 'POST'], 'options' => []]];
     $router = $this->getMock(FastRouteRouter::class);
     $router->expects($this->any())->method('match')->willReturn(RouteResult::fromRouteMatch($this->config[0]['path'], function () {
     }, ['agreement_id' => '1234']));
     $this->router = $router;
 }
 public function setUp()
 {
     $routeAssemblerProphezy = $this->prophesize(RouteAssembler::class);
     $routeAssemblerProphezy->assembleUrl('home', true)->willReturn('/foo/bar');
     $routeAssemblerProphezy->assembleUrl(null, ['lang' => 'es'])->willReturn('/es');
     $routeAssemblerProphezy->assembleUrl(null, ['lang' => 'en'])->willReturn('/en');
     $routeAssemblerProphezy->getCurrentRouteResult()->willReturn(RouteResult::fromRouteMatch('home', 'HelloWorld', []));
     $this->extension = new NavigationExtension(Translator::factory([]), $routeAssemblerProphezy->reveal(), ['menu' => [['route' => 'home', 'icon' => 'house', 'label' => 'Home'], ['uri' => 'http://foo.com', 'target' => true, 'label' => 'Blog', 'icon' => 'book']], 'lang_menu' => [['label' => 'Español', 'class' => 'es', 'params' => ['lang' => 'es']], ['label' => 'English', 'class' => 'en', 'params' => ['lang' => 'en']]]]);
 }
 public function setUp()
 {
     $this->request = new ServerRequest();
     $this->prophecyRouter = $this->prophesize(RouterInterface::class);
     $this->prophecyRouter->match($this->request)->willReturn(RouteResult::fromRouteMatch('home', function ($req, $resp) {
         return $resp;
     }, $this->params));
     $this->assembler = new RouteAssembler($this->prophecyRouter->reveal(), $this->request);
 }
 /**
  * Merge route result params and provided parameters.
  *
  * If the route result represents a routing failure, returns the params
  * verbatim.
  *
  * If the route result does not represent the same route name requested,
  * returns the params verbatim.
  *
  * Otherwise, merges the route result params with those provided at
  * invocation, with the latter having precedence.
  *
  * @param string $route Route name.
  * @param array $params Parameters provided at invocation.
  * @return array
  */
 private function mergeParams($route, array $params)
 {
     if ($this->result->isFailure()) {
         return $params;
     }
     if ($this->result->getMatchedRouteName() !== $route) {
         return $params;
     }
     return array_merge($this->result->getMatchedParams(), $params);
 }
 public function setUp()
 {
     $this->request = new ServerRequest();
     $router = $this->prophesize(RouterInterface::class);
     $router->match($this->request)->willReturn(RouteResult::fromRouteMatch('home', function ($req, $resp) {
         return $resp;
     }, ['lang' => 'es']));
     $this->translator = Translator::factory(['locale' => 'en']);
     $this->middleware = new LanguageMiddleware($this->translator, $router->reveal());
 }
Пример #7
0
 /**
  * {@inheritdoc}
  */
 public function match(Request $request)
 {
     $this->router->handle($request->getUri()->getPath());
     if (!$this->router->wasMatched()) {
         // TODO Is it worth to validate, if route matches but the method is incompatible?
         return RouteResult::fromRouteFailure();
     }
     $matchedRoute = $this->router->getMatchedRoute();
     return RouteResult::fromRouteMatch($matchedRoute->getName(), $this->router->getNamespaceName(), $this->collectParams($matchedRoute));
 }
 public function testWithNoCacheResponseIsCached()
 {
     $response = new Response();
     $next = function ($req, $resp) {
         return $resp;
     };
     $this->router->match($this->request)->willReturn(RouteResult::fromRouteMatch('home', $next, ['cacheable' => true]));
     $this->assertFalse($this->cache->contains('/foo'));
     $this->middleware->__invoke($this->request, $response, $next);
     $this->assertTrue($this->cache->contains('/foo'));
 }
Пример #9
0
 /**
  * {@inheritdoc}
  */
 public function match(ServerRequestInterface $request)
 {
     $this->injectRoutes();
     $matchResult = $this->router->match($request);
     if ($matchResult instanceof SuccessfulMatch) {
         return RouteResult::fromRouteMatch($matchResult->getRouteName(), $matchResult->getParam('middleware'), $matchResult->getParams());
     }
     if ($matchResult instanceof MethodNotAllowed) {
         return RouteResult::fromRouteFailure($matchResult->getAllowedMethods());
     }
     return RouteResult::fromRouteFailure();
 }
Пример #10
0
 /**
  * Match a request against the known routes.
  *
  * Implementations will aggregate required information from the provided
  * request instance, and pass them to the underlying router implementation;
  * when done, they will then marshal a `RouteResult` instance indicating
  * the results of the matching operation and return it to the caller.
  *
  * @param  Request $request
  * @return RouteResult
  */
 public function match(Request $request)
 {
     $this->_forbidRouteAdd = true;
     $params = $request->getServerParams();
     $path = $params['PATH_INFO'];
     // get the matched route
     $matchedRoute = $this->_matchPathToRoutePath($path);
     // check if route exists
     if ($matchedRoute instanceof Route) {
         return RouteResult::fromRouteMatch($matchedRoute->getName(), $matchedRoute->getMiddleware(), $params);
     }
     return RouteResult::fromRouteFailure();
 }
Пример #11
0
 /**
  * @param  Request $request
  * @return RouteResult
  */
 public function match(Request $request)
 {
     $matchedRoutes = $this->router->getMatchedRoutes($request->getMethod(), $request->getUri()->getPath());
     if (count($matchedRoutes) === 0) {
         return RouteResult::fromRouteFailure();
     }
     /** @var \Slim\Route $matchedRoute */
     $matchedRoute = array_shift($matchedRoutes);
     $params = $matchedRoute->getParams();
     // Get the middleware from the route params and remove it
     $middleware = $params['middleware'];
     unset($params['middleware']);
     return RouteResult::fromRouteMatch($matchedRoute->getName(), $middleware, $params);
 }
 /**
  * Test throwing of the exception
  * @covers StdLib\Validator\ValidationMiddleware::__invoke
  */
 public function testInvokeMiddlewareThrowsException()
 {
     $this->setExpectedException(ValidationFailedException::class);
     $router = $this->getMock(FastRouteRouter::class);
     $this->applyValidationConfig();
     $router->expects($this->any())->method('match')->willReturn(RouteResult::fromRouteMatch($this->config[0]['path'], function () {
     }, []));
     $optionExtractor = new OptionsExtractor($this->config, $router);
     $validator = new Validator($optionExtractor, $router, $this->getEntityManagerMock());
     $middleware = new ValidationMiddleware($validator);
     $request = $this->createRequest(static::$urlInvalid);
     $response = $this->getMock(ResponseInterface::class);
     $closure = function () {
     };
     $middleware->__invoke($request, $response, $closure);
 }
 /**
  * @test
  */
 public function provideCorrectTokenUpdatesExpirationAndFallbacksToNextMiddleware()
 {
     $authToken = 'ABC-abc';
     $request = ServerRequestFactory::fromGlobals()->withAttribute(RouteResult::class, RouteResult::fromRouteMatch('bar', 'foo', []))->withHeader(CheckAuthenticationMiddleware::AUTHORIZATION_HEADER, 'bearer ' . $authToken);
     $this->jwtService->verify($authToken)->willReturn(true)->shouldBeCalledTimes(1);
     $this->jwtService->refresh($authToken)->willReturn($authToken)->shouldBeCalledTimes(1);
     $isCalled = false;
     $this->assertFalse($isCalled);
     $this->middleware->__invoke($request, new Response(), function ($req, $resp) use(&$isCalled) {
         $isCalled = true;
         return $resp;
     });
     $this->assertTrue($isCalled);
 }
 public function testGetCurrentRouteResult()
 {
     $this->routeAssemblerProphezy->getCurrentRouteResult()->willReturn(RouteResult::fromRouteMatch('home', 'HelloWorld', []));
     $result = $this->extension->getCurrentRouteResult();
     $this->assertInstanceOf(RouteResult::class, $result);
 }
 public function testRoutingSuccessResultingInContainerExceptionReRaisesException()
 {
     $request = new ServerRequest();
     $response = new Response();
     $result = RouteResult::fromRouteMatch('/foo', 'TestAsset\\Middleware', []);
     $this->router->match($request)->willReturn($result);
     $this->container->has('TestAsset\\Middleware')->willReturn(true);
     $this->container->get('TestAsset\\Middleware')->willThrow(new TestAsset\ContainerException());
     $app = $this->getApplication();
     $next = function ($request, $response) {
         $this->fail('Should not enter $next');
     };
     $this->setExpectedException('Zend\\Expressive\\Exception\\InvalidMiddlewareException', 'retrieve');
     $app->routeMiddleware($request, $response, $next);
 }
Пример #16
0
 /**
  * @group 64
  */
 public function testInvocationWillPipeRoutingMiddlewareIfNotAlreadyPiped()
 {
     $request = new Request([], [], 'http://example.com/');
     $response = $this->prophesize('Psr\\Http\\Message\\ResponseInterface');
     $middleware = function ($req, $res, $next = null) {
         return $res;
     };
     $this->router->match($request)->willReturn(RouteResult::fromRouteMatch('foo', 'foo', []));
     $container = $this->prophesize(ContainerInterface::class);
     $container->has('foo')->willReturn(true);
     $container->get('foo')->willReturn($middleware);
     $app = new Application($this->router->reveal(), $container->reveal());
     $pipeline = $this->prophesize('SplQueue');
     // Test that the route middleware is enqueued
     $pipeline->enqueue(Argument::that(function ($route) use($app) {
         if (!$route instanceof StratigilityRoute) {
             return false;
         }
         if ($route->path !== '/') {
             return false;
         }
         return $route->handler === [$app, 'routeMiddleware'];
     }))->shouldBeCalled();
     // Prevent dequeueing
     $pipeline->isEmpty()->willReturn(true);
     $r = new ReflectionProperty($app, 'pipeline');
     $r->setAccessible(true);
     $r->setValue($app, $pipeline->reveal());
     $app($request, $response->reveal(), $middleware);
 }
 public function testInvokeRedirectResponseToSameUri()
 {
     $request = $this->prophesize(ServerRequest::class);
     $response = new RedirectResponse('/');
     $next = function ($req, $res, $err = null) use($response) {
         return $response;
     };
     $routeResult = RouteResult::fromRouteMatch('home', function () {
     }, []);
     $uri = $this->prophesize(Uri::class);
     $uri->getPath()->willReturn('/')->shouldBeCalled();
     $request->getUri()->willReturn($uri)->shouldBeCalled();
     $uri->getPath()->willReturn('/')->shouldBeCalled();
     $request->withUri(Argument::type(Uri::class))->willReturn($request)->shouldBeCalled();
     $request->getUri()->willReturn($uri)->shouldBeCalled();
     $this->router->match($request)->willReturn($routeResult)->shouldBeCalled();
     $response = $this->middleware->__invoke($request->reveal(), $response, $next);
 }
 /**
  * Marshals a route result based on the results of matching and the current HTTP method.
  *
  * @param array $result
  * @param string $method
  * @return RouteResult
  */
 private function marshalMatchedRoute(array $result, $method)
 {
     $path = $result[1];
     $route = array_reduce($this->routes, function ($matched, $route) use($path, $method) {
         if ($matched) {
             return $matched;
         }
         if ($path !== $route->getPath()) {
             return $matched;
         }
         if (!$route->allowsMethod($method)) {
             return $matched;
         }
         return $route;
     }, false);
     if (false === $route) {
         // This likely should never occur, but is present for completeness.
         return RouteResult::fromRouteFailure();
     }
     return RouteResult::fromRouteMatch($route->getName(), $route->getMiddleware(), $result[2]);
 }
 /**
  * Marshals a route result based on the results of matching and the current HTTP method.
  *
  * @param array $result
  * @param string $method
  * @return RouteResult
  */
 private function marshalMatchedRoute(array $result, $method)
 {
     $path = $result[1];
     $middleware = array_reduce($this->routes, function ($middleware, $route) use($path, $method) {
         if ($middleware) {
             return $middleware;
         }
         if ($path !== $route->getPath()) {
             return $middleware;
         }
         if (!$route->allowsMethod($method)) {
             return $middleware;
         }
         return $route->getMiddleware();
     }, false);
     return RouteResult::fromRouteMatch($path, $middleware, $result[2]);
 }
Пример #20
0
 /**
  * @test
  */
 public function responseWithoutErrorReturnsStatus500()
 {
     $response = $this->errorHandler->__invoke(ServerRequestFactory::fromGlobals()->withAttribute(RouteResult::class, RouteResult::fromRouteMatch('foo', 'bar', [])), (new Response())->withStatus(200), 'Some error');
     $this->assertInstanceOf(Response\JsonResponse::class, $response);
     $this->assertEquals(500, $response->getStatusCode());
 }
Пример #21
0
 /**
  * Marshals a route result based on the matched AuraRoute.
  *
  * Note: no actual typehint is provided here; Aura Route instances provide
  * property overloading, which is difficult to mock for testing; we simply
  * assume an object at this point.
  *
  * @param AuraRoute $route
  * @return RouteResult
  */
 private function marshalMatchedRoute($route)
 {
     return RouteResult::fromRouteMatch($route->name, $route->params['action'], $route->params);
 }
 public function testValidateValidationAppliedWithErrors()
 {
     /**
      * Apply the validation to the config
      */
     $this->applyValidationConfig();
     $router = $this->getMock(FastRouteRouter::class);
     $router->expects($this->any())->method('match')->willReturn(RouteResult::fromRouteMatch($this->config[0]['path'], function () {
     }, []));
     $optionExtractor = new OptionsExtractor($this->config, $router);
     $validator = new Validator($optionExtractor, $router, $this->getEntityManagerMock());
     /**
      * @var ValidationResultInterface $validationResult
      */
     $validationResult = $validator->validate($this->createRequest(static::$urlInvalid));
     /**
      * Should not be valid
      */
     $this->assertInstanceOf(ValidationResultInterface::class, $validationResult);
     $this->assertFalse($validationResult->valid());
     $this->assertTrue($validationResult->notValid());
     $this->assertNotEmpty($validationResult->getMessages());
     $this->assertEmpty($validationResult->getData());
     $this->assertGreaterThan(0, count($validationResult->getMessages()));
     $this->assertContains('Please provide an id for the agreement', $validationResult->getMessages());
 }
Пример #23
0
 /**
  * Create a succesful RouteResult from the given RouteMatch.
  *
  * @param RouteMatch $match
  * @return RouteResult
  */
 private function marshalSuccessResultFromRouteMatch(RouteMatch $match)
 {
     $params = $match->getParams();
     $middleware = isset($params['middleware']) ? $params['middleware'] : $this->getMiddlewareFromRoute($match->getMatchedRouteName());
     return RouteResult::fromRouteMatch($match->getMatchedRouteName(), $middleware, $params);
 }
Пример #24
0
 /**
  * Create a successful RouteResult from the given RouteMatch.
  *
  * @param RouteMatch $match
  * @return RouteResult
  */
 private function marshalSuccessResultFromRouteMatch(RouteMatch $match)
 {
     $params = $match->getParams();
     if (array_key_exists(self::METHOD_NOT_ALLOWED_ROUTE, $params)) {
         return RouteResult::fromRouteFailure($this->allowedMethodsByPath[$params[self::METHOD_NOT_ALLOWED_ROUTE]]);
     }
     return RouteResult::fromRouteMatch($this->getMatchedRouteName($match->getMatchedRouteName()), $params['middleware'], $params);
 }
Пример #25
0
 public function testComposedEmitterIsCalledByRun()
 {
     $routeResult = RouteResult::fromRouteFailure();
     $this->router->match()->willReturn($routeResult);
     $finalResponse = $this->prophesize('Psr\\Http\\Message\\ResponseInterface')->reveal();
     $finalHandler = function ($req, $res, $err = null) use($finalResponse) {
         return $finalResponse;
     };
     $emitter = $this->prophesize('Zend\\Diactoros\\Response\\EmitterInterface');
     $emitter->emit(Argument::type('Psr\\Http\\Message\\ResponseInterface'))->shouldBeCalled();
     $app = new Application($this->router->reveal(), null, $finalHandler, $emitter->reveal());
     $request = new Request([], [], 'http://example.com/');
     $response = $this->prophesize('Psr\\Http\\Message\\ResponseInterface');
     $app->run($request, $response->reveal());
 }
 public function testGetCurrentRouteName()
 {
     $this->routeAssemblerProphezy->getCurrentRouteResult()->willReturn(RouteResult::fromRouteMatch('foo', '', []));
     $this->assertEquals('foo', $this->extension->getCurrentRouteName());
 }