From 7ce9fc782bec1bfdd303b8b6f175b3ef96534387 Mon Sep 17 00:00:00 2001 From: JoshyPHP Date: Mon, 16 Oct 2023 19:39:33 +0200 Subject: [PATCH] Added BencodeSerializable interface --- README.md | 35 +++++++++++++++++++++++++++++++++-- composer.json | 3 ++- src/BencodeSerializable.php | 18 ++++++++++++++++++ src/Encoder.php | 4 ++++ tests/EncoderTest.php | 11 +++++++++++ 5 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 src/BencodeSerializable.php diff --git a/README.md b/README.md index 977e2fd..9026415 100644 --- a/README.md +++ b/README.md @@ -23,8 +23,12 @@ print_r(Bencode::decode('d3:bar4:spam3:fooi42ee')); ``` ArrayObject Object ( - [bar] => spam - [foo] => 42 + [storage:ArrayObject:private] => Array + ( + [bar] => spam + [foo] => 42 + ) + ) ``` @@ -38,6 +42,33 @@ print_r(Bencode::encode(['foo' => 42, 'bar' => 'spam'])); d3:bar4:spam3:fooi42ee ``` +Supported types are as follow: + + - `array`, `int`, and `string` values are encoded natively. + - `float` values that can be losslessly converted to integers are coerced to `int`. + - `bool` values are coerced to `int`. + - An object that implements `s9e\Bencode\BencodeSerializable` is encoded as the value returned by its `bencodeSerialize()` method. + - The properties of an `stdClass` object are encoded in a dictionary. + - An instance of `ArrayObject` is treated as an array. + +```php +use s9e\Bencode\Bencode; +use s9e\Bencode\BencodeSerializable; + +$bencodable = new class implements BencodeSerializable +{ + public function bencodeSerialize(): array|int|string + { + return 42; + } +}; + +print_r(Bencode::encode($bencodable)); +``` +``` +i42e +``` + #### Handle exceptions ```php diff --git a/composer.json b/composer.json index fe756aa..29845ca 100644 --- a/composer.json +++ b/composer.json @@ -10,7 +10,8 @@ }, "require-dev": { "phpunit/phpunit": ">=10.0", - "nikic/php-fuzzer": "*" + "nikic/php-fuzzer": "*", + "s9e/repdoc": "dev-wip" }, "autoload": { "psr-4": { diff --git a/src/BencodeSerializable.php b/src/BencodeSerializable.php new file mode 100644 index 0000000..d02f5ea --- /dev/null +++ b/src/BencodeSerializable.php @@ -0,0 +1,18 @@ +bencodeSerialize()); + } if ($value instanceof ArrayObject) { return static::encodeAssociativeArray($value->getArrayCopy()); diff --git a/tests/EncoderTest.php b/tests/EncoderTest.php index 2a1e546..a2c7e97 100644 --- a/tests/EncoderTest.php +++ b/tests/EncoderTest.php @@ -6,6 +6,7 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use TypeError; +use s9e\Bencode\BencodeSerializable; use s9e\Bencode\Encoder; use s9e\Bencode\Exceptions\EncodingException; use stdClass; @@ -60,6 +61,16 @@ public static function getEncodeTests() 'de', new class extends stdClass {} ], + [ + 'i42e', + new class implements BencodeSerializable + { + public function bencodeSerialize(): array|int|string + { + return 42; + } + } + ], [ 'd3:fooi1ee', ['foo' => 1]