Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
namespace JmesPath;
3
 
4
class Utils
5
{
6
    public static $typeMap = [
7
        'boolean' => 'boolean',
8
        'string'  => 'string',
9
        'NULL'    => 'null',
10
        'double'  => 'number',
11
        'float'   => 'number',
12
        'integer' => 'number'
13
    ];
14
 
15
    /**
16
     * Returns true if the value is truthy
17
     *
18
     * @param mixed $value Value to check
19
     *
20
     * @return bool
21
     */
22
    public static function isTruthy($value)
23
    {
24
        if (!$value) {
25
            return $value === 0 || $value === '0';
26
        } elseif ($value instanceof \stdClass) {
27
            return (bool) get_object_vars($value);
28
        } else {
29
            return true;
30
        }
31
    }
32
 
33
    /**
34
     * Gets the JMESPath type equivalent of a PHP variable.
35
     *
36
     * @param mixed $arg PHP variable
37
     * @return string Returns the JSON data type
38
     * @throws \InvalidArgumentException when an unknown type is given.
39
     */
40
    public static function type($arg)
41
    {
42
        $type = gettype($arg);
43
        if (isset(self::$typeMap[$type])) {
44
            return self::$typeMap[$type];
45
        } elseif ($type === 'array') {
46
            if (empty($arg)) {
47
                return 'array';
48
            }
49
            reset($arg);
50
            return key($arg) === 0 ? 'array' : 'object';
51
        } elseif ($arg instanceof \stdClass) {
52
            return 'object';
53
        } elseif ($arg instanceof \Closure) {
54
            return 'expression';
55
        } elseif ($arg instanceof \ArrayAccess
56
            && $arg instanceof \Countable
57
        ) {
58
            return count($arg) == 0 || $arg->offsetExists(0)
59
                ? 'array'
60
                : 'object';
61
        } elseif (method_exists($arg, '__toString')) {
62
            return 'string';
63
        }
64
 
65
        throw new \InvalidArgumentException(
66
            'Unable to determine JMESPath type from ' . get_class($arg)
67
        );
68
    }
69
 
70
    /**
71
     * Determine if the provided value is a JMESPath compatible object.
72
     *
73
     * @param mixed $value
74
     *
75
     * @return bool
76
     */
77
    public static function isObject($value)
78
    {
79
        if (is_array($value)) {
80
            return !$value || array_keys($value)[0] !== 0;
81
        }
82
 
83
        // Handle array-like values. Must be empty or offset 0 does not exist
84
        return $value instanceof \Countable && $value instanceof \ArrayAccess
85
            ? count($value) == 0 || !$value->offsetExists(0)
86
            : $value instanceof \stdClass;
87
    }
88
 
89
    /**
90
     * Determine if the provided value is a JMESPath compatible array.
91
     *
92
     * @param mixed $value
93
     *
94
     * @return bool
95
     */
96
    public static function isArray($value)
97
    {
98
        if (is_array($value)) {
99
            return !$value || array_keys($value)[0] === 0;
100
        }
101
 
102
        // Handle array-like values. Must be empty or offset 0 exists.
103
        return $value instanceof \Countable && $value instanceof \ArrayAccess
104
            ? count($value) == 0 || $value->offsetExists(0)
105
            : false;
106
    }
107
 
108
    /**
109
     * JSON aware value comparison function.
110
     *
111
     * @param mixed $a First value to compare
112
     * @param mixed $b Second value to compare
113
     *
114
     * @return bool
115
     */
116
    public static function isEqual($a, $b)
117
    {
118
        if ($a === $b) {
119
            return true;
120
        } elseif ($a instanceof \stdClass) {
121
            return self::isEqual((array) $a, $b);
122
        } elseif ($b instanceof \stdClass) {
123
            return self::isEqual($a, (array) $b);
124
        } else {
125
            return false;
126
        }
127
    }
128
 
129
    /**
130
     * Safely add together two values.
131
     *
132
     * @param mixed $a First value to add
133
     * @param mixed $b Second value to add
134
     *
135
     * @return int|float
136
     */
137
    public static function add($a, $b)
138
    {
139
        if (is_numeric($a)) {
140
            if (is_numeric($b)) {
141
                return $a + $b;
142
            } else {
143
                return $a;
144
            }
145
        } else {
146
            if (is_numeric($b)) {
147
                return $b;
148
            } else {
149
                return 0;
150
            }
151
        }
152
    }
153
 
154
    /**
155
     * JMESPath requires a stable sorting algorithm, so here we'll implement
156
     * a simple Schwartzian transform that uses array index positions as tie
157
     * breakers.
158
     *
159
     * @param array    $data   List or map of data to sort
160
     * @param callable $sortFn Callable used to sort values
161
     *
162
     * @return array Returns the sorted array
163
     * @link http://en.wikipedia.org/wiki/Schwartzian_transform
164
     */
165
    public static function stableSort(array $data, callable $sortFn)
166
    {
167
        // Decorate each item by creating an array of [value, index]
168
        array_walk($data, function (&$v, $k) {
169
            $v = [$v, $k];
170
        });
171
        // Sort by the sort function and use the index as a tie-breaker
172
        uasort($data, function ($a, $b) use ($sortFn) {
173
            return $sortFn($a[0], $b[0]) ?: ($a[1] < $b[1] ? -1 : 1);
174
        });
175
 
176
        // Undecorate each item and return the resulting sorted array
177
        return array_map(function ($v) {
178
            return $v[0];
179
        }, array_values($data));
180
    }
181
 
182
    /**
183
     * Creates a Python-style slice of a string or array.
184
     *
185
     * @param array|string $value Value to slice
186
     * @param int|null     $start Starting position
187
     * @param int|null     $stop  Stop position
188
     * @param int          $step  Step (1, 2, -1, -2, etc.)
189
     *
190
     * @return array|string
191
     * @throws \InvalidArgumentException
192
     */
193
    public static function slice($value, $start = null, $stop = null, $step = 1)
194
    {
195
        if (!is_array($value) && !is_string($value)) {
196
            throw new \InvalidArgumentException('Expects string or array');
197
        }
198
 
199
        return self::sliceIndices($value, $start, $stop, $step);
200
    }
201
 
202
    private static function adjustEndpoint($length, $endpoint, $step)
203
    {
204
        if ($endpoint < 0) {
205
            $endpoint += $length;
206
            if ($endpoint < 0) {
207
                $endpoint = $step < 0 ? -1 : 0;
208
            }
209
        } elseif ($endpoint >= $length) {
210
            $endpoint = $step < 0 ? $length - 1 : $length;
211
        }
212
 
213
        return $endpoint;
214
    }
215
 
216
    private static function adjustSlice($length, $start, $stop, $step)
217
    {
218
        if ($step === null) {
219
            $step = 1;
220
        } elseif ($step === 0) {
221
            throw new \RuntimeException('step cannot be 0');
222
        }
223
 
224
        if ($start === null) {
225
            $start = $step < 0 ? $length - 1 : 0;
226
        } else {
227
            $start = self::adjustEndpoint($length, $start, $step);
228
        }
229
 
230
        if ($stop === null) {
231
            $stop = $step < 0 ? -1 : $length;
232
        } else {
233
            $stop = self::adjustEndpoint($length, $stop, $step);
234
        }
235
 
236
        return [$start, $stop, $step];
237
    }
238
 
239
    private static function sliceIndices($subject, $start, $stop, $step)
240
    {
241
        $type = gettype($subject);
242
        $len = $type == 'string' ? mb_strlen($subject, 'UTF-8') : count($subject);
243
        list($start, $stop, $step) = self::adjustSlice($len, $start, $stop, $step);
244
 
245
        $result = [];
246
        if ($step > 0) {
247
            for ($i = $start; $i < $stop; $i += $step) {
248
                $result[] = $subject[$i];
249
            }
250
        } else {
251
            for ($i = $start; $i > $stop; $i += $step) {
252
                $result[] = $subject[$i];
253
            }
254
        }
255
 
256
        return $type == 'string' ? implode('', $result) : $result;
257
    }
258
}