Skip to content

Commit fe7e75f

Browse files
committed
Format generated config files using the short array syntax
1 parent 6862632 commit fe7e75f

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed

lib/internal/Magento/Framework/App/DeploymentConfig/Writer/PhpFormatter.php

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
*/
1212
class PhpFormatter implements FormatterInterface
1313
{
14+
const INDENT = ' ';
15+
1416
/**
1517
* Format deployment configuration.
1618
* If $comments is present, each item will be added
@@ -23,7 +25,7 @@ public function format($data, array $comments = [])
2325
if (!empty($comments) && is_array($data)) {
2426
return "<?php\nreturn array (\n" . $this->formatData($data, $comments) . "\n);\n";
2527
}
26-
return "<?php\nreturn " . var_export($data, true) . ";\n";
28+
return "<?php\nreturn " . $this->varExportShort($data, true) . ";\n";
2729
}
2830

2931
/**
@@ -65,4 +67,27 @@ private function formatData($data, $comments = [], $prefix = ' ')
6567

6668
return var_export($data, true);
6769
}
70+
71+
/**
72+
* If variable to export is an array, format with the php >= 5.4 short array syntax. Otherwise use
73+
* default var_export functionality.
74+
*
75+
* @param mixed $var
76+
* @param integer $depth
77+
* @return string
78+
*/
79+
private function varExportShort($var, $depth=0) {
80+
if (gettype($var) === 'array') {
81+
$indexed = array_keys($var) === range(0, count($var) - 1);
82+
$r = [];
83+
foreach ($var as $key => $value) {
84+
$r[] = str_repeat(self::INDENT, $depth)
85+
. ($indexed ? '' : $this->varExportShort($key) . ' => ')
86+
. $this->varExportShort($value, $depth + 1);
87+
}
88+
return sprintf("[\n%s\n%s]", implode(",\n", $r), str_repeat(self::INDENT, $depth - 1));
89+
}
90+
91+
return var_export($var, TRUE);
92+
}
6893
}

lib/internal/Magento/Framework/App/Test/Unit/DeploymentConfig/Writer/PhpFormatterTest.php

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,13 +129,37 @@ public function formatWithCommentDataProvider()
129129
'ns4' => 'just text',
130130
);
131131
132+
TEXT;
133+
134+
$expectedResult3 = <<<TEXT
135+
<?php
136+
return [
137+
'ns1' => [
138+
's1' => [
139+
's11',
140+
's12'
141+
],
142+
's2' => [
143+
's21',
144+
's22'
145+
]
146+
],
147+
'ns2' => [
148+
's1' => [
149+
's11'
150+
]
151+
],
152+
'ns3' => 'just text',
153+
'ns4' => 'just text'
154+
];
155+
132156
TEXT;
133157
return [
134158
['string', [], "<?php\nreturn 'string';\n"],
135159
['string', ['comment'], "<?php\nreturn 'string';\n"],
136-
[$array, [], "<?php\nreturn " . var_export($array, true) . ";\n"],
137160
[$array, $comments1, $expectedResult1],
138161
[$array, $comments2, $expectedResult2],
162+
[$array, [], $expectedResult3],
139163
];
140164
}
141165
}

0 commit comments

Comments
 (0)