Skip to content

Commit

Permalink
Add formatter that only casts content to string
Browse files Browse the repository at this point in the history
  • Loading branch information
lcobucci committed Mar 26, 2018
1 parent a33d567 commit ff5f2a0
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/Formatter/StringCast.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);

namespace Lcobucci\ContentNegotiation\Formatter;

use Lcobucci\ContentNegotiation\ContentCouldNotBeFormatted;
use Lcobucci\ContentNegotiation\Formatter;
use function is_object;
use function method_exists;

final class StringCast implements Formatter
{
/**
* {@inheritdoc}
*/
public function format($content): string
{
if (is_object($content) && ! method_exists($content, '__toString')) {
throw new ContentCouldNotBeFormatted('Given data could not be cast to string');
}

return (string) $content;
}
}
71 changes: 71 additions & 0 deletions tests/Formatter/StringCastTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);

namespace Lcobucci\ContentNegotiation\Tests\Formatter;

use Lcobucci\ContentNegotiation\ContentCouldNotBeFormatted;
use Lcobucci\ContentNegotiation\Formatter\StringCast;
use PHPUnit\Framework\TestCase;

/**
* @coversDefaultClass \Lcobucci\ContentNegotiation\Formatter\StringCast
*/
final class StringCastTest extends TestCase
{
/**
* @test
* @dataProvider validData
*
* @covers ::format()
*
* @param mixed $content
*/
public function formatShouldSimplyReturnTheStringRepresentationOfTheContent(
string $expected,
$content
): void {
$formatter = new StringCast();

self::assertSame($expected, $formatter->format($content));
}

/**
* @return mixed[][]
*/
public function validData(): array
{
$test = new class
{
public function __toString(): string
{
return 'test';
}
};

return [
['test', 'test'],
['test', $test],
['1', 1],
['1', true],
['', false],
['', null],
];
}

/**
* @test
*
* @covers ::format()
*/
public function formatShouldRaiseExceptionWhenContentCouldNotBeCastToString(): void
{
$this->expectException(ContentCouldNotBeFormatted::class);

$content = new class
{
};

$formatter = new StringCast();
$formatter->format($content);
}
}

0 comments on commit ff5f2a0

Please sign in to comment.