111 lines
2.9 KiB
PHP
111 lines
2.9 KiB
PHP
<?php
|
|
// Serialiser.php
|
|
// Created: 2022-01-13
|
|
// Updated: 2022-02-27
|
|
|
|
namespace Index\Serialisation;
|
|
|
|
use Index\IO\Stream;
|
|
|
|
/**
|
|
* Base class for Serialisers.
|
|
*/
|
|
abstract class Serialiser {
|
|
/**
|
|
* Returns a global Base32Serialiser instance with default settings.
|
|
*
|
|
* @return Base32Serialiser
|
|
*/
|
|
public static function base32(): Base32Serialiser {
|
|
static $instance = null;
|
|
if($instance === null)
|
|
$instance = new Base32Serialiser;
|
|
return $instance;
|
|
}
|
|
|
|
/**
|
|
* Returns a global Base62Serialiser instance with default settings.
|
|
*
|
|
* @return Base62Serialiser
|
|
*/
|
|
public static function base62(): Base62Serialiser {
|
|
static $instance = null;
|
|
if($instance === null)
|
|
$instance = new Base62Serialiser;
|
|
return $instance;
|
|
}
|
|
|
|
/**
|
|
* Returns a global Base64Serialiser instance with default settings.
|
|
*
|
|
* @return Base64Serialiser
|
|
*/
|
|
public static function base64(): Base64Serialiser {
|
|
static $instance = null;
|
|
if($instance === null)
|
|
$instance = new Base64Serialiser;
|
|
return $instance;
|
|
}
|
|
|
|
/**
|
|
* Returns a global UriBase64Serialiser instance with default settings.
|
|
*
|
|
* @return UriBase64Serialiser
|
|
*/
|
|
public static function uriBase64(): UriBase64Serialiser {
|
|
static $instance = null;
|
|
if($instance === null)
|
|
$instance = new UriBase64Serialiser;
|
|
return $instance;
|
|
}
|
|
|
|
/**
|
|
* Returns a global JsonSerialiser instance with default settings.
|
|
*
|
|
* @return JsonSerialiser
|
|
*/
|
|
public static function json(): JsonSerialiser {
|
|
static $instance = null;
|
|
if($instance === null)
|
|
$instance = new JsonSerialiser;
|
|
return $instance;
|
|
}
|
|
|
|
/**
|
|
* Returns a global BencodeSerialiser instance with default settings.
|
|
*
|
|
* @return BencodeSerialiser
|
|
*/
|
|
public static function bencode(): BencodeSerialiser {
|
|
static $instance = null;
|
|
if($instance === null)
|
|
$instance = new BencodeSerialiser;
|
|
return $instance;
|
|
}
|
|
|
|
/**
|
|
* Serialises data to a stringable format.
|
|
*
|
|
* @param mixed $input Data to be serialised.
|
|
* @return string Serialised representation of the input data.
|
|
*/
|
|
abstract public function serialise(mixed $input): string;
|
|
|
|
/**
|
|
* Deserialises a stringable format into data.
|
|
*
|
|
* @param Stream|string $input String or stream to be deserialised.
|
|
* @return mixed Deserialised data of the input string.
|
|
*/
|
|
abstract public function deserialise(Stream|string $input): mixed;
|
|
|
|
/**
|
|
* Serialises data to a stringable format into stream.
|
|
*
|
|
* @param mixed $input Data to be serialised.
|
|
* @param Stream $output Target stream.
|
|
*/
|
|
public function serialiseToStream(mixed $input, Stream $output): void {
|
|
$output->write($this->serialise($input));
|
|
}
|
|
}
|