write() public method

public write ( $string )
 /**
  * Convert a CakePHP response into a PSR7 one.
  *
  * @param CakeResponse $response The CakePHP response to convert
  * @return PsrResponse $response The equivalent PSR7 response.
  */
 public static function toPsr(CakeResponse $response)
 {
     $status = $response->statusCode();
     $headers = $response->header();
     if (!isset($headers['Content-Type'])) {
         $headers['Content-Type'] = $response->type();
     }
     $body = $response->body();
     $stream = 'php://memory';
     if (is_string($body)) {
         $stream = new Stream('php://memory', 'wb');
         $stream->write($response->body());
     }
     if (is_callable($body)) {
         $stream = new CallbackStream($body);
     }
     // This is horrible, but CakePHP doesn't have a getFile() method just yet.
     $fileProp = new \ReflectionProperty($response, '_file');
     $fileProp->setAccessible(true);
     $file = $fileProp->getValue($response);
     if ($file) {
         $stream = new Stream($file->path, 'rb');
     }
     return new DiactorosResponse($stream, $status, $headers);
 }
Esempio n. 2
0
 /**
  * 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);
 }
Esempio n. 3
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);
 }
 /**
  * @param string $content
  *
  * @return StreamInterface
  */
 protected function createBody($content)
 {
     $body = new Stream('php://temp', 'wb+');
     $body->write($content);
     $body->rewind();
     return $body;
 }
Esempio n. 5
0
 /**
  * Creates stream from string data
  *
  * @param string $content
  *
  * @throws RuntimeException
  *
  * @return StreamInterface
  *
  * @since 3.00
  */
 public function createStreamFromString($content)
 {
     $stream = new Stream('php://memory', 'wb+');
     $stream->write($content);
     $stream->rewind();
     return $stream;
 }
 /**
  * @param string $content
  * @param array $headers
  * @param int $statusCode
  * @return Response
  */
 protected function responseFactory($content, array $headers = [], $statusCode = 200)
 {
     $stream = new Stream('php://memory', 'r+');
     $stream->write($content);
     $response = new Response($stream, $statusCode, $headers);
     return $response;
 }
Esempio n. 7
0
 /**
  * Create the message body.
  *
  * @param QrCode $qrCode
  * @return StreamInterface
  */
 private function createBody(QrCode $qrCode)
 {
     $body = new Stream('php://temp', 'wb+');
     $body->write($qrCode->get());
     $body->rewind();
     return $body;
 }
Esempio n. 8
0
 /**
  * Get body for response
  *
  * {@inheritdoc}
  */
 public function getBody()
 {
     $body = new Stream('php://temp', 'wb+');
     $body->write($this->resource->asJson());
     $body->rewind();
     return $body;
 }
Esempio n. 9
0
 /**
  * {@inheritdoc}
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, WatcherInterface $watcher)
 {
     $content = '';
     $contentType = $this->determineContentType($request);
     switch ($contentType) {
         case 'text/json':
         case 'application/json':
             $content = $this->renderJson($watcher);
             break;
         case 'text/xml':
         case 'application/xml':
             $content = $this->renderXml($watcher);
             break;
         case 'text/html':
             $content = $this->renderHtml($watcher);
             break;
     }
     $body = new Stream('php://temp', 'r+');
     $body->write($content);
     if ($watcher instanceof ScheduledWatcherInterface) {
         $response = $response->withHeader('Expires', $watcher->getEnd()->format('D, d M Y H:i:s e'))->withHeader('Retry-After', $watcher->getEnd()->format('D, d M Y H:i:s e'));
     } else {
         $response = $response->withHeader('Cache-Control', 'max-age=0')->withHeader('Cache-Control', 'no-cache, must-revalidate')->withHeader('Pragma', 'no-cache');
     }
     return $response->withStatus(503)->withHeader('Content-Type', $contentType)->withBody($body);
 }
Esempio n. 10
0
 /**
  * Handle an exception and generate an error response.
  *
  * @param Exception $ex The exception to handle.
  * @param Request $request The request.
  * @param Response $response The response.
  * @return Response A response
  */
 public function handleException(Exception $ex, Request $request, Response $response)
 {
     $message = sprintf("[%s] %s\n%s", get_class($ex), $ex->getMessage(), $ex->getTraceAsString());
     // Must be PSR logger (Monolog)
     $logger = $request->getAttribute(\App\Middleware\LoggerMiddleware::ATTRIBUTE);
     if (!empty($logger)) {
         $logger->error($message);
     }
     $stream = new Stream('php://temp', 'wb+');
     $stream->write('An Internal Server Error Occurred');
     // Verbose error output
     if (!empty($this->config['verbose'])) {
         $stream->write("\n<br>{$message}");
     }
     $response = $response->withStatus(500)->withBody($stream);
     return $response;
 }
 function makeBody($content = '', $stream = 'php://memory')
 {
     $s = new Stream($stream, 'wb+');
     if (exists($content)) {
         $s->write($content);
     }
     return $s;
 }
