index/src/Http/Content/BencodedContent.php

76 lines
1.9 KiB
PHP

<?php
// BencodedContent.php
// Created: 2022-02-10
// Updated: 2024-08-01
namespace Index\Http\Content;
use Index\Bencode\{Bencode,IBencodeSerialisable};
use Index\IO\{Stream,FileStream};
/**
* Represents Bencoded body content for a HTTP message.
*/
class BencodedContent implements IHttpContent, IBencodeSerialisable {
/**
* @param mixed $content Content to be bencoded.
*/
public function __construct(
private mixed $content
) {}
/**
* Retrieves unencoded content.
*
* @return mixed Content.
*/
public function getContent(): mixed {
return $this->content;
}
public function bencodeSerialise(): mixed {
return $this->content;
}
/**
* Encodes the content.
*
* @return string Bencoded string.
*/
public function encode(): string {
return Bencode::encode($this->content);
}
public function __toString(): string {
return $this->encode();
}
/**
* Creates an instance from encoded content.
*
* @param mixed $encoded Bencoded content.
* @return BencodedContent Instance representing the provided content.
*/
public static function fromEncoded(mixed $encoded): BencodedContent {
return new BencodedContent(Bencode::decode($encoded));
}
/**
* Creates an instance from an encoded file.
*
* @param string $path Path to the bencoded file.
* @return BencodedContent Instance representing the provided path.
*/
public static function fromFile(string $path): BencodedContent {
return self::fromEncoded(FileStream::openRead($path));
}
/**
* Creates an instance from the raw request body.
*
* @return BencodedContent Instance representing the request body.
*/
public static function fromRequest(): BencodedContent {
return self::fromFile('php://input');
}
}