-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
ExportsValues.php
69 lines (60 loc) · 1.77 KB
/
ExportsValues.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
namespace Cerbero\LaravelEnum;
/**
* The exports values trait.
*
*/
trait ExportsValues
{
/**
* Export the given value.
*
* @param mixed $value
* @param int $initialPadding
* @param int $incrementalPadding
* @return string
*/
protected function export($value, int $initialPadding = 0, int $incrementalPadding = 4) : string
{
if (is_array($value)) {
return $this->exportArray($value, $initialPadding, $incrementalPadding);
}
return $this->exportScalar($value);
}
/**
* Format the given scalar value to an exportable string.
*
* @param mixed $value
* @return string
*/
protected function exportScalar($value) : string
{
if (is_null($value)) {
return 'null';
}
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
return is_string($value) ? "'{$value}'" : "{$value}";
}
/**
* Format the given array to an exportable string
*
* @param array $array
* @param int $initialPadding
* @param int $incrementalPadding
* @return string
*/
protected function exportArray(array $array, int $initialPadding = 0, int $incrementalPadding = 4) : string
{
$padding = $initialPadding + $incrementalPadding;
$indentation = str_repeat(' ', $padding);
$exported = [];
foreach ($array as $key => $value) {
$exportedKey = is_int($key) ? '' : "'{$key}' => ";
$exportedValue = $this->export($value, $padding, $incrementalPadding);
$exported[] = $indentation . $exportedKey . $exportedValue;
}
return "[\n" . implode(",\n", $exported) . ",\n" . str_repeat(' ', $initialPadding) . ']';
}
}