Implode::apply()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 13
nc 4
nop 3
dl 0
loc 22
rs 9.5222
c 1
b 0
f 0
ccs 12
cts 12
cp 1
crap 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Oliverde8\Component\RuleEngine\Rules;
6
7
/**
8
 * Class Implode
9
 *
10
 * @author    de Cramer Oliver<[email protected]>
11
 * @copyright 2018 Oliverde8
12
 * @package Oliverde8\Component\RuleEngine\Rules
13
 */
14
class Implode extends AbstractRule
15
{
16
    /**
17 3
     * @inheritdoc
18
     */
19 3
    public function apply(array $rowData, array &$transformedData, array $options = [])
20 3
    {
21 3
        $subOptions = $options;
22
        unset($subOptions['values']);
23 3
        unset($subOptions['with']);
24 3
25 3
        $data = [];
26
        foreach ($options['values'] as $ruleData) {
27 3
            $value = $this->ruleApplier->apply($rowData, $transformedData, $ruleData, $subOptions);
28 3
29 2
            if (!empty($value)) {
30 2
                if (is_array($value)) {
31
                    foreach ($this->flatten($value) as $v) {
32
                        $data[] = $v;
33 1
                    }
34
                } else {
35
                    $data[] = $value;
36
                }
37
            }
38 3
        }
39
40
        return implode($options['with'], $data);
41
    }
42
43
    /**
44
     * Flatten a multidimensional array.
45
     *
46
     * @param array $array
47
     *
48 2
     * @return \Generator
49
     */
50 2
    protected function flatten(array $array): \Generator
51 2
    {
52 2
        foreach ($array as $v) {
53 2
            if (is_array($v)) {
54
                foreach ($this->flatten($v) as $value) {
55
                    yield $value;
56 2
                };
57
            } else {
58
                yield $v;
59 2
            }
60
        }
61
    }
62
63
    /**
64 3
     * @inheritdoc
65
     */
66 3
    public function validate(array $options): void
67 3
    {
68 3
        $this->requireOption('values', $options);
69
        $this->requireOption('with', $options);
70
    }
71
72
    /**
73 1
     * @inheritdoc
74
     */
75 1
    public function getRuleCode(): string
76
    {
77
        return 'implode';
78
    }
79
}