index/src/Http/Content/JsonContent.php

49 lines
1.1 KiB
PHP

<?php
// JsonContent.php
// Created: 2022-02-10
// Updated: 2022-02-27
namespace Index\Http\Content;
use JsonSerializable;
use Stringable;
use Index\IO\Stream;
use Index\IO\FileStream;
use Index\Serialisation\Serialiser;
class JsonContent implements Stringable, IHttpContent, JsonSerializable {
private mixed $content;
public function __construct(mixed $content) {
$this->content = $content;
}
public function getContent(): mixed {
return $this->content;
}
public function jsonSerialize(): mixed {
return $this->content;
}
public function encode(): string {
return Serialiser::json()->serialise($this->content);
}
public function __toString(): string {
return $this->encode();
}
public static function fromEncoded(Stream|string $encoded): JsonContent {
return new JsonContent(Serialiser::json()->deserialise($encoded));
}
public static function fromFile(string $path): JsonContent {
return self::fromEncoded(FileStream::openRead($path));
}
public static function fromRequest(): JsonContent {
return self::fromFile('php://input');
}
}