Serializer::packArray()   B
last analyzed

Complexity

Conditions 10
Paths 46

Size

Total Lines 53

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 10

Importance

Changes 0
Metric Value
cc 10
nc 46
nop 2
dl 0
loc 53
rs 7.1587
c 0
b 0
f 0
ccs 30
cts 30
cp 1
crap 10

How to fix   Long Method    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
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
9
namespace Spiral\Support;
10
11
use Spiral\Support\Exceptions\SerializeException;
12
use Spiral\Support\Serializer\DeclarationInterface;
13
14
/**
15
 * Provides very simple api for serializing values. Attention, this is helper class, it's not
16
 * intended for processing user input.
17
 */
18
class Serializer
19
{
20
    /**
21
     * Fixed 4 spaces indent.
22
     */
23
    const INDENT = DeclarationInterface::INDENT;
24
25
    /**
26
     * Serialize array.
27
     *
28
     * @param mixed $array
29
     *
30
     * @return string
31
     */
32 8
    public function serialize($array): string
33
    {
34 8
        if (is_array($array)) {
35 8
            return $this->packArray($array);
36
        }
37
38 4
        return $this->packValue($array);
39
    }
40
41
    /**
42
     * @param array $array
43
     * @param int   $level
44
     *
45
     * @return string
46
     */
47 8
    protected function packArray(array $array, int $level = 0): string
48
    {
49 8
        if ($array === []) {
50 1
            return '[]';
51
        }
52
53
        //Delimiters between rows and sub-arrays.
54 7
        $subIndent = "\n" . str_repeat(self::INDENT, $level + 2);
55 7
        $keyIndent = "\n" . str_repeat(self::INDENT, $level + 1);
56
57
        //No keys for associated array
58 7
        $associated = array_diff_key($array, array_keys(array_keys($array)));
59
60 7
        $result = [];
61 7
        $innerIndent = 0;
62 7
        if (!empty($associated)) {
63 4
            foreach ($array as $key => $value) {
64
                //Based on biggest key length
65 4
                $innerIndent = max(strlen(var_export($key, true)), $innerIndent);
66
            }
67
        }
68
69 7
        foreach ($array as $key => $value) {
70 7
            $prefix = '';
71 7
            if (!empty($associated)) {
72
                //Key prefix
73 4
                $prefix = str_pad(
74 4
                        var_export($key, true),
75 4
                        $innerIndent, ' ',
76 4
                        STR_PAD_RIGHT
77 4
                    ) . " => ";
78
            }
79
80 7
            if (!is_array($value)) {
81 7
                $result[] = $prefix . $this->packValue($value);
82 7
                continue;
83
            }
84
85 4
            if ($value === []) {
86 1
                $result[] = $prefix . "[]";
87 1
                continue;
88
            }
89
90 3
            $subArray = $this->packArray($value, $level + 1);
91 3
            $result[] = $prefix . "[{$subIndent}" . $subArray . "{$keyIndent}]";
92
        }
93
94 7
        if ($level !== 0) {
95 3
            return $result ? join(",{$keyIndent}", $result) : "";
96
        }
97
98 7
        return "[{$keyIndent}" . join(",{$keyIndent}", $result) . "\n]";
99
    }
100
101
    /**
102
     * Pack array key value into string.
103
     *
104
     * @param mixed $value
105
     *
106
     * @return string
107
     * @throws SerializeException
108
     */
109 7
    protected function packValue($value): string
110
    {
111 7
        if ($value instanceof DeclarationInterface) {
112
            //No indentation here
113 1
            return $value->render();
114
        }
115
116 7
        if (is_null($value)) {
117 4
            return "null";
118
        }
119
120 7
        if (is_bool($value)) {
121 3
            return ($value ? "true" : "false");
122
        }
123
124 7
        if (is_object($value) && method_exists($value, '__set_state')) {
125
            return var_export($value, true);
126
        }
127
128 7
        if (!is_string($value) && !is_numeric($value)) {
129
            print_r($value);
130
            throw new SerializeException("Unable to pack non scalar value");
131
        }
132
133 7
        if (is_string($value) && class_exists($value)) {
134 1
            $reflection = new \ReflectionClass($value);
135
136 1
            return '\\' . $reflection->getName() . '::class';
137
        }
138
139 7
        return var_export($value, true);
140
    }
141
}