Responses are considered immutable; all methods that might change state are implemented such that they retain the internal state of the current message and return a new instance that contains the changed state.
Inheritance: implements Psr\Http\Message\ResponseInterface
Example #1
4
 public function index()
 {
     $promises = call_user_func(function () {
         foreach ($this->usernames as $username) {
             (yield $this->client->requestAsync('GET', 'https://api.github.com/users/' . $username));
         }
     });
     // Wait till all the requests are finished.
     \GuzzleHttp\Promise\all($promises)->then(function (array $responses) {
         $this->profiles = array_map(function ($response) {
             return json_decode($response->getBody(), true);
         }, $responses);
     })->wait();
     // Return JSON response
     $response = new Response();
     // StreamInterface objects are not immutable!
     $response->getBody()->write($this->html());
     return $response->withHeader('Content-type', 'text/html');
 }
Example #2
0
 /**
  * @param Request $request
  * @param array $routeParams
  * @return \Zend\Diactoros\Response
  */
 public function handle(Request $request, array $routeParams = [])
 {
     $view = $this->render($request, $routeParams);
     $response = new Response();
     $response->getBody()->write($view->render());
     return $response;
 }
 /**
  * @dataProvider mappedMiddlewaresProvider
  *
  * @param array|string $mappedMiddlewares
  * @param int          $expectedCounter
  */
 public function testDispatchesMappedMiddlewares($mappedMiddlewares, int $expectedCounter)
 {
     $container = $this->prophesize(ContainerInterface::class);
     $middleware = new WorkerMiddleware(['message-name' => $mappedMiddlewares], $container->reveal());
     $request = $this->createRequest();
     $response = new Response();
     if (is_string($mappedMiddlewares)) {
         $mappedMiddlewares = (array) $mappedMiddlewares;
     }
     foreach ($mappedMiddlewares as $mappedMiddleware) {
         $container->get($mappedMiddleware)->shouldBeCalled()->willReturn([$this, 'incrementMiddleware']);
     }
     $out = function ($request, ResponseInterface $response) use($expectedCounter) {
         $this->assertEquals('default-queue', $request->getAttribute(WorkerMiddleware::MATCHED_QUEUE_ATTRIBUTE));
         $this->assertEquals('123abc', $request->getAttribute(WorkerMiddleware::MESSAGE_ID_ATTRIBUTE));
         $this->assertEquals('message-name', $request->getAttribute(WorkerMiddleware::MESSAGE_NAME_ATTRIBUTE));
         $this->assertEquals(['id' => 123], $request->getAttribute(WorkerMiddleware::MESSAGE_PAYLOAD_ATTRIBUTE));
         $this->assertEquals($expectedCounter, $request->getAttribute('counter', 0));
         $this->assertEquals($expectedCounter, $response->hasHeader('counter') ? $response->getHeaderLine('counter') : 0);
         return $response->withAddedHeader('foo', 'bar');
     };
     /** @var ResponseInterface $returnedResponse */
     $returnedResponse = $middleware($request, $response, $out);
     $this->assertEquals('bar', $returnedResponse->getHeaderLine('foo'), 'Make sure that $out was called');
     $this->assertEquals('ZfrEbWorker', $returnedResponse->getHeaderLine('X-HANDLED-BY'), 'Make sure that it adds the X-HANDLED-BY header');
 }
 public function testToCakeBody()
 {
     $psr = new PsrResponse('php://memory', 200, ['X-testing' => ['value', 'value2']]);
     $psr->getBody()->write('A message for you');
     $result = ResponseTransformer::toCake($psr);
     $this->assertSame('A message for you', $result->body());
 }
 public function createResponse(ApiProblem $apiProblem)
 {
     $response = new Response('php://memory', $apiProblem->getDetail('status'), ['Content-Type' => 'application/problem+json']);
     $json = Json::toJson($apiProblem);
     $response->getBody()->write($json);
     return $response;
 }
