Inheritance: extends Zend\Stratigility\MiddlewarePipe, implements Zend\Expressive\Router\RouteResultSubjectInterface, use trait MarshalMiddlewareTrait
コード例 #1
0
 public function up(Application $app, EntityManager $em)
 {
     $profileId = DemoAccountFixture::getSecondAccount()->getCurrentProfile()->getId();
     $service = $app->getContainer()->get(ProfileCommunitiesService::class);
     /** @var ProfileCommunitiesService $service */
     self::$bookmarks = [1 => $service->joinToCommunity($profileId, SampleCommunitiesFixture::getCommunity(1)->getSID()), 2 => $service->joinToCommunity($profileId, SampleCommunitiesFixture::getCommunity(2)->getSID()), 3 => $service->joinToCommunity($profileId, SampleCommunitiesFixture::getCommunity(3)->getSID()), 4 => $service->joinToCommunity($profileId, SampleCommunitiesFixture::getCommunity(4)->getSID()), 5 => $service->joinToCommunity($profileId, SampleCommunitiesFixture::getCommunity(5)->getSID())];
 }
コード例 #2
0
 public function up(Application $app, EntityManager $em)
 {
     $accountService = $app->getContainer()->get(AccountService::class);
     /** @var AccountService $accountService */
     $appAccessAccountService = $app->getContainer()->get(AccountAppAccessService::class);
     /** @var AccountAppAccessService $account */
     $all = $accountService->createAccount('*****@*****.**', self::ACCOUNT_PASSWORD);
     $admin = $accountService->createAccount('*****@*****.**', self::ACCOUNT_PASSWORD);
     $reports = $accountService->createAccount('*****@*****.**', self::ACCOUNT_PASSWORD);
     $feedback = $accountService->createAccount('*****@*****.**', self::ACCOUNT_PASSWORD);
     $ac_all = new AccountAppAccess($all);
     $ac_all->allowAdmin();
     $ac_all->allowFeedback();
     $ac_all->allowReports();
     $ac_admin = new AccountAppAccess($admin);
     $ac_admin->allowAdmin();
     $ac_reports = new AccountAppAccess($reports);
     $ac_reports->allowReports();
     $ac_feedback = new AccountAppAccess($feedback);
     $ac_feedback->allowFeedback();
     $appAccessAccountService->applyAppAccess($ac_all);
     $appAccessAccountService->applyAppAccess($ac_admin);
     $appAccessAccountService->applyAppAccess($ac_reports);
     $appAccessAccountService->applyAppAccess($ac_feedback);
     self::$accounts = ['all' => $all, 'admin' => $admin, 'reports' => $reports, 'feedback' => $feedback];
 }
コード例 #3
0
 /**
  * @param Request $request
  *
  * @return Response
  * @throws \Exception
  */
 public function doRequest($request)
 {
     $inputStream = fopen('php://memory', 'r+');
     $content = $request->getContent();
     if ($content !== null) {
         fwrite($inputStream, $content);
         rewind($inputStream);
     }
     $queryParams = [];
     $postParams = [];
     $queryString = parse_url($request->getUri(), PHP_URL_QUERY);
     if ($queryString != '') {
         parse_str($queryString, $queryParams);
     }
     if ($request->getMethod() !== 'GET') {
         $postParams = $request->getParameters();
     }
     $serverParams = $request->getServer();
     if (!isset($serverParams['SCRIPT_NAME'])) {
         //required by WhoopsErrorHandler
         $serverParams['SCRIPT_NAME'] = 'Codeception';
     }
     $zendRequest = new ServerRequest($serverParams, $this->convertFiles($request->getFiles()), $request->getUri(), $request->getMethod(), $inputStream, $this->extractHeaders($request));
     $zendRequest = $zendRequest->withCookieParams($request->getCookies())->withQueryParams($queryParams)->withParsedBody($postParams);
     $cwd = getcwd();
     chdir(codecept_root_dir());
     $this->application->run($zendRequest);
     chdir($cwd);
     $this->request = $zendRequest;
     $response = $this->responseCollector->getResponse();
     $this->responseCollector->clearResponse();
     return new Response($response->getBody(), $response->getStatusCode(), $response->getHeaders());
 }
