flattenObjectsWithSingleKeyScalars()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 10
rs 9.2
cc 4
eloc 5
nc 4
nop 1
1
<?php
2
3
/**
4
 * Author: Nil Portugués Calderó <[email protected]>
5
 * Date: 8/14/15
6
 * Time: 8:48 PM.
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace NilPortugues\Api\Hal\Helpers;
13
14
use NilPortugues\Api\Hal\JsonTransformer;
15
16
final class AttributeFormatterHelper
17
{
18
    /**
19
     * Simplifies the data structure by removing an array level if data is scalar and has one element in array.
20
     *
21
     * @param array $array
22
     */
23
    public static function flattenObjectsWithSingleKeyScalars(array &$array)
24
    {
25
        if (1 === \count($array) && \is_scalar(\end($array))) {
26
            $array = \array_pop($array);
27
        }
28
29
        if (\is_array($array)) {
30
            self::loopScalarValues($array, 'flattenObjectsWithSingleKeyScalars');
31
        }
32
    }
33
34
    /**
35
     * @param array  $array
36
     * @param string $method
37
     */
38
    private static function loopScalarValues(array &$array, $method)
39
    {
40
        foreach ($array as $propertyName => &$value) {
41
            if (\is_array($value) && JsonTransformer::LINKS_KEY !== $propertyName) {
42
                self::$method($value);
43
            }
44
        }
45
    }
46
}
47