Completed
Branch dev (b63562)
by Marwan
01:48
created

ArrayProxyTrait::castArrayToString()   B

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
 * @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 4
    public static function getArrayValueByKey(array &$array, string $key, $default = null)
28
    {
29 4
        if (!strlen($key) || !count($array)) {
30 1
            return $default;
31
        }
32
33 4
        $data = &$array;
34
35 4
        if (strpos($key, '.') !== false) {
36 4
            $parts = explode('.', $key);
37
38 4
            foreach ($parts as $part) {
39 4
                if (!array_key_exists($part, $data)) {
40 2
                    return $default;
41
                }
42
43 4
                $data = &$data[$part];
44
            }
45
46 4
            return $data;
47
        }
48
49 4
        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 2
    public static function setArrayValueByKey(array &$array, string $key, $value): bool
60
    {
61 2
        if (!strlen($key)) {
62 1
            return false;
63
        }
64
65 2
        $parts = explode('.', $key);
66 2
        $lastPart = array_pop($parts);
67
68 2
        $data = &$array;
69
70 2
        if (!empty($parts)) {
71 2
            foreach ($parts as $part) {
72 2
                if (!isset($data[$part])) {
73 2
                    $data[$part] = [];
74
                }
75
76 2
                $data = &$data[$part];
77
            }
78
        }
79
80 2
        $data[$lastPart] = $value;
81
82 2
        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 4
    public static function castArrayToString(array $array): string
91
    {
92 4
        $pieces = [];
93
94 4
        foreach ($array as $item) {
95
            switch (true) {
96 2
                case (is_array($item)):
97 1
                    $pieces[] = self::castArrayToString($item);
98 1
                    break;
99 2
                case (is_object($item)):
100 1
                    $pieces[] = get_class($item) ?? 'object';
101 1
                    break;
102 2
                case (is_string($item)):
103 2
                    $pieces[] = "'{$item}'";
104 2
                    break;
105 1
                case (is_bool($item)):
106 1
                    $pieces[] = $item ? 'true' : 'false';
107 1
                    break;
108 1
                case (is_null($item)):
109 1
                    $pieces[] = 'null';
110 1
                    break;
111
                default:
112 1
                    $pieces[] = $item;
113
            }
114
        }
115
116 4
        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 2
    public static function castArrayToObject(array $array, bool $useJson = false): stdClass
126
    {
127 2
        if ($useJson) {
128 1
            return json_decode(json_encode($array));
129
        }
130
131 1
        $stdClass = new stdClass();
132
133 1
        foreach ($array as $key => $value) {
134 1
            $stdClass->{$key} = is_array($value)
135 1
                ? self::arrayToObject($value, $useJson)
0 ignored issues
show
Bug introduced by
The method arrayToObject() does not exist on MAKS\AmqpAgent\Helper\ArrayProxyTrait. Did you maybe mean castArrayToObject()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

135
                ? self::/** @scrutinizer ignore-call */ arrayToObject($value, $useJson)

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
136 1
                : $value;
137
        }
138
139 1
        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 2
    public static function castObjectToArray($object, bool $useJson = false): array
149
    {
150 2
        if ($useJson) {
151 1
            return json_decode(json_encode($object), true);
152
        }
153
154 1
        $array = [];
155
156 1
        $reflectionClass = new ReflectionObject($object);
157 1
        foreach ($reflectionClass->getProperties() as $property) {
158 1
            $property->setAccessible(true);
159 1
            $array[$property->getName()] = $property->getValue($object);
160 1
            $property->setAccessible(false);
161
        }
162
163 1
        return $array;
164
    }
165
}
166