コード例 #4
0
 public function up(Application $app, EntityManager $em)
 {
     $postService = $app->getContainer()->get(PostService::class);
     /** @var PostService $postService */
     for ($i = 0; $i < 10; $i++) {
         self::$posts[$i] = $postService->createPost(new CreatePostParameters(DefaultPostType::CODE_INT, DemoAccountFixture::getAccount()->getCurrentProfile()->getId(), SampleCollectionsFixture::getProfileCollection(1)->getId(), 'Demo Post Content', []));
     }
 }
コード例 #5
0
 public function testResourceIdRelationIdRequest()
 {
     $request = $this->request->withUri(new Uri('http://localhost/api/ping/1/comments/1'))->withMethod('GET');
     $response = $this->app->__invoke($request, new Response());
     $data = json_decode((string) $response->getBody(), true);
     $this->assertEquals(200, $response->getStatusCode());
     $this->assertArrayHasKey('ack', $data);
 }
コード例 #6
0
 public function up(Application $app, EntityManager $em)
 {
     $profile = DemoProfileFixture::getProfile();
     $collectionService = $app->getContainer()->get(CollectionService::class);
     /** @var CollectionService $collectionService */
     self::$profileCollections = [1 => $collectionService->createCollection(new CreateCollectionParameters(sprintf('profile:%s', $profile->getId()), 'Profile Collection 1', 'My Profile Collection 1', [SampleThemesFixture::getTheme(1)->getId()])), 2 => $collectionService->createCollection(new CreateCollectionParameters(sprintf('profile:%s', $profile->getId()), 'Profile Collection 1', 'My Profile Collection 2', [SampleThemesFixture::getTheme(2)->getId()])), 3 => $collectionService->createCollection(new CreateCollectionParameters(sprintf('profile:%s', $profile->getId()), 'Profile Collection 1', 'My Profile Collection 3', [SampleThemesFixture::getTheme(3)->getId()])), 4 => $collectionService->createCollection(new CreateCollectionParameters(sprintf('profile:%s', $profile->getId()), 'Profile Collection 1', 'My Profile Collection 4', [SampleThemesFixture::getTheme(4)->getId()])), 5 => $collectionService->createCollection(new CreateCollectionParameters(sprintf('profile:%s', $profile->getId()), 'Profile Collection 1', 'My Profile Collection 5', [SampleThemesFixture::getTheme(5)->getId()]))];
     self::$communityCollections = [1 => $collectionService->createCollection(new CreateCollectionParameters(sprintf('community:%s', SampleCommunitiesFixture::getCommunity(1)->getId()), 'Community Collection 1', 'My Community Collection 1', [SampleThemesFixture::getTheme(1)->getId()])), 2 => $collectionService->createCollection(new CreateCollectionParameters(sprintf('community:%s', SampleCommunitiesFixture::getCommunity(2)->getId()), 'Community Collection 2', 'My Community Collection 2', [SampleThemesFixture::getTheme(2)->getId()])), 3 => $collectionService->createCollection(new CreateCollectionParameters(sprintf('community:%s', SampleCommunitiesFixture::getCommunity(3)->getId()), 'Community Collection 3', 'My Community Collection 3', [SampleThemesFixture::getTheme(3)->getId()])), 4 => $collectionService->createCollection(new CreateCollectionParameters(sprintf('community:%s', SampleCommunitiesFixture::getCommunity(4)->getId()), 'Community Collection 4', 'My Community Collection 4', [SampleThemesFixture::getTheme(4)->getId()])), 5 => $collectionService->createCollection(new CreateCollectionParameters(sprintf('community:%s', SampleCommunitiesFixture::getCommunity(5)->getId()), 'Community Collection 5', 'My Community Collection 5', [SampleThemesFixture::getTheme(5)->getId()]))];
 }
