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
/**
5
 * Dispatches to named JMESPath functions using a single function that has the
6
 * following signature:
7
 *
8
 *     mixed $result = fn(string $function_name, array $args)
9
 */
10
class FnDispatcher
11
{
12
    /**
13
     * Gets a cached instance of the default function implementations.
14
     *
15
     * @return FnDispatcher
16
     */
17
    public static function getInstance()
18
    {
19
        static $instance = null;
20
        if (!$instance) {
21
            $instance = new self();
22
        }
23
 
24
        return $instance;
25
    }
26
 
27
    /**
28
     * @param string $fn   Function name.
29
     * @param array  $args Function arguments.
30
     *
31
     * @return mixed
32
     */
33
    public function __invoke($fn, array $args)
34
    {
35
        return $this->{'fn_' . $fn}($args);
36
    }
37
 
38
    private function fn_abs(array $args)
39
    {
40
        $this->validate('abs', $args, [['number']]);
41
        return abs($args[0]);
42
    }
43
 
44
    private function fn_avg(array $args)
45
    {
46
        $this->validate('avg', $args, [['array']]);
47
        $sum = $this->reduce('avg:0', $args[0], ['number'], function ($a, $b) {
48
            return Utils::add($a, $b);
49
        });
50
        return $args[0] ? ($sum / count($args[0])) : null;
51
    }
52
 
53
    private function fn_ceil(array $args)
54
    {
55
        $this->validate('ceil', $args, [['number']]);
56
        return ceil($args[0]);
57
    }
58
 
59
    private function fn_contains(array $args)
60
    {
61
        $this->validate('contains', $args, [['string', 'array'], ['any']]);
62
        if (is_array($args[0])) {
63
            return in_array($args[1], $args[0]);
64
        } elseif (is_string($args[1])) {
65
            return mb_strpos($args[0], $args[1], 0, 'UTF-8') !== false;
66
        } else {
67
            return null;
68
        }
69
    }
70
 
71
    private function fn_ends_with(array $args)
72
    {
73
        $this->validate('ends_with', $args, [['string'], ['string']]);
74
        list($search, $suffix) = $args;
75
        return $suffix === '' || mb_substr($search, -mb_strlen($suffix, 'UTF-8'), null, 'UTF-8') === $suffix;
76
    }
77
 
78
    private function fn_floor(array $args)
79
    {
80
        $this->validate('floor', $args, [['number']]);
81
        return floor($args[0]);
82
    }
83
 
84
    private function fn_not_null(array $args)
85
    {
86
        if (!$args) {
87
            throw new \RuntimeException(
88
                "not_null() expects 1 or more arguments, 0 were provided"
89
            );
90
        }
91
 
92
        return array_reduce($args, function ($carry, $item) {
93
            return $carry !== null ? $carry : $item;
94
        });
95
    }
96
 
97
    private function fn_join(array $args)
98
    {
99
        $this->validate('join', $args, [['string'], ['array']]);
100
        $fn = function ($a, $b, $i) use ($args) {
101
            return $i ? ($a . $args[0] . $b) : $b;
102
        };
103
        return $this->reduce('join:0', $args[1], ['string'], $fn);
104
    }
105
 
106
    private function fn_keys(array $args)
107
    {
108
        $this->validate('keys', $args, [['object']]);
109
        return array_keys((array) $args[0]);
110
    }
111
 
112
    private function fn_length(array $args)
113
    {
114
        $this->validate('length', $args, [['string', 'array', 'object']]);
115
        return is_string($args[0]) ? mb_strlen($args[0], 'UTF-8') : count((array) $args[0]);
116
    }
117
 
118
    private function fn_max(array $args)
119
    {
120
        $this->validate('max', $args, [['array']]);
121
        $fn = function ($a, $b) {
122
            return $a >= $b ? $a : $b;
123
        };
124
        return $this->reduce('max:0', $args[0], ['number', 'string'], $fn);
125
    }
126
 
127
    private function fn_max_by(array $args)
128
    {
129
        $this->validate('max_by', $args, [['array'], ['expression']]);
130
        $expr = $this->wrapExpression('max_by:1', $args[1], ['number', 'string']);
131
        $fn = function ($carry, $item, $index) use ($expr) {
132
            return $index
133
                ? ($expr($carry) >= $expr($item) ? $carry : $item)
134
                : $item;
135
        };
136
        return $this->reduce('max_by:1', $args[0], ['any'], $fn);
137
    }
138
 
139
    private function fn_min(array $args)
140
    {
141
        $this->validate('min', $args, [['array']]);
142
        $fn = function ($a, $b, $i) {
143
            return $i && $a <= $b ? $a : $b;
144
        };
145
        return $this->reduce('min:0', $args[0], ['number', 'string'], $fn);
146
    }
147
 
148
    private function fn_min_by(array $args)
149
    {
150
        $this->validate('min_by', $args, [['array'], ['expression']]);
151
        $expr = $this->wrapExpression('min_by:1', $args[1], ['number', 'string']);
152
        $i = -1;
153
        $fn = function ($a, $b) use ($expr, &$i) {
154
            return ++$i ? ($expr($a) <= $expr($b) ? $a : $b) : $b;
155
        };
156
        return $this->reduce('min_by:1', $args[0], ['any'], $fn);
157
    }
158
 
159
    private function fn_reverse(array $args)
160
    {
161
        $this->validate('reverse', $args, [['array', 'string']]);
162
        if (is_array($args[0])) {
163
            return array_reverse($args[0]);
164
        } elseif (is_string($args[0])) {
165
            return strrev($args[0]);
166
        } else {
167
            throw new \RuntimeException('Cannot reverse provided argument');
168
        }
169
    }
170
 
171
    private function fn_sum(array $args)
172
    {
173
        $this->validate('sum', $args, [['array']]);
174
        $fn = function ($a, $b) {
175
            return Utils::add($a, $b);
176
        };
177
        return $this->reduce('sum:0', $args[0], ['number'], $fn);
178
    }
179
 
180
    private function fn_sort(array $args)
181
    {
182
        $this->validate('sort', $args, [['array']]);
183
        $valid = ['string', 'number'];
184
        return Utils::stableSort($args[0], function ($a, $b) use ($valid) {
185
            $this->validateSeq('sort:0', $valid, $a, $b);
186
            return strnatcmp($a, $b);
187
        });
188
    }
189
 
190
    private function fn_sort_by(array $args)
191
    {
192
        $this->validate('sort_by', $args, [['array'], ['expression']]);
193
        $expr = $args[1];
194
        $valid = ['string', 'number'];
195
        return Utils::stableSort(
196
            $args[0],
197
            function ($a, $b) use ($expr, $valid) {
198
                $va = $expr($a);
199
                $vb = $expr($b);
200
                $this->validateSeq('sort_by:0', $valid, $va, $vb);
201
                return strnatcmp($va, $vb);
202
            }
203
        );
204
    }
205
 
206
    private function fn_starts_with(array $args)
207
    {
208
        $this->validate('starts_with', $args, [['string'], ['string']]);
209
        list($search, $prefix) = $args;
210
        return $prefix === '' || mb_strpos($search, $prefix, 0, 'UTF-8') === 0;
211
    }
212
 
213
    private function fn_type(array $args)
214
    {
215
        $this->validateArity('type', count($args), 1);
216
        return Utils::type($args[0]);
217
    }
218
 
219
    private function fn_to_string(array $args)
220
    {
221
        $this->validateArity('to_string', count($args), 1);
222
        $v = $args[0];
223
        if (is_string($v)) {
224
            return $v;
225
        } elseif (is_object($v)
226
            && !($v instanceof \JsonSerializable)
227
            && method_exists($v, '__toString')
228
        ) {
229
            return (string) $v;
230
        }
231
 
232
        return json_encode($v);
233
    }
234
 
235
    private function fn_to_number(array $args)
236
    {
237
        $this->validateArity('to_number', count($args), 1);
238
        $value = $args[0];
239
        $type = Utils::type($value);
240
        if ($type == 'number') {
241
            return $value;
242
        } elseif ($type == 'string' && is_numeric($value)) {
243
            return mb_strpos($value, '.', 0, 'UTF-8') ? (float) $value : (int) $value;
244
        } else {
245
            return null;
246
        }
247
    }
248
 
249
    private function fn_values(array $args)
250
    {
251
        $this->validate('values', $args, [['array', 'object']]);
252
        return array_values((array) $args[0]);
253
    }
254
 
255
    private function fn_merge(array $args)
256
    {
257
        if (!$args) {
258
            throw new \RuntimeException(
259
                "merge() expects 1 or more arguments, 0 were provided"
260
            );
261
        }
262
 
263
        return call_user_func_array('array_replace', $args);
264
    }
265
 
266
    private function fn_to_array(array $args)
267
    {
268
        $this->validate('to_array', $args, [['any']]);
269
 
270
        return Utils::isArray($args[0]) ? $args[0] : [$args[0]];
271
    }
272
 
273
    private function fn_map(array $args)
274
    {
275
        $this->validate('map', $args, [['expression'], ['any']]);
276
        $result = [];
277
        foreach ($args[1] as $a) {
278
            $result[] = $args[0]($a);
279
        }
280
        return $result;
281
    }
282
 
283
    private function typeError($from, $msg)
284
    {
285
        if (mb_strpos($from, ':', 0, 'UTF-8')) {
286
            list($fn, $pos) = explode(':', $from);
287
            throw new \RuntimeException(
288
                sprintf('Argument %d of %s %s', $pos, $fn, $msg)
289
            );
290
        } else {
291
            throw new \RuntimeException(
292
                sprintf('Type error: %s %s', $from, $msg)
293
            );
294
        }
295
    }
296
 
297
    private function validateArity($from, $given, $expected)
298
    {
299
        if ($given != $expected) {
300
            $err = "%s() expects {$expected} arguments, {$given} were provided";
301
            throw new \RuntimeException(sprintf($err, $from));
302
        }
303
    }
304
 
305
    private function validate($from, $args, $types = [])
306
    {
307
        $this->validateArity($from, count($args), count($types));
308
        foreach ($args as $index => $value) {
309
            if (!isset($types[$index]) || !$types[$index]) {
310
                continue;
311
            }
312
            $this->validateType("{$from}:{$index}", $value, $types[$index]);
313
        }
314
    }
315
 
316
    private function validateType($from, $value, array $types)
317
    {
318
        if ($types[0] == 'any'
319
            || in_array(Utils::type($value), $types)
320
            || ($value === [] && in_array('object', $types))
321
        ) {
322
            return;
323
        }
324
        $msg = 'must be one of the following types: ' . implode(', ', $types)
325
            . '. ' . Utils::type($value) . ' found';
326
        $this->typeError($from, $msg);
327
    }
328
 
329
    /**
330
     * Validates value A and B, ensures they both are correctly typed, and of
331
     * the same type.
332
     *
333
     * @param string   $from   String of function:argument_position
334
     * @param array    $types  Array of valid value types.
335
     * @param mixed    $a      Value A
336
     * @param mixed    $b      Value B
337
     */
338
    private function validateSeq($from, array $types, $a, $b)
339
    {
340
        $ta = Utils::type($a);
341
        $tb = Utils::type($b);
342
 
343
        if ($ta !== $tb) {
344
            $msg = "encountered a type mismatch in sequence: {$ta}, {$tb}";
345
            $this->typeError($from, $msg);
346
        }
347
 
348
        $typeMatch = ($types && $types[0] == 'any') || in_array($ta, $types);
349
        if (!$typeMatch) {
350
            $msg = 'encountered a type error in sequence. The argument must be '
351
                . 'an array of ' . implode('|', $types) . ' types. '
352
                . "Found {$ta}, {$tb}.";
353
            $this->typeError($from, $msg);
354
        }
355
    }
356
 
357
    /**
358
     * Reduces and validates an array of values to a single value using a fn.
359
     *
360
     * @param string   $from   String of function:argument_position
361
     * @param array    $values Values to reduce.
362
     * @param array    $types  Array of valid value types.
363
     * @param callable $reduce Reduce function that accepts ($carry, $item).
364
     *
365
     * @return mixed
366
     */
367
    private function reduce($from, array $values, array $types, callable $reduce)
368
    {
369
        $i = -1;
370
        return array_reduce(
371
            $values,
372
            function ($carry, $item) use ($from, $types, $reduce, &$i) {
373
                if (++$i > 0) {
374
                    $this->validateSeq($from, $types, $carry, $item);
375
                }
376
                return $reduce($carry, $item, $i);
377
            }
378
        );
379
    }
380
 
381
    /**
382
     * Validates the return values of expressions as they are applied.
383
     *
384
     * @param string   $from  Function name : position
385
     * @param callable $expr  Expression function to validate.
386
     * @param array    $types Array of acceptable return type values.
387
     *
388
     * @return callable Returns a wrapped function
389
     */
390
    private function wrapExpression($from, callable $expr, array $types)
391
    {
392
        list($fn, $pos) = explode(':', $from);
393
        $from = "The expression return value of argument {$pos} of {$fn}";
394
        return function ($value) use ($from, $expr, $types) {
395
            $value = $expr($value);
396
            $this->validateType($from, $value, $types);
397
            return $value;
398
        };
399
    }
400
 
401
    /** @internal Pass function name validation off to runtime */
402
    public function __call($name, $args)
403
    {
404
        $name = str_replace('fn_', '', $name);
405
        throw new \RuntimeException("Call to undefined function {$name}");
406
    }
407
}