Esempio n. 12
0
 protected static function requestFromZendDiactoros($url = null, $method = null, $headers = null, $body = null)
 {
     if (is_string($body)) {
         $bodyStr = $body;
         $body = new ZendDiactorosStream('php://temp', 'r+');
         $body->write($bodyStr);
     }
     return new ZendDiactorosRequest($url ? (string) $url : '', $method ? $method : 'GET', $body ? $body : 'php://temp', $headers ? $headers : []);
 }
 /**
  * @dataProvider getDraftMessages
  */
 public function testInvalidMessage($message)
 {
     $request = (new \Zend\Diactoros\Request())->withUri(new \Zend\Diactoros\Uri('/message'))->withMethod("POST");
     $stream = new Stream('php://memory', 'wb+');
     $stream->write(json_encode($message));
     $request = $request->withBody($stream);
     $response = new \Zend\Diactoros\Response();
     $response = $this->app->run($request, $response);
     $this->assertEquals(406, $response->getStatusCode());
 }
Esempio n. 14
0
 /**
  * Creates a PSR-7 compatible request
  *
  * @param \TYPO3\Flow\Http\Request $nativeRequest Flow request object
  * @param array $files List of uploaded files like in $_FILES
  * @param array $query List of uploaded files like in $_GET
  * @param array $post List of uploaded files like in $_POST
  * @param array $cookies List of uploaded files like in $_COOKIES
  * @param array $server List of uploaded files like in $_SERVER
  * @return \Psr\Http\Message\ServerRequestInterface PSR-7 request object
  */
 protected function createRequest(\TYPO3\Flow\Http\Request $nativeRequest, array $files, array $query, array $post, array $cookies, array $server)
 {
     $server = ServerRequestFactory::normalizeServer($server);
     $files = ServerRequestFactory::normalizeFiles($files);
     $headers = $nativeRequest->getHeaders()->getAll();
     $uri = (string) $nativeRequest->getUri();
     $method = $nativeRequest->getMethod();
     $body = new Stream('php://temp', 'wb+');
     $body->write($nativeRequest->getContent());
     return new ServerRequest($server, $files, $uri, $method, $body, $headers, $cookies, $query, $post);
 }
Esempio n. 15
0
 /**
  * @test
  */
 public function regularRequestsAreUrlDecoded()
 {
     $body = new Stream('php://temp', 'wr');
     $body->write('foo=bar&bar[]=one&bar[]=5');
     $request = ServerRequestFactory::fromGlobals()->withMethod('PUT')->withBody($body);
     $test = $this;
     $this->middleware->__invoke($request, new Response(), function (Request $req, $resp) use($test, $request) {
         $test->assertNotSame($request, $req);
         $test->assertEquals(['foo' => 'bar', 'bar' => ['one', 5]], $req->getParsedBody());
     });
 }
 /**
  * Convert a Zend\Http\Response in a PSR-7 response, using zend-diactoros
  *
  * @param  ZendRequest $zendRequest
  * @return ServerRequest
  */
 public static function fromZend(ZendRequest $zendRequest)
 {
     $body = new Stream('php://memory', 'wb+');
     $body->write($zendRequest->getContent());
     $headers = empty($zendRequest->getHeaders()) ? [] : $zendRequest->getHeaders()->toArray();
     $query = empty($zendRequest->getQuery()) ? [] : $zendRequest->getQuery()->toArray();
     $post = empty($zendRequest->getPost()) ? [] : $zendRequest->getPost()->toArray();
     $files = empty($zendRequest->getFiles()) ? [] : $zendRequest->getFiles()->toArray();
     $request = new ServerRequest([], self::convertFilesToUploaded($files), $zendRequest->getUriString(), $zendRequest->getMethod(), $body, $headers);
     $request = $request->withQueryParams($query);
     return $request->withParsedBody($post);
 }
