1 | <?php |
||
19 | abstract class AbstractDocument implements DocumentInterface |
||
20 | { |
||
21 | /** |
||
22 | * get fields |
||
23 | * |
||
24 | * @return array |
||
25 | */ |
||
26 | abstract protected function getFields(): array; |
||
27 | |||
28 | /** |
||
29 | * to json |
||
30 | * |
||
31 | * @return string |
||
32 | */ |
||
33 | 5 | public function toJson(): string |
|
34 | { |
||
35 | 5 | $document = []; |
|
36 | |||
37 | 5 | foreach ($this->getFields() as $field) { |
|
38 | 4 | $value = $this->$field; |
|
39 | |||
40 | 4 | if (is_null($value)) { |
|
41 | continue; |
||
42 | } |
||
43 | |||
44 | 4 | if (is_array($value)) { |
|
45 | 1 | foreach (array_keys($value) as $key) { |
|
46 | 1 | $document[sprintf('%1$s.%2$s', $field, $key)] = $value[$key]; |
|
47 | } |
||
48 | |||
49 | 1 | continue; |
|
50 | } |
||
51 | |||
52 | 4 | $document[$this->toSnakeCase($field)] = $this->$field; |
|
53 | } |
||
54 | |||
55 | 5 | return json_encode($document); |
|
56 | } |
||
57 | |||
58 | /** |
||
59 | * to snake case |
||
60 | * |
||
61 | * @param string $string |
||
62 | * |
||
63 | * @return string |
||
64 | */ |
||
65 | 4 | private function toSnakeCase(string $string): string |
|
69 | } |
||
70 |