| 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 | 9 | public function toJson(): string |
|
| 34 | { |
||
| 35 | 9 | $document = []; |
|
| 36 | |||
| 37 | 9 | foreach ($this->getFields() as $field) { |
|
| 38 | 8 | $value = $this->$field; |
|
| 39 | |||
| 40 | 8 | if (is_null($value)) { |
|
| 41 | continue; |
||
| 42 | } |
||
| 43 | |||
| 44 | 8 | if (is_array($value)) { |
|
| 45 | 2 | foreach (array_keys($value) as $key) { |
|
| 46 | 2 | $document[sprintf('%1$s.%2$s', $field, $key)] = $value[$key]; |
|
| 47 | } |
||
| 48 | |||
| 49 | 2 | continue; |
|
| 50 | } |
||
| 51 | |||
| 52 | 8 | $document[$this->toSnakeCase($field)] = $this->$field; |
|
| 53 | } |
||
| 54 | |||
| 55 | 9 | return json_encode($document); |
|
| 56 | } |
||
| 57 | |||
| 58 | /** |
||
| 59 | * to snake case |
||
| 60 | * |
||
| 61 | * @param string $string |
||
| 62 | * |
||
| 63 | * @return string |
||
| 64 | */ |
||
| 65 | 8 | private function toSnakeCase(string $string): string |
|
| 69 | } |
||
| 70 |