Completed
Push — master ( b035c8...ddcf44 )
by Paweł
02:10
created

ArrayType::getValue()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
nc 9
nop 0
dl 0
loc 27
rs 8.5546
c 0
b 0
f 0
ccs 15
cts 15
cp 1
crap 7
1
<?php
2
declare(strict_types=1);
3
4
namespace Wszetko\Sitemap\Items\DataTypes;
5
6
use Wszetko\Sitemap\Interfaces\DataType;
7
use Wszetko\Sitemap\Traits\Domain;
8
9
/**
10
 * Class ArrayType
11
 *
12
 * @package Wszetko\Sitemap\Items\DataTypes
13
 */
14
class ArrayType extends AbstractDataType
15
{
16
    /**
17
     * @var \Wszetko\Sitemap\Items\DataTypes\AbstractDataType
18
     */
19
    private $baseDataType;
20
21
    /**
22
     * @var int
23
     */
24
    protected $maxElements;
25
26
    /**
27
     * ArrayType constructor.
28
     *
29
     * @param $name
30
     * @param $dataType
31
     */
32 41
    public function __construct($name, $dataType)
33
    {
34 41
        parent::__construct($name);
35
36 41
        $this->baseDataType = new $dataType($this->getName());
37 41
        $this->value = [];
38 41
    }
39
40
    /**
41
     * @return \Wszetko\Sitemap\Items\DataTypes\AbstractDataType
42
     */
43 41
    public function getBaseDataType(): AbstractDataType
44
    {
45 41
        return $this->baseDataType;
46
    }
47
48
    /**
49
     * @return int|null
50
     */
51 8
    public function getMaxElements(): ?int
52
    {
53 8
        return $this->maxElements;
54
    }
55
56
    /**
57
     * @param int $maxElements
58
     *
59
     * @return self
60
     */
61 34
    public function setMaxElements(int $maxElements): self
62
    {
63 34
        $this->maxElements = $maxElements;
64
65 34
        return $this;
66
    }
67
68
    /**
69
     * @param       $value
70
     * @param mixed ...$parameters
71
     *
72
     * @return \Wszetko\Sitemap\Interfaces\DataType
73
     */
74 2
    public function setValue($value, ...$parameters): DataType
75
    {
76 2
        if (is_array($value)) {
77 2
            foreach ($value as $val) {
78 2
                $this->addValue($val, $parameters);
79
            }
80
        } else {
81 1
            $this->addValue($value, $parameters);
82
        }
83
84 2
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (Wszetko\Sitemap\Items\DataTypes\ArrayType) is incompatible with the return type declared by the interface Wszetko\Sitemap\Interfaces\DataType::setValue of type self.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
85
    }
86
87
    /**
88
     * @param       $value
89
     * @param mixed ...$parameters
90
     */
91 9
    public function addValue($value, ...$parameters)
92
    {
93 9
        if (is_array($value)) {
94 3
            foreach ($value as $val) {
95 3
                $this->addValue($val, $parameters[0]);
96
            }
97
        } else {
98 9
            $var = clone $this->getBaseDataType();
99 9
            $var->setValue($value, $parameters[0]);
100
101 9
            if (!is_null($var->getValue())) {
102 9
                $this->value[] = $var;
103
            }
104
        }
105 9
    }
106
107
    /**
108
     * @return mixed
109
     */
110 8
    public function getValue()
111
    {
112 8
        $values = parent::getValue();
113
114 8
        if (empty($values)) {
115 2
            return null;
116
        }
117
118 8
        $result = [];
119
120 8
        foreach ($values as $element) {
0 ignored issues
show
Bug introduced by
The expression $values of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
121 8
            $this->propagateDomain($element);
122 8
            $value = $element->getValue();
123
124 8
            if (is_array($value) && !empty(array_values($value)[0])) {
125 2
                $result[array_key_first($value)] = array_values($value)[0];
126 6
            } elseif (!empty($value)) {
127 8
                $result[] = $value;
128
            }
129
        }
130
131 8
        if ($this->getMaxElements()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->getMaxElements() of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
132 4
            $result = array_slice($result, 0, $this->getMaxElements());
133
        }
134
135 8
        return $result;
136
    }
137
}