Example #6
0
 /**
  * Executes a http request.
  *
  * @param ServerRequestInterface $request
  *
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, Response $response)
 {
     $runner = new Runner(array_merge($this->queue, $this->sources, [function (ServerRequestInterface $request, Response $response, callable $next) {
         return $response->withStatus(404);
     }]));
     return $runner($request, $response);
 }
 /**
  * @param Request $request
  * @return \Zend\Diactoros\Response
  */
 public function handle(Request $request)
 {
     $view = $this->render($request);
     $response = new Response();
     $response->getBody()->write($view->render());
     return $response;
 }
 /**
  * Return admin assets
  * @param Response $response
  * @param $asset
  * @return Response|static
  * @throws FileNotFoundException
  */
 public function assets(Response $response, $asset)
 {
     $filesystem = new Filesystem(new Adapter(FS2ADMIN));
     $expires = 8640000;
     try {
         // generate cache data
         $timestamp_string = gmdate('D, d M Y H:i:s ', $filesystem->getTimestamp($asset)) . 'GMT';
         $etag = md5($filesystem->read($asset));
         $mime_type = $filesystem->getMimetype($asset);
         if (0 !== strpos($mime_type, 'image')) {
             $mime_type = 'text/css';
         }
         $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false;
         $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? $_SERVER['HTTP_IF_NONE_MATCH'] : false;
         if (($if_none_match && $if_none_match == "\"{$etag}\"" || !$if_none_match) && ($if_modified_since && $if_modified_since == $timestamp_string)) {
             return $response->withStatus('304');
         } else {
             $response = $response->withHeader('Last-Modified', $timestamp_string)->withHeader('ETag', "\"{$etag}\"");
         }
         // send out content type, expire time and the file
         $response->getBody()->write($filesystem->read($asset));
         return $response->withHeader('Expires', gmdate('D, d M Y H:i:s ', time() + $expires) . 'GMT')->withHeader('Content-Type', $mime_type)->withHeader('Pragma', 'cache')->withHeader('Cache-Control', 'cache');
     } catch (FileNotFoundException $e) {
         throw $e;
     }
 }
 public function testRunSingleCheckFromAttribute()
 {
     $this->runner->method('run')->with('group-name/label-name')->willReturn($this->collection);
     $this->request = $this->request->withAttribute('filter', 'group-name')->withAttribute('label', 'label-name');
     $responseFromFactory = new Response();
     $responseFromFactory->getBody()->write('foo');
     $this->resultResponseFactory->method('createResponse')->with($this->request, $this->collection)->willReturn($responseFromFactory);
     $finalResponse = $this->middleware->__invoke($this->request, $this->response);
     $this->assertSame($responseFromFactory, $finalResponse);
 }
Example #10
0
 /**
  * Test that emit invokes the appropriate methods on the emitter.
  *
  * @return void
  */
 public function testEmit()
 {
     $response = new Response('php://memory', 200, ['x-testing' => 'source header']);
     $final = $response->withHeader('X-First', 'first')->withHeader('X-Second', 'second');
     $emitter = $this->getMock('Zend\\Diactoros\\Response\\EmitterInterface');
     $emitter->expects($this->once())->method('emit')->with($final);
     $app = new MiddlewareApplication($this->config);
     $server = new Server($app);
     $server->emit($server->run(null, $response), $emitter);
 }
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $out = null)
 {
     if ($request->getUri()->getPath() === '/robots.txt') {
         $newReponse = new Response('php://memory', 200, ['Content-Type' => 'text/plain']);
         $newReponse->getBody()->write("User-Agent: *\nDisallow: /");
         return $newReponse;
     }
     /* @var $out ResponseInterface */
     $response = $out === null ? $response : $out($request, $response);
     return $response->withHeader(self::ROBOTS_HEADER, 'noindex, nofollow');
 }
 function make($status = 200, $content = '', $contentType = null, array $headers = [])
 {
     if ($contentType) {
         $headers['Content-Type'] = $contentType;
     }
     $response = new Response('php://memory', $status, $headers);
     if ($content) {
         $response->getBody()->write($content);
     }
     return $response;
 }
Example #13
0
 /**
  * @param string $content
  * @param string $filename
  *
  * @return \Psr\Http\Message\ResponseInterface
  */
 private function fileDownload($content, $filename)
 {
     $contentDisposition = sprintf("attachment; filename*=utf-8''%s", rawurlencode($filename));
     $response = new Response();
     if (is_string($content)) {
         $body = $response->getBody();
         $body->write($content);
     } elseif ($content instanceof StreamInterface) {
         $body = $content;
     }
     return $response->withBody($body)->withHeader('Content-Disposition', $contentDisposition);
 }
