EnumeratedStringToArrayTransformer::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 2
nop 1
crap 3
1
<?php
2
3
namespace TreeHouse\Feeder\Modifier\Data\Transformer;
4
5
use TreeHouse\Feeder\Exception\TransformationFailedException;
6
7
/**
8
 * Transforms a string to an array, using one or more delimiters.
9
 */
10
class EnumeratedStringToArrayTransformer implements TransformerInterface
11
{
12
    /**
13
     * @var array
14
     */
15
    protected $delimiters;
16
17
    /**
18
     * @var string
19
     */
20
    protected $regex;
21
22
    /**
23
     * @param array $delimiters
24
     */
25 18
    public function __construct(array $delimiters = [])
26
    {
27 18
        $this->delimiters = !empty($delimiters) ? $delimiters : [','];
28 18
        $this->regex = sprintf('/(%s)+/', implode('|', array_map(function ($delimiter) {
29 18
            if (mb_strlen($delimiter) > 1) {
30
                // treat it as a word
31 18
                return '\b' . preg_quote($delimiter, '/') . '\b';
32
            }
33
34 18
            return preg_quote($delimiter, '/');
35 18
        }, $this->delimiters)));
36 18
    }
37
38
    /**
39
     * @inheritdoc
40
     */
41 18
    public function transform($value)
42
    {
43
        // only transform when we have something to transform
44 18
        if (is_null($value)) {
45 2
            return $value;
46
        }
47
48 16
        if (is_array($value)) {
49 2
            return $value;
50
        }
51
52 14 View Code Duplication
        if (!is_scalar($value)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
53 2
            throw new TransformationFailedException(
54 2
                sprintf('Expected a scalar value to transform, got %s instead.', var_export($value, true))
55 2
            );
56
        }
57
58 12
        return array_map('trim', preg_split($this->regex, $value, null, PREG_SPLIT_NO_EMPTY));
59
    }
60
}
61