Skip to content

Commit

Permalink
feat: implemented helpers for one-way object to string conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
petrknap committed Apr 21, 2024
1 parent 12ab4a5 commit 674168e
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/StringableInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace PetrKnap\Binary;

use Stringable;
use Throwable;

interface StringableInterface extends Stringable
{
/**
* @return string binary representation of this instance
*
* @throws Throwable
*/
public function toBinary(): string;

/**
* @see self::toBinary()
*/
public function __toString(): string;
}
14 changes: 14 additions & 0 deletions src/StringableTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace PetrKnap\Binary;

trait StringableTrait
{
public function __toString(): string
{
/** @var StringableInterface $this */
return $this->toBinary();
}
}
40 changes: 40 additions & 0 deletions tests/StringableTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace PetrKnap\Binary;

use PHPUnit\Framework\TestCase;

final class StringableTest extends TestCase
{
public const DATA = b'data';

public function testToBinaryMethodWorks(): void
{
self::assertSame(
self::DATA,
self::getStringableInstance()->toBinary(),
);
}

public function testNativeConversionWorks(): void
{
self::assertSame(
self::DATA,
(string) self::getStringableInstance(),
);
}

private function getStringableInstance(): StringableInterface
{
return new class () implements StringableInterface {
use StringableTrait;

public function toBinary(): string
{
return StringableTest::DATA;
}
};
}
}

0 comments on commit 674168e

Please sign in to comment.