EnumeratedStringToArrayTransformer   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 51
Duplicated Lines 9.8 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 5
loc 51
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 3
A transform() 5 19 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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