Skip to content

Commit e7804a2

Browse files
committed
Create JsonParsableStringifier
1 parent 9e25a31 commit e7804a2

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
/*
4+
* This file is part of Respect/Stringifier.
5+
*
6+
* (c) Henrique Moody <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the "LICENSE.md"
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace Respect\Stringifier\Stringifiers;
15+
16+
use const JSON_UNESCAPED_UNICODE;
17+
use const JSON_UNESCAPED_SLASHES;
18+
use function json_encode;
19+
use Respect\Stringifier\Stringifier;
20+
21+
/**
22+
* Converts any value into JSON parsable string representation.
23+
*
24+
* @author Henrique Moody <[email protected]>
25+
*/
26+
final class JsonParsableStringifier implements Stringifier
27+
{
28+
/**
29+
* {@inheritdoc}
30+
*/
31+
public function stringify($raw, int $depth): ?string
32+
{
33+
$string = json_encode($raw, (JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION));
34+
if (false === $string) {
35+
return null;
36+
}
37+
38+
return $string;
39+
}
40+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<?php
2+
3+
/*
4+
* This file is part of Respect/Stringifier.
5+
*
6+
* (c) Henrique Moody <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the "LICENSE.md"
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace Respect\Stringifier\Test\Stringifiers;
15+
16+
use Respect\Stringifier\Stringifiers\JsonParsableStringifier;
17+
use PHPUnit\Framework\TestCase;
18+
use function tmpfile;
19+
20+
/**
21+
* @covers \Respect\Stringifier\Stringifiers\JsonParsableStringifier
22+
* @author Henrique Moody <[email protected]>
23+
*/
24+
final class JsonParsableStringifierTest extends TestCase
25+
{
26+
/**
27+
* @test
28+
*/
29+
public function shouldReturnNullWhenNotPossibleToConvertToAJsonParsableString(): void
30+
{
31+
$raw = tmpfile();
32+
$depth = 0;
33+
34+
$jsonSerializableStringifier = new JsonParsableStringifier();
35+
36+
self::assertNull($jsonSerializableStringifier->stringify($raw, $depth));
37+
}
38+
39+
/**
40+
* @test
41+
*/
42+
public function shouldConvertRawValueToAJsonParsableString(): void
43+
{
44+
$raw = 'É uma \' " string';
45+
$depth = 0;
46+
47+
$expected = '"É uma \' \" string"';
48+
49+
$jsonSerializableStringifier = new JsonParsableStringifier();
50+
51+
self::assertSame($expected, $jsonSerializableStringifier->stringify($raw, $depth));
52+
}
53+
}

0 commit comments

Comments
 (0)