コード例 #7
0
 public function testIntegrationExample()
 {
     $request = new ServerRequest([], [], 'https://example.com/', 'GET');
     $response = $this->app->__invoke($request, new Response());
     $body = (string) $response->getBody();
     $this->assertEquals(200, $response->getStatusCode());
     $this->assertContains('text/html', $response->getHeaderLine('Content-Type'));
     $this->assertContains('<title>Home</title>', $body);
 }
コード例 #8
0
 public function testInjectedFinalHandlerCanEmitA404WhenNoMiddlewareMatches()
 {
     $finalHandler = new TemplatedErrorHandler();
     $app = new Application(new FastRouteRouter(), null, $finalHandler, $this->getEmitter());
     $request = new ServerRequest([], [], 'https://example.com/foo', 'GET');
     $response = new Response();
     $app->run($request, $response);
     $this->assertInstanceOf(ResponseInterface::class, $this->response);
     $this->assertEquals(404, $this->response->getStatusCode());
 }
コード例 #9
0
ファイル: ZendExpressive.php プロジェクト: Marfuz/c4t_test
 private function initResponseCollector()
 {
     /**
      * @var Zend\Expressive\Emitter\EmitterStack
      */
     $emitterStack = $this->application->getEmitter();
     while (!$emitterStack->isEmpty()) {
         $emitterStack->pop();
     }
     $this->responseCollector = new ZendExpressiveConnector\ResponseCollector();
     $emitterStack->unshift($this->responseCollector);
 }
コード例 #10
0
 public function up(Application $app, EntityManager $em)
 {
     $accountService = $app->getContainer()->get(AccountService::class);
     /** @var AccountService $accountService */
     $currentAccountService = $app->getContainer()->get(CurrentAccountService::class);
     /** @var CurrentAccountService $currentAccountService */
     $account = $accountService->createAccount(self::ACCOUNT_EMAIL, self::ACCOUNT_PASSWORD);
     $accountSecond = $accountService->createAccount(self::ACCOUNT_EMAIL_SECOND, self::ACCOUNT_PASSWORD);
     $currentAccountService->signInWithAccount($account);
     self::$account = $account;
     self::$secondAccount = $accountSecond;
 }
コード例 #11
0
 public function up(Application $app, EntityManager $em)
 {
     $subscribeService = $app->getContainer()->get(SubscribeService::class);
     $profile = DemoAccountFixture::getAccount()->getCurrentProfile();
     $theme = SampleThemesFixture::getTheme(1);
     self::$subscribes['theme'][0] = $subscribeService->subscribeTheme($profile, $theme);
     $subscribeProfile = DemoProfileFixture::getProfile();
     self::$subscribes['profile'][0] = $subscribeService->subscribeProfile($profile, $subscribeProfile);
     $collections = SampleCollectionsFixture::getCommunityCollections();
     $collection = array_shift($collections);
     self::$subscribes['collection'][0] = $subscribeService->subscribeCollection($profile, $collection);
     $community = SampleCommunitiesFixture::getCommunity(1);
     self::$subscribes['community'][0] = $subscribeService->subscribeCommunity($profile, $community);
 }
