Passed
Push — master ( d8a269...27cede )
by Alexander
02:46 queued 01:01
created

ArrayItem::renderValue()   C

Complexity

Conditions 12
Paths 10

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 17
c 1
b 0
f 0
nc 10
nop 1
dl 0
loc 26
ccs 0
cts 26
cp 0
crap 156
rs 6.9666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Cycle\Helper;
6
7
final class ArrayItem
8
{
9
    public ?string $key;
10
    /** @var mixed */
11
    public $value;
12
    public bool $wrapValue = true;
13
    public bool $wrapKey;
14
    public function __construct(?string $key, $value = null, bool $wrapKey = false)
15
    {
16
        $this->key = $key;
17
        $this->value = $value;
18
        $this->wrapKey = $wrapKey;
19
    }
20
    public function __toString()
21
    {
22
        $result = '';
23
        if ($this->key !== null) {
24
            $result = $this->wrapKey ? "'{$this->key}' => " : "{$this->key} => ";
25
        }
26
        return $result . $this->renderValue($this->value);
27
    }
28
    private function renderValue($value)
29
    {
30
        if ($value === null) {
31
            return 'null';
32
        }
33
        if (is_bool($value)) {
34
            return $value ? 'true' : 'false';
35
        }
36
        if (is_array($value)) {
37
            if (count($value) === 0) {
38
                return '[]';
39
            }
40
            $result = '[';
41
            foreach ($value as $key => $item) {
42
                $result .= "\n";
43
                if (!$item instanceof ArrayItem) {
44
                    $result .= is_int($key) ? "{$key} => " : "'{$key}' => ";
45
                }
46
                $result .= $this->renderValue($item) . ',';
47
            }
48
            return str_replace("\n", "\n    ", $result) .  "\n]";
49
        }
50
        if (!$this->wrapValue || is_int($value) || $value instanceof ArrayItem) {
51
            return (string)$value;
52
        }
53
        return "'" . addslashes((string)$value) . "'";
54
    }
55
}
56