Example #14
0
 /**
  * User login
  *
  * @param Request $request
  * @param Response $response
  * @return Response
  */
 public function login(Request $request = null, Response $response = null)
 {
     $app = $this->app($request);
     $user = new UserSession($app);
     $user->logout();
     $assets = $this->getAssets();
     $assets[] = 'view::Index/css/login.css';
     $app->view->addData(['assets' => $assets]);
     $app->view->addData($this->getData($request));
     $content = $app->view->render('view::Index/html/login.html.php');
     $response->getBody()->write($content);
     return $response;
 }
 public function process(ServerRequestInterface $request, DelegateInterface $delegate) : ResponseInterface
 {
     $feed = null;
     if ($this->cache->contains('blog:xml-feed')) {
         $feed = $this->cache->fetch('blog:xml-feed');
     }
     if (!$feed) {
         $feed = $this->generateXmlFeed();
         $this->cache->save('blog:xml-feed', $feed);
     }
     $response = new Response();
     $response->getBody()->write($feed);
     return $response->withHeader('Content-Type', 'application/atom+xml')->withHeader('Cache-Control', ['public', 'max-age=3600']);
 }
Example #16
0
 public function index()
 {
     $promises = $this->getProfiles();
     $profiles = [];
     // Wait till all the requests are finished.
     (new EachPromise($promises, ['concurrency' => 4, 'fulfilled' => function ($profile) use(&$profiles) {
         $profiles[] = $profile;
     }]))->promise()->wait();
     // Return JSON response
     $response = new Response();
     // StreamInterface objects are not immutable!
     $response->getBody()->write($this->html($profiles));
     return $response->withHeader('Content-type', 'text/html');
 }
Example #17
0
 public function testFourth()
 {
     $request = ServerRequestFactory::fromGlobals();
     $response = new Response();
     $stack = new Stack();
     $stack->push(function (ServerRequestInterface $request, ResponseInterface $response, callable $next = null) {
         $response->getBody()->write(1);
         return $response;
     });
     $stack->push(function (ServerRequestInterface $request, ResponseInterface $response, callable $next = null) {
         $response->getBody()->write(2);
         return $next ? $next($request, $response) : $response;
     });
     $this->assertSame('1', (string) $stack->__invoke($request, $response)->getBody());
 }
Example #18
0
 /**
  * Create a JSON response with the given data.
  *
  * Default JSON encoding is performed with the following options, which
  * produces RFC4627-compliant JSON, capable of embedding into HTML.
  *
  * - JSON_HEX_TAG
  * - JSON_HEX_APOS
  * - JSON_HEX_AMP
  * - JSON_HEX_QUOT
  * - JSON_UNESCAPED_SLASHES
  *
  * @param mixed $data Data to convert to JSON.
  * @param int $status Integer status code for the response; 200 by default.
  * @param array $headers Array of headers to use at initialization.
  * @param int $encodingOptions JSON encoding options to use.
  * @throws InvalidArgumentException if unable to encode the $data to JSON.
  */
 public function __construct($data, $status = 200, array $headers = [], $encodingOptions = self::DEFAULT_JSON_FLAGS)
 {
     $body = new Stream('php://temp', 'wb+');
     $body->write($this->jsonEncode($data, $encodingOptions));
     $headers = $this->injectContentType('application/json', $headers);
     parent::__construct($body, $status, $headers);
 }
Example #19
0
 /**
  * Index action
  *
  * @param Request $request
  * @param Response $response
  * @return Response
  */
 public function index(Request $request = null, Response $response = null)
 {
     $app = $this->app($request);
     // Increment counter
     $counter = $app->session->get('counter', 0);
     $counter++;
     $app->session->set('counter', $counter);
     // Add data to template
     $assets = $this->getAssets(['view::Index/js/index.js']);
     $text = $this->getText(['Loaded successfully!' => __('Loaded successfully!')]);
     $data = $this->getData($request, ['assets' => $assets, 'text' => $text, 'content' => 'view::Index/html/index.html.php', 'counter' => $counter]);
     // Render template
     $content = $app->view->render('view::Layout/html/layout.html.php', $data);
     $response->getBody()->write($content);
     return $response;
 }
 public function testAttachToHtmlResponse()
 {
     $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']);
     $response = new Response('php://memory', 200, ['Content-Type' => 'text/html']);
     $response->getBody()->write('ResponseBody');
     $calledOut = false;
     $outFunction = function ($request, $response) use(&$calledOut) {
         $calledOut = true;
         return $response;
     };
     $this->debugbarRenderer->expects($this->once())->method('renderHead')->willReturn('RenderHead');
     $this->debugbarRenderer->expects($this->once())->method('render')->willReturn('RenderBody');
     $result = call_user_func($this->middleware, $request, $response, $outFunction);
     $this->assertTrue($calledOut, 'Out is not called');
     $this->assertSame($response, $result);
     $this->assertSame("ResponseBodyRenderHeadRenderBody", (string) $result->getBody());
 }
 /**
  * Create a redirect response.
  *
  * Produces a redirect response with a Location header and the given status
  * (302 by default).
  *
  * Note: this method overwrites the `location` $headers value.
  *
  * @param string|UriInterface $uri URI for the Location header.
  * @param int $status Integer status code for the redirect; 302 by default.
  * @param array $headers Array of headers to use at initialization.
  */
 public function __construct($uri, $status = 302, array $headers = array())
 {
     if (!is_string($uri) && !$uri instanceof UriInterface) {
         throw new InvalidArgumentException(sprintf('Uri provided to %s MUST be a string or Psr\\Http\\Message\\UriInterface instance; received "%s"', __CLASS__, is_object($uri) ? get_class($uri) : gettype($uri)));
     }
     $headers['location'] = array((string) $uri);
     parent::__construct('php://temp', $status, $headers);
 }
