ArrayProxyTrait::castArrayToString()   B
last analyzed

Complexity

Conditions 8
Paths 8

Size

Total Lines 27
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 27
ccs 20
cts 20
cp 1
rs 8.4444
cc 8
nc 8
nop 1
crap 8
1
<?php
2
3
/**
4
 * @author Marwan Al-Soltany <[email protected]>
5
 * @copyright Marwan Al-Soltany 2020
6
 * For the full copyright and license information, please view
7
 * the LICENSE file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace MAKS\AmqpAgent\Helper;
13
14
use stdClass;
15
use ReflectionObject;
16
17
/**
18
 * A trait containing methods for for manipulating and working with arrays.
19
 * @since 2.0.0
20
 */
21
trait ArrayProxyTrait
22
{
23
    /**
24
     * Gets a value from an array via dot-notation representation.
25
     * @param array &$array The array to get the value from.
26
     * @param string $key The dotted key representation.
27
     * @param mixed $default [optional] The default fallback value.
28
     * @return mixed The requested value if found otherwise the default parameter.
29
     */
30 4
    public static function getArrayValueByKey(array &$array, string $key, $default = null)
31
    {
32 4
        if (!strlen($key) || !count($array)) {
33 1
            return $default;
34
        }
35
36 4
        $data = &$array;
37
38 4
        if (strpos($key, '.') !== false) {
39 4
            $parts = explode('.', $key);
40
41 4
            foreach ($parts as $part) {
42 4
                if (!array_key_exists($part, $data)) {
43 2
                    return $default;
44
                }
45
46 4
                $data = &$data[$part];
47
            }
48
49 4
            return $data;
50
        }
51
52 4
        return array_key_exists($key, $data) ? $data[$key] : $default;
53
    }
54
55
    /**
56
     * Sets a value of an array via dot-notation representation.
57
     * @param array $array The array to set the value in.
58
     * @param string $key The string key representation.
59
     * @param mixed $value The value to set.
60
     * @return bool True on success.
61
     */
62 2
    public static function setArrayValueByKey(array &$array, string $key, $value): bool
63
    {
64 2
        if (!strlen($key)) {
65 1
            return false;
66
        }
67
68 2
        $parts = explode('.', $key);
69 2
        $lastPart = array_pop($parts);
70
71 2
        $data = &$array;
72
73 2
        if (!empty($parts)) {
74 2
            foreach ($parts as $part) {
75 2
                if (!isset($data[$part])) {
76 2
                    $data[$part] = [];
77
                }
78
79 2
                $data = &$data[$part];
80
            }
81
        }
82
83 2
        $data[$lastPart] = $value;
84
85 2
        return true;
86
    }
87
88
    /**
89
     * Returns a string representation of an array by imploding it recursively with common formatting of data-types.
90
     * @param array $array The array to implode.
91
     * @return string
92
     */
93 4
    public static function castArrayToString(array $array): string
94
    {
95 4
        $pieces = [];
96
97 4
        foreach ($array as $item) {
98
            switch (true) {
99 2
                case (is_array($item)):
100 1
                    $pieces[] = self::castArrayToString($item);
101 1
                    break;
102 2
                case (is_object($item)):
103 1
                    $pieces[] = get_class($item) ?? 'object';
104 1
                    break;
105 2
                case (is_string($item)):
106 2
                    $pieces[] = "'{$item}'";
107 2
                    break;
108 1
                case (is_bool($item)):
109 1
                    $pieces[] = $item ? 'true' : 'false';
110 1
                    break;
111 1
                case (is_null($item)):
112 1
                    $pieces[] = 'null';
113 1
                    break;
114
                default:
115 2
                    $pieces[] = $item;
116
            }
117
        }
118
119 4
        return '[' . implode(', ', $pieces) . ']';
120
    }
121
122
    /**
123
     * Converts (casts) an array to an object (stdClass).
124
     * @param array $array The array to convert.
125
     * @param bool $useJson [optional] Whether to use json_decode/json_encode to cast the array, default is via iteration.
126
     * @return stdClass The result object.
127
     */
128 2
    public static function castArrayToObject(array $array, bool $useJson = false): stdClass
129
    {
130 2
        if ($useJson) {
131 1
            return json_decode(json_encode($array));
132
        }
133
134 1
        $stdClass = new stdClass();
135
136 1
        foreach ($array as $key => $value) {
137 1
            $stdClass->{$key} = is_array($value)
138 1
                ? self::castArrayToObject($value, $useJson)
139 1
                : $value;
140
        }
141
142 1
        return $stdClass;
143
    }
144
145
    /**
146
     * Converts (casts) an object to an associative array.
147
     * @param object $object The object to convert.
148
     * @param bool $useJson [optional] Whether to use json_decode/json_encode to cast the object, default is via reflection.
149
     * @return array The result array.
150
     */
151 2
    public static function castObjectToArray($object, bool $useJson = false): array
152
    {
153 2
        if ($useJson) {
154 1
            return json_decode(json_encode($object), true);
155
        }
156
157 1
        $array = [];
158
159 1
        $reflectionClass = new ReflectionObject($object);
160 1
        foreach ($reflectionClass->getProperties() as $property) {
161 1
            $property->setAccessible(true);
162 1
            $array[$property->getName()] = $property->getValue($object);
163 1
            $property->setAccessible(false);
164
        }
165
166 1
        return $array;
167
    }
168
}
169