@@ -9,22 +9,25 @@ final class Encode
9
9
private const ARRAY_START = '[ ' ;
10
10
private const ARRAY_END = '] ' ;
11
11
12
- public function __invoke (iterable $ schema , int $ level = 0 ): \Generator
12
+ public static function from (iterable $ schema , bool $ pretty = false ): \Generator
13
13
{
14
+ if ($ pretty ) {
15
+ yield from self ::pretty ($ schema );
16
+ return ;
17
+ }
18
+
14
19
$ key = $ schema instanceof \Iterator ? $ schema ->key () : key ($ schema );
15
20
if (null === $ key ) {
16
21
yield '[] ' ;
17
22
return ;
18
23
}
19
24
$ isHash = is_string ($ key );
20
25
21
- yield ($ isHash ? self ::HASH_START : self ::ARRAY_START ). PHP_EOL ;
26
+ yield ($ isHash ? self ::HASH_START : self ::ARRAY_START );
22
27
23
- $ indentation = str_repeat (' ' , $ level );
24
28
$ isFirst = true ;
25
29
foreach ($ schema as $ key => $ child ) {
26
- $ comma = $ isFirst ? '' : ', ' .PHP_EOL ;
27
- yield $ comma .$ indentation ;
30
+ yield $ isFirst ? '' : ', ' ;
28
31
$ isFirst = false ;
29
32
30
33
if ($ isHash ) {
@@ -35,18 +38,23 @@ public function __invoke(iterable $schema, int $level = 0): \Generator
35
38
$ child = $ child ();
36
39
}
37
40
if (is_iterable ($ child )) {
38
- yield from ( $ this )( $ child, $ level + 1 );
41
+ yield from self :: from ( $ child );
39
42
continue ;
40
43
}
41
44
if (is_object ($ child )) {
42
45
if ($ child instanceof \JsonSerializable) {
43
- yield from ( $ this )( $ child ->jsonSerialize (), $ level + 1 );
46
+ yield from self :: from ( $ child ->jsonSerialize ());
44
47
continue ;
45
48
}
46
49
}
47
50
yield json_encode ($ child ).PHP_EOL ;
48
51
}
49
52
50
- yield PHP_EOL .$ indentation .($ isHash ? self ::HASH_END : self ::ARRAY_END );
53
+ yield ($ isHash ? self ::HASH_END : self ::ARRAY_END );
54
+ }
55
+
56
+ public static function pretty (iterable $ schema ): \Generator
57
+ {
58
+ yield from [json_encode (json_decode (implode (iterator_to_array (self ::from ($ schema ), false ))), JSON_PRETTY_PRINT )];
51
59
}
52
60
}
0 commit comments