2022-09-13 15:13:11 +02:00
|
|
|
<?php
|
|
|
|
// JsonContent.php
|
|
|
|
// Created: 2022-02-10
|
2023-07-21 21:47:41 +00:00
|
|
|
// Updated: 2023-07-21
|
2022-09-13 15:13:11 +02:00
|
|
|
|
|
|
|
namespace Index\Http\Content;
|
|
|
|
|
|
|
|
use JsonSerializable;
|
|
|
|
use Stringable;
|
|
|
|
use Index\IO\Stream;
|
|
|
|
use Index\IO\FileStream;
|
|
|
|
|
|
|
|
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 {
|
2023-07-21 21:47:41 +00:00
|
|
|
return json_encode($this->content);
|
2022-09-13 15:13:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public function __toString(): string {
|
|
|
|
return $this->encode();
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function fromEncoded(Stream|string $encoded): JsonContent {
|
2023-07-21 21:47:41 +00:00
|
|
|
return new JsonContent(json_decode($encoded));
|
2022-09-13 15:13:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public static function fromFile(string $path): JsonContent {
|
|
|
|
return self::fromEncoded(FileStream::openRead($path));
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function fromRequest(): JsonContent {
|
|
|
|
return self::fromFile('php://input');
|
|
|
|
}
|
|
|
|
}
|