| Total Complexity | 16 |
| Total Lines | 108 |
| Duplicated Lines | 0 % |
| Coverage | 0% |
| Changes | 0 | ||
| 1 | <?php |
||
| 7 | class IniWriter |
||
| 8 | { |
||
| 9 | |||
| 10 | /** |
||
| 11 | * @param string $filename |
||
| 12 | * @param array $config |
||
| 13 | * @param string $header |
||
| 14 | * |
||
| 15 | * @return int |
||
| 16 | */ |
||
| 17 | public function toFile($filename, array $config, $header = null) |
||
| 18 | { |
||
| 19 | $ini = $this->toString($config, $header); |
||
| 20 | return File::put($filename, $ini); |
||
| 21 | } |
||
| 22 | |||
| 23 | /** |
||
| 24 | * @param array $config |
||
| 25 | * @param string|null $header |
||
| 26 | * |
||
| 27 | * @return string |
||
| 28 | */ |
||
| 29 | public function toString(array $config, $header = null) |
||
| 30 | { |
||
| 31 | $ini = !empty($header) ? $header . PHP_EOL : ''; |
||
| 32 | |||
| 33 | uasort($config, function ($first, $second) { |
||
| 34 | if (is_array($first)) { |
||
| 35 | return 1; |
||
| 36 | } |
||
| 37 | |||
| 38 | if (is_array($second)) |
||
| 39 | { |
||
| 40 | return -1; |
||
| 41 | } |
||
| 42 | |||
| 43 | return 0; |
||
| 44 | }); |
||
| 45 | |||
| 46 | $names = array_keys($config); |
||
| 47 | |||
| 48 | foreach ($names as $name) |
||
| 49 | { |
||
| 50 | $section = $config[$name]; |
||
| 51 | |||
| 52 | if (!is_array($section)) |
||
| 53 | { |
||
| 54 | $ini .= $name . ' = ' . $this->encodeValue($section) . PHP_EOL; |
||
| 55 | continue; |
||
| 56 | } |
||
| 57 | |||
| 58 | if (empty($section)) |
||
| 59 | { |
||
| 60 | continue; |
||
| 61 | } |
||
| 62 | |||
| 63 | if (!empty($ini)) |
||
| 64 | { |
||
| 65 | $ini .= PHP_EOL; |
||
| 66 | } |
||
| 67 | |||
| 68 | $ini .= "[$name]" . PHP_EOL; |
||
| 69 | |||
| 70 | foreach ($section as $option => $value) |
||
| 71 | { |
||
| 72 | if (is_numeric($option)) |
||
| 73 | { |
||
| 74 | $option = $name; |
||
| 75 | $value = (array)$value; |
||
| 76 | } |
||
| 77 | |||
| 78 | if (is_array($value)) |
||
| 79 | { |
||
| 80 | foreach ($value as $key => $currentValue) |
||
| 81 | { |
||
| 82 | $ini .= $option . '[' . $key . '] = ' . $this->encodeValue($currentValue) . PHP_EOL; |
||
| 83 | } |
||
| 84 | } |
||
| 85 | else |
||
| 86 | { |
||
| 87 | $ini .= $option . ' = ' . $this->encodeValue($value) . PHP_EOL; |
||
| 88 | } |
||
| 89 | } |
||
| 90 | |||
| 91 | $ini .= "\n"; |
||
| 92 | } |
||
| 93 | |||
| 94 | return $ini; |
||
| 95 | } |
||
| 96 | |||
| 97 | /** |
||
| 98 | * @param $value |
||
| 99 | * |
||
| 100 | * @return int|string |
||
| 101 | */ |
||
| 102 | protected function encodeValue($value) |
||
| 115 | } |
||
| 116 | |||
| 117 | } |
||
| 118 |