Esempio n. 17
0
 /**
  * Create the message body.
  *
  * @param string|StreamInterface $html
  * @return StreamInterface
  * @throws InvalidArgumentException if $html is neither a string or stream.
  */
 private function createBody($html)
 {
     if ($html instanceof StreamInterface) {
         return $html;
     }
     if (!is_string($html)) {
         throw new InvalidArgumentException(sprintf('Invalid content (%s) provided to %s', is_object($html) ? get_class($html) : gettype($html), __CLASS__));
     }
     $body = new Stream('php://temp', 'wb+');
     $body->write($html);
     return $body;
 }
Esempio n. 18
0
 /**
  * {@inheritDoc}
  *
  * Will render the view and use the content as the body of the response.
  * It will also set the specified HTTP code and optional additional headers.
  */
 public function process(ServerRequestInterface $request, ResponseInterface $response)
 {
     $className = $this->_config['view']['className'];
     if (empty($className)) {
         $className = 'App\\View\\AppView';
     }
     $viewConfig = $this->_config['view'] ?: [];
     $view = new $className(RequestTransformer::toCake($request), ResponseTransformer::toCake($response), null, $viewConfig);
     $stream = new Stream(fopen('php://memory', 'r+'));
     $stream->write($view->render());
     $response = $response->withBody($stream);
     $response = $response->withStatus($this->_config['code']);
     $response = $this->addHeaders($response);
     return $response;
 }
 /**
  * Creates a stream
  *
  * @param string|resource|StreamInterface|null $body
  *
  * @return StreamInterface
  *
  * @throws \InvalidArgumentException If the stream body is invalid
  * @throws \RuntimeException If cannot write into stream
  */
 public function createStream($body = null)
 {
     if (!$body instanceof StreamInterface) {
         if (is_resource($body)) {
             $body = new Stream($body);
         } else {
             $stream = new Stream('php://memory', 'rw');
             if (null !== $body) {
                 $stream->write((string) $body);
             }
             $body = $stream;
         }
     }
     $body->rewind();
     return $body;
 }
Esempio n. 20
0
 /**
  * Creates a stream.
  *
  * @param null|resource|string|\Psr\Http\Message\StreamInterface|null $body The body
  *
  * @return \Psr\Http\Message\StreamInterface The stream
  */
 private function doCreateStream($body)
 {
     if ($body instanceof StreamInterface) {
         $body->rewind();
         return $body;
     }
     if (is_resource($body)) {
         return $this->doCreateStream(new Stream($body));
     }
     $stream = new Stream('php://memory', 'rw');
     if ($body === null) {
         return $stream;
     }
     $stream->write((string) $body);
     return $this->doCreateStream($stream);
 }
