|
| 1 | +<?php |
| 2 | + |
| 3 | + |
| 4 | +namespace TheCodingMachine\FluidSchema; |
| 5 | + |
| 6 | + |
| 7 | +use function addslashes; |
| 8 | +use function array_map; |
| 9 | +use function implode; |
| 10 | +use function is_array; |
| 11 | +use function is_numeric; |
| 12 | +use function is_string; |
| 13 | +use function var_export; |
| 14 | + |
| 15 | +class DoctrineAnnotationDumper |
| 16 | +{ |
| 17 | + /** |
| 18 | + * Write a string representing the parameter passed in. |
| 19 | + * @param mixed $item |
| 20 | + */ |
| 21 | + public static function exportValues($item): string |
| 22 | + { |
| 23 | + if ($item === null) { |
| 24 | + return ''; |
| 25 | + } |
| 26 | + if ($item === []) { |
| 27 | + return '({})'; |
| 28 | + } |
| 29 | + return '('.self::innerExportValues($item, true).')'; |
| 30 | + } |
| 31 | + |
| 32 | + private static function innerExportValues($item, bool $first): string |
| 33 | + { |
| 34 | + if ($item === null) { |
| 35 | + return 'null'; |
| 36 | + } |
| 37 | + if (is_string($item)) { |
| 38 | + return '"'.addslashes($item).'"'; |
| 39 | + } |
| 40 | + if (is_numeric($item)) { |
| 41 | + return $item; |
| 42 | + } |
| 43 | + if (is_bool($item)) { |
| 44 | + return $item ? 'true' : 'false'; |
| 45 | + } |
| 46 | + if (is_array($item)) { |
| 47 | + if (self::isAssoc($item)) { |
| 48 | + if ($first) { |
| 49 | + array_walk($item, function(&$value, $key) { |
| 50 | + $value = $key.' = '.self::innerExportValues($value, false); |
| 51 | + }); |
| 52 | + } else { |
| 53 | + array_walk($item, function(&$value, $key) { |
| 54 | + $value = '"'.addslashes($key).'":'.self::innerExportValues($value, false); |
| 55 | + }); |
| 56 | + } |
| 57 | + $result = implode(', ', $item); |
| 58 | + if (!$first) { |
| 59 | + $result = '{'.$result.'}'; |
| 60 | + } |
| 61 | + return $result; |
| 62 | + } else { |
| 63 | + array_walk($item, function(&$value, $key) { |
| 64 | + $value = self::innerExportValues($value, false); |
| 65 | + }); |
| 66 | + $result = implode(', ', $item); |
| 67 | + if (!$first) { |
| 68 | + $result = '{'.$result.'}'; |
| 69 | + } |
| 70 | + return $result; |
| 71 | + } |
| 72 | + } |
| 73 | + throw new \RuntimeException('Cannot serialize value in Doctrine annotation.'); |
| 74 | + } |
| 75 | + |
| 76 | + private static function isAssoc(array $arr): bool |
| 77 | + { |
| 78 | + return array_keys($arr) !== range(0, count($arr) - 1); |
| 79 | + } |
| 80 | +} |
0 commit comments