コード例 #12
0
 /**
  * @param string     $method
  * @param string     $uri
  * @param array|null $parameters
  * @param array|null $sessionData
  *
  * @return ResponseInterface
  *
  * @throws \BadMethodCallException
  * @throws \Interop\Container\Exception\NotFoundException
  * @throws \Interop\Container\Exception\ContainerException
  * @throws \InvalidArgumentException
  */
 protected function handleRequest(string $method, string $uri, array $parameters = null, array $sessionData = null) : ResponseInterface
 {
     // Create request
     $request = (new ServerRequest())->withMethod($method)->withUri(new Uri($uri));
     // Set post parameters
     if ($parameters !== null) {
         $request = $request->withParsedBody($parameters);
     }
     // Set PSR-7 session data
     if ($sessionData !== null) {
         // Get session middleware
         $sessionMiddleWare = self::$container->get(SessionMiddleware::class);
         // Get signer
         $signerReflection = new \ReflectionProperty($sessionMiddleWare, 'signer');
         $signerReflection->setAccessible(true);
         $signer = $signerReflection->getValue($sessionMiddleWare);
         // Get signature key
         $signatureKeyReflection = new \ReflectionProperty($sessionMiddleWare, 'signatureKey');
         $signatureKeyReflection->setAccessible(true);
         $signatureKey = $signatureKeyReflection->getValue($sessionMiddleWare);
         // Set session data as a cookie
         $request = $request->withCookieParams([SessionMiddleware::DEFAULT_COOKIE => (string) (new Builder())->setIssuedAt((new \DateTime('-30 second'))->getTimestamp())->setExpiration((new \DateTime('+30 second'))->getTimestamp())->set(SessionMiddleware::SESSION_CLAIM, DefaultSessionData::fromTokenData($sessionData))->sign($signer, $signatureKey)->getToken()]);
     }
     // Invoke the request
     return self::$app->__invoke($request, new Response());
 }
コード例 #13
0
 private function setupEvents(Application $app, EventEmitter $emitter, $eventConfigFile)
 {
     if (file_exists($eventConfigFile)) {
         $callback = (require $eventConfigFile);
         if (!is_callable($callback)) {
             throw new \Exception(sprintf('Event config `%s` should returns a Callable with EventEmitter and Container argument', $eventConfigFile));
         }
         $result = $callback($emitter, $app->getContainer());
         if (is_array($result) && count($result)) {
             Chain::create($result)->map(function (string $script) use($app) {
                 return $app->getContainer()->get($script);
             })->map(function (EventsBootstrapInterface $script) use($emitter) {
                 $script->up($emitter);
             });
         }
     }
 }
コード例 #14
0
 public function testDeleteUnknownUser()
 {
     $uuid = 'badfdcad-1ad5-42fb-8da6-4a2db08c6941';
     $request = $this->request->withUri(new Uri(sprintf('http://localhost/api/users/%s', $uuid)))->withMethod('DELETE');
     $response = $this->app->__invoke($request, new Response());
     $data = json_decode((string) $response->getBody(), true);
     $this->assertEquals(404, $response->getStatusCode());
     $this->assertEquals('application/json', $response->getHeaderLine('Content-Type'));
     $this->assertArrayHasKey('errors', $data);
 }
コード例 #15
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());
 }
コード例 #16
0
 public function up(Application $app, EntityManager $em)
 {
     $themeService = $app->getContainer()->get(ThemeService::class);
     /** @var ThemeService $themeService */
     self::$themes = [1 => $themeService->createTheme(new CreateThemeParameters('Theme 1', 'My Theme 1')), 2 => $themeService->createTheme(new CreateThemeParameters('Theme 2', 'My Theme 2')), 3 => $themeService->createTheme(new CreateThemeParameters('Theme 3', 'My Theme 3')), 4 => $themeService->createTheme(new CreateThemeParameters('Theme 4', 'My Theme 4')), 5 => $themeService->createTheme(new CreateThemeParameters('Theme 5', 'My Theme 5'))];
 }
コード例 #17
0
 /**
  * Возвращает ссылку на контейнер текущего приложения
  * Используйте для получение сервисов/репозиторие/etc
  * @return Container
  */
 protected function container() : Container
 {
     return self::$app->getContainer();
 }