Example #22
0
 /**
  * PsrApiResponse constructor.
  *
  * @param null  $data
  * @param array $apiMessages
  * @param int   $status
  * @param array $headers
  * @param int   $encodingOptions
  */
 public function __construct($data = null, $apiMessages = [], $status = 200, array $headers = [], $encodingOptions = 0)
 {
     $this->messages = new ApiMessages();
     $this->setData($data);
     $this->addApiMessages($apiMessages);
     $this->encodingOptions = $encodingOptions;
     $headers = $this->injectContentType('application/json', $headers);
     parent::__construct($this->getBody(), $status, $headers);
 }
 /**
  * Wrap the remaining middleware with error handling.
  *
  * @param Request $request The request.
  * @param Response $response The response.
  * @param callable $next Callback to invoke the next middleware.
  * @return Response A response
  */
 public function __invoke(Request $request, Response $response, callable $next)
 {
     $uri = $this->getBaseUri($request);
     $route = $this->router->dispatch($request->getMethod(), $uri);
     if ($route[0] === Dispatcher::NOT_FOUND) {
         $stream = new Stream('php://temp', 'wb+');
         $stream->write('Not found');
         return $response->withStatus(404)->withBody($stream);
     }
     if ($route[0] === Dispatcher::METHOD_NOT_ALLOWED) {
         $stream = new Stream('php://temp', 'wb+');
         $stream->write('Not allowed');
         return $response->withStatus(405)->withBody($stream);
     }
     $request = $request->withAttribute('vars', $route[2]);
     $response = $this->executeCallable($route[1], $request, $response, $next);
     return $next($request, $response);
 }
 /**
  * @param \OAuth2\Token\AccessTokenInterface|null $access_token On Symfony v3.1+ only, this argument is resolved through the new argument resolver feature
  *
  * @return \Psr\Http\Message\ResponseInterface
  */
 public function userinfoAction(AccessTokenInterface $access_token = null)
 {
     if (null === $access_token) {
         $token = $this->token_storage->getToken();
         if (!$token instanceof OAuth2Token) {
             throw new AuthenticationException('Unable to find an OAuth2 Access Token. Are you behind the OAuth2 Firewall?');
         }
         $access_token = $token->getAccessToken();
     }
     try {
         $info = $this->userinfo_endpoint->handle($access_token);
         $response = new Response('php://memory', 200, ['Content-Type' => sprintf('application/%s', is_array($info) ? 'json' : 'jwt'), 'Cache-Control' => 'no-store', 'Pragma' => 'no-cache']);
         $response->getBody()->write(is_array($info) ? json_encode($info) : $info);
     } catch (BaseException $e) {
         $response = new Response();
         $e->getHttpResponse($response);
     }
     return $response;
 }
 public function testRoutingFailureDueToHttpMethodCallsNextWithNotAllowedResponseAndError()
 {
     $request = new ServerRequest();
     $response = new Response();
     $result = RouteResult::fromRouteFailure(['GET', 'POST']);
     $this->router->match($request)->willReturn($result);
     $next = function ($request, $response, $error = false) {
         $this->assertEquals(405, $error);
         $this->assertEquals(405, $response->getStatusCode());
         return $response;
     };
     $app = $this->getApplication();
     $test = $app->routeMiddleware($request, $response, $next);
     $this->assertInstanceOf('Psr\\Http\\Message\\ResponseInterface', $test);
     $this->assertEquals(405, $test->getStatusCode());
     $allow = $test->getHeaderLine('Allow');
     $this->assertContains('GET', $allow);
     $this->assertContains('POST', $allow);
 }
