ulmus-api/src/Stream/JsonStream.php

56 lines
1.6 KiB
PHP

<?php
namespace Ulmus\Api\Stream;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
use Ulmus\Api\Common\HttpHeaderEnum;
use Ulmus\Api\Stream\Stream;
use Ulmus\Api\Common\StreamOutputInterface;
class JsonStream extends Stream
{
public const DEFAULT_JSON_ENCODING_FLAGS = JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR;
public const DEFAULT_JSON_DECODING_FLAGS = JSON_THROW_ON_ERROR;
public int $depth = 1024;
public int $encodingOptions;
public int $decodingOptions;
public function __construct($encodingOptions = self::DEFAULT_JSON_ENCODING_FLAGS, $decodingOptions = self::DEFAULT_JSON_DECODING_FLAGS)
{
$this->encodingOptions = $encodingOptions;
$this->decodingOptions = $decodingOptions;
}
public static function fromContent(mixed $content, int $encodingOptions = self::DEFAULT_JSON_ENCODING_FLAGS) : StreamInterface
{
if ( false === $json = json_encode($content, $encodingOptions) ) {
throw new \InvalidArgumentException(sprintf('Json encoding failed with message `%s`.', json_last_error_msg()));
}
return static::fromJsonEncoded($json);
}
public static function fromJsonEncoded(string $json) : StreamInterface
{
$obj = static::fromTemp($json);
$obj->rewind();
return $obj;
}
public function decode(): mixed
{
$content = $this->getContents();
if ($content === "") {
return null;
}
return json_decode($content, true, $this->depth, $this->decodingOptions);
}
}