1 | <?php |
||
21 | class JsonFormatter implements FormatterInterface |
||
22 | { |
||
23 | use RowProcessor; |
||
24 | use InvokeFormatter; |
||
25 | use TraversableTrait; |
||
26 | |||
27 | const JSON_ARRAY_START = '['; |
||
28 | const JSON_ARRAY_END = ']' . PHP_EOL; |
||
29 | const JSON_ARRAY_SEPARATOR = ',' . PHP_EOL; |
||
30 | |||
31 | /** |
||
32 | * @var JsonFormatInterface |
||
33 | */ |
||
34 | private $format; |
||
35 | |||
36 | /** |
||
37 | * @var string |
||
38 | */ |
||
39 | private $linePostfix; |
||
40 | |||
41 | /** |
||
42 | * @var int |
||
43 | */ |
||
44 | private $encodeOptions; |
||
45 | |||
46 | /** |
||
47 | * JsonFormatter constructor. |
||
48 | * |
||
49 | * @param JsonFormatInterface $format |
||
50 | */ |
||
51 | 7 | public function __construct(JsonFormatInterface $format) |
|
52 | { |
||
53 | 7 | $this->addProcessor(new DateTimeProcessor()); |
|
54 | 7 | $this->format = $format; |
|
55 | 7 | $this->linePostfix = $format->isSingleBlock() ? static::JSON_ARRAY_SEPARATOR : PHP_EOL; |
|
56 | 7 | $this->encodeOptions = $format->getJsonEncodeOptions(); |
|
57 | |||
58 | // If the json is a blob on each line, turn off pretty print to ensure it is all on a single line |
||
59 | 7 | if ($format->isEachLine()) { |
|
60 | 4 | $this->encodeOptions &= ~JSON_PRETTY_PRINT; |
|
61 | } |
||
62 | 7 | } |
|
63 | |||
64 | /** |
||
65 | * @param array|Traversable $row |
||
66 | * |
||
67 | * @return string |
||
68 | */ |
||
69 | 6 | public function format($row) |
|
76 | |||
77 | /** |
||
78 | * Return an initial block if required |
||
79 | * |
||
80 | * @return string |
||
81 | */ |
||
82 | 5 | public function getInitialBlock() |
|
90 | |||
91 | /** |
||
92 | * Return a closing block if required |
||
93 | * |
||
94 | * @return string |
||
95 | */ |
||
96 | 5 | public function getClosingBlock() |
|
104 | |||
105 | /** |
||
106 | * Get a separator between each row |
||
107 | * |
||
108 | * @return string |
||
109 | */ |
||
110 | 5 | public function getRowSeparator() |
|
114 | } |
||
115 |