index/src/Http/Content/JsonContent.php

80 lines
1.9 KiB
PHP

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