index/src/Http/Content/JsonContent.php

79 lines
1.9 KiB
PHP
Raw Normal View History

2022-09-13 15:13:11 +02:00
<?php
// JsonContent.php
// Created: 2022-02-10
// Updated: 2024-08-01
2022-09-13 15:13:11 +02:00
namespace Index\Http\Content;
use JsonSerializable;
use Index\IO\{Stream,FileStream};
2022-09-13 15:13:11 +02:00
/**
* Represents JSON body content for a HTTP message.
*/
class JsonContent implements IHttpContent, JsonSerializable {
2022-09-13 15:13:11 +02:00
private mixed $content;
/**
* @param mixed $content Content to be JSON encoded.
*/
2022-09-13 15:13:11 +02:00
public function __construct(mixed $content) {
$this->content = $content;
}
/**
* Retrieves unencoded content.
*
* @return mixed Content.
*/
2022-09-13 15:13:11 +02:00
public function getContent(): mixed {
return $this->content;
}
public function jsonSerialize(): mixed {
return $this->content;
}
/**
* Encodes the content.
*
* @return string JSON encoded string.
*/
2022-09-13 15:13:11 +02:00
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();
}
/**
* Creates an instance from encoded content.
*
* @param mixed $encoded JSON encoded content.
* @return JsonContent Instance representing the provided content.
*/
public static function fromEncoded(mixed $encoded): JsonContent {
2023-07-21 21:47:41 +00:00
return new JsonContent(json_decode($encoded));
2022-09-13 15:13:11 +02:00
}
/**
* Creates an instance from an encoded file.
*
* @param string $path Path to the JSON encoded file.
* @return JsonContent Instance representing the provided path.
*/
2022-09-13 15:13:11 +02:00
public static function fromFile(string $path): JsonContent {
return self::fromEncoded(FileStream::openRead($path));
}
/**
* Creates an instance from the raw request body.
*
* @return JsonContent Instance representing the request body.
*/
2022-09-13 15:13:11 +02:00
public static function fromRequest(): JsonContent {
return self::fromFile('php://input');
}
}