/** * 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, int $status = 200, array $headers = [], $encodingOptions = self::DEFAULT_JSON_FLAGS) { $body = new Stream(fopen('php://temp', 'wb+')); $body->write($this->jsonEncode($data, $encodingOptions)); $body->rewind(); $headers = $this->injectContentType('application/json', $headers); parent::__construct($status, $headers, $body); }
/** * Create the message body. * * @param string|StreamInterface $html * * @throws InvalidArgumentException if $html is neither a string or stream. * * @return StreamInterface */ private function createBody($html) : StreamInterface { 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(fopen('php://temp', 'wb+')); $body->write($html); $body->rewind(); return $body; }
public function testCanDetachStream() { $r = fopen('php://temp', 'w+'); $stream = new Stream($r); $stream->write('foo'); $this->assertTrue($stream->isReadable()); $this->assertSame($r, $stream->detach()); $stream->detach(); $this->assertFalse($stream->isReadable()); $this->assertFalse($stream->isWritable()); $this->assertFalse($stream->isSeekable()); $throws = function (callable $fn) use($stream) { try { $fn($stream); $this->fail(); } catch (Exception $e) { } }; $throws(function ($stream) { $stream->read(10); }); $throws(function ($stream) { $stream->write('bar'); }); $throws(function ($stream) { $stream->seek(10); }); $throws(function ($stream) { $stream->tell(); }); $throws(function ($stream) { $stream->eof(); }); $throws(function ($stream) { $stream->getSize(); }); $throws(function ($stream) { $stream->getContents(); }); $this->assertSame('', (string) $stream); $stream->close(); }