Flatten::flattenValue()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 6
c 1
b 0
f 0
nc 8
nop 2
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 4
rs 10
1
<?php
2
/**
3
 * This file is part of the sauls/helpers package.
4
 *
5
 * @author    Saulius Vaičeliūnas <[email protected]>
6
 * @link      http://saulius.vaiceliunas.lt
7
 * @copyright 2018
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
namespace Sauls\Component\Helper\Operation\ArrayOperation;
14
15
class Flatten implements FlattenInterface
16
{
17
    /**
18
     * @var MergeInterface
19
     */
20
    private $arrayMergeOperation;
21
22 1
    public function __construct(MergeInterface $arrayMergeOperation)
23
    {
24 1
        $this->arrayMergeOperation = $arrayMergeOperation;
25 1
    }
26
27
    /**
28
     * @throws \RuntimeException
29
     */
30 7
    public function execute(array $array): array
31
    {
32
        try {
33 7
            $result = [];
34 7
            foreach (\array_keys($array) as $key) {
35 6
                $this->flattenValue($array[$key], $result);
36
            }
37
38 6
            return \array_values(\array_unique($result));
39 1
        } catch (\Throwable $t) {
40 1
            throw new \RuntimeException($t->getMessage());
41
        }
42
    }
43
44 6
    private function flattenValue($value, array &$result): void
45
    {
46 6
        if (\is_scalar($value)) {
47 6
            $result[] = $value;
48
        }
49
50 6
        if (\is_array($value)) {
51 4
            $result = $this->arrayMergeOperation->execute($result, $this->execute($value));
52
        }
53
54 6
        if (\is_object($value)) {
55 2
            $result[] = (string)$value;
56
        }
57 6
    }
58
}
59