Example #26
0
 /**
  * Edit
  *
  * @param Request $request
  * @param Response $response
  * @return Response
  */
 public function edit(Request $request = null, Response $response = null)
 {
     // All GET parameters
     $queryParams = $request->getQueryParams();
     // All POST or PUT parameters
     $postParams = $request->getParsedBody();
     // Single GET parameter
     //$title = $queryParams['title'];
     //
     // Single POST/PUT parameter
     //$data = $postParams['data'];
     //
     // Get routing arguments
     $vars = $request->getAttribute('vars');
     $id = $vars['id'];
     // Get config value
     $app = $this->app($request);
     $env = $app->config['env']['name'];
     // Get GET parameter
     $id = $app->http->get('id');
     // Increment counter
     $counter = $app->session->get('counter', 0);
     $counter++;
     $app->session->set('counter', $counter);
     $app->logger->info('My log message');
     // Set locale
     //$app->session->set('user.locale', 'de_DE');
     //
     //Model example
     //$user = new \App\Model\User($app);
     //$userRows = $user->getAll();
     //$userRow = $user->getById($id);
     //
     // Add data to template
     $data = $this->getData($request, ['id' => $id, 'assets' => $this->getAssets(), 'content' => 'view::User/html/edit.html.php']);
     // Render template
     $content = $app->view->render('view::Layout/html/layout.html.php', $data);
     // Return new response
     $response->getBody()->write($content);
     return $response;
 }
 /**
  * Create a JSONP response with the given data.
  *
  * @param mixed $data Data to convert to JSON.
  * @param string $callback The JSONP callback function.
  * @param int $status Integer status code for the response; 200 by default.
  * @param array $headers Array of headers to use at initialization.
  * @param int $encodingOptions JSON encoding options to use.
  * @throws InvalidArgumentException if $data pr $callback invalid.
  */
 public function __construct($data, $callback, $status = 200, array $headers = [], $encodingOptions = JsonResponse::DEFAULT_JSON_FLAGS)
 {
     $this->validateCallback($callback);
     $body = new Stream('php://temp', 'wb+');
     $body->write($callback);
     $body->write('(');
     $body->write($this->jsonEncode($data, $encodingOptions));
     $body->write(');');
     $body->rewind();
     $headers = $this->injectContentType('application/javascript', $headers);
     parent::__construct($body, $status, $headers);
 }
Example #28
0
 /**
  *
  */
 public function run()
 {
     $route = $this->getRoute();
     if ($route !== null) {
         $queue = array_merge($this->_middleware->getArrayCopy(), $route->getMiddleware());
         $queue[] = $route->getRequestHandler();
         $relayBuilder = new RelayBuilder();
         $relay = $relayBuilder->newInstance($queue);
         (new SapiEmitter())->emit($relay($this->_request, $this->_response));
         return true;
     }
     (new SapiEmitter())->emit($this->_response->withStatus(404));
 }
 public function testSimulateRequest()
 {
     $simulatedRequest = "DELETE / HTTP/1.1\r\nBar: faz\r\nHost: php-middleware.com";
     $postBody = http_build_query([RequestSimulatorMiddleware::PARAM => $simulatedRequest]);
     $stream = new Stream('php://memory', 'wb+');
     $stream->write($postBody);
     $request = new ServerRequest([], [], new Uri(), 'POST', $stream, ['Content-type' => 'application/x-www-form-urlencoded']);
     $responseBody = json_encode(['boo' => 'foo']);
     $response = new Response('php://memory', 200, ['content-type' => 'application/json']);
     $response->getBody()->write($responseBody);
     $next = function (ServerRequestInterface $request, ResponseInterface $response) {
         $this->assertSame('DELETE', $request->getMethod());
         $this->assertSame('faz', $request->getHeaderLine('Bar'));
         return $response;
     };
     /* @var $result ResponseInterface */
     $result = call_user_func($this->middleware, $request, $response, $next);
     $body = (string) $result->getBody();
     $this->assertContains('text/html', $result->getHeaderLine('Content-type'));
     $this->assertContains('{"boo":"foo"}', $body);
     $this->assertContains('<html>', $body);
     $this->assertContains('DELETE / HTTP/1.1', $body);
 }
 /**
  * Create a plain text response.
  *
  * Produces a text response with a Content-Type of text/plain and a default
  * status of 200.
  *
  * @param string|StreamInterface $text String or stream for the message body.
  * @param int $status Integer status code for the response; 200 by default.
  * @param array $headers Array of headers to use at initialization.
  * @throws InvalidArgumentException if $text is neither a string or stream.
  */
 public function __construct($text, $status = 200, array $headers = [])
 {
     parent::__construct($this->createBody($text), $status, $this->injectContentType('text/plain; charset=utf-8', $headers));
 }