コード例 #18
0
 /**
  * Given a collection of middleware specifications, pipe them to the application.
  *
  * @param array $collection
  * @param Application $app
  * @param ContainerInterface $container
  * @throws Exception\InvalidMiddlewareException for invalid middleware.
  */
 private function injectMiddleware(array $collection, Application $app, ContainerInterface $container)
 {
     foreach ($collection as $spec) {
         if (!array_key_exists('middleware', $spec)) {
             continue;
         }
         $middleware = $spec['middleware'];
         if (!is_callable($middleware)) {
             $middleware = $this->marshalMiddleware($middleware, $container);
         }
         $path = isset($spec['path']) ? $spec['path'] : '/';
         $app->pipe($path, $middleware);
     }
 }
コード例 #19
0
 /**
  * Inject routes from configuration, if any.
  *
  * @param array $routes Route definitions
  * @param Application $app
  */
 private function injectRoutes(array $routes, Application $app)
 {
     foreach ($routes as $spec) {
         if (!isset($spec['path']) || !isset($spec['middleware'])) {
             continue;
         }
         if (isset($spec['allowed_methods'])) {
             $methods = $spec['allowed_methods'];
             if (!is_array($methods)) {
                 throw new ContainerInvalidArgumentException(sprintf('Allowed HTTP methods for a route must be in form of an array; received "%s"', gettype($methods)));
             }
         } else {
             $methods = Route::HTTP_METHOD_ANY;
         }
         $name = isset($spec['name']) ? $spec['name'] : null;
         $route = new Route($spec['path'], $spec['middleware'], $methods, $name);
         if (isset($spec['options'])) {
             $options = $spec['options'];
             if (!is_array($options)) {
                 throw new ContainerInvalidArgumentException(sprintf('Route options must be an array; received "%s"', gettype($options)));
             }
             $route->setOptions($options);
         }
         $app->route($route);
     }
 }
コード例 #20
0
 /**
  * @dataProvider routerAdapters
  * @group 74
  */
 public function testWithOnlyRootPathRouteDefinedRoutingToSubPathsShouldReturn404($adapter)
 {
     $app = new Application(new $adapter());
     $app->route('/', function ($req, $res, $next) {
         $res->getBody()->write('Middleware');
         return $res;
     }, ['GET']);
     $next = function ($req, $res) {
         return $res;
     };
     $request = new ServerRequest(['REQUEST_METHOD' => 'GET'], [], '/foo', 'GET');
     $response = new Response();
     $result = $app->routeMiddleware($request, $response, $next);
     $this->assertInstanceOf(Response::class, $result);
     $this->assertNotEquals(405, $result->getStatusCode());
 }
コード例 #21
0
 /**
  * @group lazy-piping
  */
 public function testAllowsPipingErrorMiddlewareAsServiceNameWithPath()
 {
     $middleware = function ($error, $req, $res, $next) {
         return 'invoked';
     };
     $container = $this->prophesize(ContainerInterface::class);
     $container->has('foo')->willReturn(true);
     $container->get('foo')->willReturn($middleware);
     $app = new Application($this->router->reveal(), $container->reveal());
     $app->pipeErrorHandler('/foo', 'foo');
     $r = new ReflectionProperty($app, 'pipeline');
     $r->setAccessible(true);
     $pipeline = $r->getValue($app);
     $route = $pipeline->dequeue();
     $this->assertInstanceOf('Zend\\Stratigility\\Route', $route);
     $handler = $route->handler;
     $this->assertEquals('invoked', $handler('foo', 'bar', 'baz', 'bat'));
 }
コード例 #22
0
 /**
  * Inject routes from configuration, if any.
  *
  * @param Application $app
  * @param ContainerInterface $container
  */
 private function injectRoutes(Application $app, ContainerInterface $container)
 {
     $config = $container->has('config') ? $container->get('config') : [];
     if (!isset($config['routes'])) {
         $app->pipeRoutingMiddleware();
         return;
     }
     foreach ($config['routes'] as $spec) {
         if (!isset($spec['path']) || !isset($spec['middleware'])) {
             continue;
         }
         $methods = isset($spec['allowed_methods']) && is_array($spec['allowed_methods']) ? $spec['allowed_methods'] : null;
         $name = isset($spec['name']) ? $spec['name'] : null;
         $route = $app->route($spec['path'], $spec['middleware'], $methods, $name);
         if (isset($spec['options']) && is_array($spec['options'])) {
             $route->setOptions($spec['options']);
         }
     }
 }
