Completed
Push — master ( 59dd4d...b5d47e )
by Marwan
15s queued 11s
created

ArrayProxyTrait::castArrayToString()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 27
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

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