Esempio n. 21
0
 /**
  * Transforms a Symfony request into a PSR-7 request object
  *
  * @param \Illuminate\Http\Request $nativeRequest Laravel request object
  * @return \Psr\Http\Message\ServerRequestInterface PSR-7 request object
  */
 protected function createRequest(\Illuminate\Http\Request $nativeRequest)
 {
     $files = ServerRequestFactory::normalizeFiles($this->getFiles($nativeRequest->files->all()));
     $server = ServerRequestFactory::normalizeServer($nativeRequest->server->all());
     $headers = $nativeRequest->headers->all();
     $cookies = $nativeRequest->cookies->all();
     $post = $nativeRequest->request->all();
     $query = $nativeRequest->query->all();
     $method = $nativeRequest->getMethod();
     $uri = $nativeRequest->getUri();
     $body = new Stream('php://temp', 'wb+');
     $body->write($nativeRequest->getContent());
     $request = new ServerRequest($server, $files, $uri, $method, $body, $headers, $cookies, $query, $post);
     foreach ($nativeRequest->attributes->all() as $key => $value) {
         $request = $request->withAttribute($key, $value);
     }
     return $request;
 }
Esempio n. 22
0
 /**
  * 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);
 }
 protected function createBody($content)
 {
     if (is_resource($content)) {
         $this->resource = $content;
         $content = null;
     }
     $this->content = $content;
     if ($content instanceof StreamInterface) {
         return $content;
     } elseif (null === $content || false === $content || '' === $content) {
         // but not zero
         $stream = new Stream('php://temp', 'r');
         return $stream;
     }
     $stream = new Stream('php://temp', 'wb+');
     $stream->write((string) $content);
     $stream->rewind();
     return $stream;
 }
Esempio n. 24
0
 public function testCreateWithJson()
 {
     $value = ['value' => 123, '_embedded' => ['key' => 'value']];
     $body = json_encode($value);
     $stream = new Stream('php://memory', 'wb+');
     $stream->write($body);
     $stream->rewind();
     $this->storage->has('notfound')->willReturn(false);
     $this->storage->set('notfound', $value)->willReturn(null);
     $action = new CreateAction($this->storage->reveal());
     $request = (new ServerRequest())->withMethod('POST')->withUri(new Uri('http://example.com/key/notfound'))->withAddedHeader('Accept', 'application/json')->withAddedHeader('Content-Type', 'application/json')->withAttribute('key', 'notfound')->withBody($stream);
     $response = $action($request, new Response(), function ($request, $response) {
         return $response;
     });
     $json = json_decode((string) $response->getBody());
     $this->assertTrue($response instanceof Response\JsonResponse);
     $this->assertSame(200, $response->getStatusCode());
     $this->assertEmpty($json);
 }
 /**
  * Return a new GuzzleHttp\Psr7\Request object.
  * The body is to be sent as a JSON request.
  * @param null|string $method
  * @param UriInterface|null|string $uri
  * @param array $headers
  * @param null $body
  * @param string $protocolVersion
  * @return Request
  */
 public function JsonRequest($method, $uri, array $headers = [], $body = null, $protocolVersion = '1.1')
 {
     // If we are sending a JSON body, then the recipient needs to know.
     $headers['Content-type'] = 'application/json';
     // If the body is not already a stream or string of some sort, then JSON encode it for streaming.
     if (!is_string($body) && !$body instanceof StreamInterface && gettype($body) != 'resource') {
         $body = json_encode($body);
     }
     // Create a stream for the body if a string.
     // Diactoros will treat a string as a resource URI and not as the body.
     if (is_string($body)) {
         $bodyStream = new Stream('php://memory', 'wb+');
         $bodyStream->write($body);
     } else {
         // CHECKME: will Diactoros accept a resource as a body?
         $bodyStream = $body;
     }
     return new Request($uri, $method, $bodyStream, $headers);
 }