コード例 #23
0
 public function up(Application $app, EntityManager $em)
 {
     $communityService = $app->getContainer()->get(CommunityService::class);
     /** @var CommunityService $communityService */
     self::$communities = [1 => $communityService->createCommunity(new CreateCommunityParameters('Community 1', 'My Community 1', SampleThemesFixture::getTheme(1)->getId())), 2 => $communityService->createCommunity(new CreateCommunityParameters('Community 2', 'My Community 2', SampleThemesFixture::getTheme(2)->getId())), 3 => $communityService->createCommunity(new CreateCommunityParameters('Community 3', 'My Community 3', SampleThemesFixture::getTheme(3)->getId())), 4 => $communityService->createCommunity(new CreateCommunityParameters('Community 4', 'My Community 4', SampleThemesFixture::getTheme(4)->getId())), 5 => $communityService->createCommunity(new CreateCommunityParameters('Community 5', 'My Community 5', SampleThemesFixture::getTheme(5)->getId()))];
 }
コード例 #24
0
 public function testRoutingSuccessResolvingToInvokableMiddlewareCallsIt()
 {
     $request = new ServerRequest();
     $response = new Response();
     $result = RouteResult::fromRouteMatch('/foo', __NAMESPACE__ . '\\TestAsset\\InvokableMiddleware', []);
     $this->router->match($request)->willReturn($result);
     // No container for this one, to ensure we marshal only a potential object instance.
     $app = new Application($this->router->reveal());
     $next = function ($request, $response) {
         $this->fail('Should not enter $next');
     };
     $test = $app->routeMiddleware($request, $response, $next);
     $this->assertInstanceOf('Psr\\Http\\Message\\ResponseInterface', $test);
     $this->assertTrue($test->hasHeader('X-Invoked'));
     $this->assertEquals(__NAMESPACE__ . '\\TestAsset\\InvokableMiddleware', $test->getHeaderLine('X-Invoked'));
 }
コード例 #25
0
 private function setupPipeFromDefinition(array $definition)
 {
     $this->app->pipe($definition['middleware']);
 }
コード例 #26
0
 public function __invoke(Application $app)
 {
     $app->pipeRoutingMiddleware();
     $app->pipeDispatchMiddleware();
 }
コード例 #27
0
 /**
  * Inject routes from configuration, if any.
  *
  * @param Application $app
  * @param ContainerInterface $container
  */
 private function injectRoutes(Application $app, ContainerInterface $container)
 {
     $config = $container->has('config') ? $container->get('config') : [];
     if (!isset($config['routes'])) {
         $app->pipeRoutingMiddleware();
         return;
     }
     foreach ($config['routes'] as $spec) {
         if (!isset($spec['path']) || !isset($spec['middleware'])) {
             continue;
         }
         if (isset($spec['allowed_methods'])) {
             $methods = $spec['allowed_methods'];
             if (!is_array($methods)) {
                 throw new ContainerInvalidArgumentException(sprintf('Allowed HTTP methods for a route must be in form of an array; received "%s"', gettype($methods)));
             }
         } else {
             $methods = Route::HTTP_METHOD_ANY;
         }
         $name = isset($spec['name']) ? $spec['name'] : null;
         $route = new Route($spec['path'], $spec['middleware'], $methods, $name);
         if (isset($spec['options'])) {
             $options = $spec['options'];
             if (!is_array($options)) {
                 throw new ContainerInvalidArgumentException(sprintf('Route options must be an array; received "%s"', gettype($options)));
             }
             $route->setOptions($options);
         }
         $app->route($route);
     }
 }