Esempio n. 26
0
 /**
  * Embed SOAP messages in PSR-7 HTTP Requests
  *
  * @param string $name              The name of the SOAP function to bind.
  * @param array  $arguments         An array of the arguments to the SOAP function.
  * @param array  $options           An associative array of options.
  *                                  The location option is the URL of the remote Web service.
  *                                  The uri option is the target namespace of the SOAP service.
  *                                  The soapaction option is the action to call.
  * @param mixed $inputHeaders       An array of headers to be bound along with the SOAP request.
  * @return RequestInterface
  * @throws RequestException         If SOAP HTTP binding failed using the given parameters.
  */
 public function request($name, array $arguments, array $options = null, $inputHeaders = null)
 {
     $soapRequest = $this->interpreter->request($name, $arguments, $options, $inputHeaders);
     if ($soapRequest->getSoapVersion() == '1') {
         $this->builder->isSOAP11();
     } else {
         $this->builder->isSOAP12();
     }
     $this->builder->setEndpoint($soapRequest->getEndpoint());
     $this->builder->setSoapAction($soapRequest->getSoapAction());
     $stream = new Stream('php://temp', 'r+');
     $stream->write($soapRequest->getSoapMessage());
     $stream->rewind();
     $this->builder->setSoapMessage($stream);
     try {
         return $this->builder->getSoapHttpRequest();
     } catch (RequestException $exception) {
         $stream->close();
         throw $exception;
     }
 }
Esempio n. 27
0
 /**
  * Get file
  *
  * @return array
  * @throws InternalServerError
  */
 public function get()
 {
     // Build file name based on (URI) arguments
     $filename = implode('/', func_get_args());
     // Get the file system
     $fileSystem = $this->container['flySystem'];
     // Get the file content and write it to file
     if (!$fileSystem->has($filename)) {
         throw new InternalServerError('Could not read file from storage.');
     }
     // Get file content
     $fileContent = $fileSystem->read($filename);
     // Get mime type
     $finfo = new \finfo(FILEINFO_MIME_TYPE);
     $mimeType = $finfo->buffer($fileContent);
     // Write content to body
     $body = new Stream('php://memory', 'w+');
     $body->write($fileContent);
     // Set headers
     $this->response = $this->response->withBody($body)->withHeader('Content-Type', $mimeType)->withHeader('Content-Length', strval(strlen($fileContent)));
     return [];
 }
Esempio n. 28
0
 /**
  * Test the Callback filter mode
  * @return void
  */
 public function testMaintenanceModeCallback()
 {
     Configure::write('Wrench.enable', true);
     $request = ServerRequestFactory::fromGlobals(['HTTP_HOST' => 'localhost', 'REQUEST_URI' => '/']);
     $response = new Response();
     $next = function ($req, $res) {
         return $res;
     };
     $middleware = new MaintenanceMiddleware(['mode' => ['className' => 'Wrench\\Mode\\Callback', 'config' => ['callback' => function ($request, $response) {
         $string = 'Some content from a callback';
         $stream = new Stream(fopen('php://memory', 'r+'));
         $stream->write($string);
         $response = $response->withBody($stream);
         $response = $response->withStatus(503);
         $response = $response->withHeader('someHeader', 'someValue');
         return $response;
     }]]]);
     $middlewareResponse = $middleware($request, $response, $next);
     $this->assertEquals('Some content from a callback', (string) $middlewareResponse->getBody());
     $this->assertEquals(503, $middlewareResponse->getStatusCode());
     $this->assertEquals('someValue', $middlewareResponse->getHeaderLine('someHeader'));
 }
 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);
 }
    /**
     * @test
     */
    public function soap12()
    {
        $interpreter = new Interpreter('http://www.webservicex.net/uszip.asmx?WSDL', ['soap_version' => SOAP_1_2]);
        $builder = new RequestBuilder();
        $httpBinding = new HttpBinding($interpreter, $builder);
        $request = $httpBinding->request('GetInfoByCity', [['USCity' => 'New York']]);
        $this->assertTrue($request instanceof \Psr\Http\Message\RequestInterface);
        $response = <<<EOD
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <GetInfoByCityResponse xmlns="http://www.webserviceX.NET">
      <GetInfoByCityResult>some information</GetInfoByCityResult>
    </GetInfoByCityResponse>
  </soap12:Body>
</soap12:Envelope>
EOD;
        $stream = new Stream('php://memory', 'r+');
        $stream->write($response);
        $stream->rewind();
        $response = new Response($stream, 200, ['Content-Type' => 'Content-Type: application/soap+xml; charset=utf-8']);
        $response = $httpBinding->response($response, 'GetInfoByCity');
        $this->assertObjectHasAttribute('GetInfoByCityResult', $response);
    }