Passed
Push — master ( a27dd3...975c9f )
by Vladimir
11:24
created

Utils::keyValMap()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace GraphQL\Utils;
6
7
use ErrorException;
8
use Exception;
9
use GraphQL\Error\Error;
10
use GraphQL\Error\InvariantViolation;
11
use GraphQL\Error\Warning;
12
use GraphQL\Language\AST\Node;
13
use GraphQL\Type\Definition\Type;
14
use GraphQL\Type\Definition\WrappingType;
15
use InvalidArgumentException;
16
use LogicException;
17
use stdClass;
18
use Traversable;
19
use function array_keys;
20
use function array_map;
21
use function array_reduce;
22
use function array_shift;
23
use function array_slice;
24
use function array_values;
25
use function asort;
26
use function chr;
27
use function count;
28
use function dechex;
29
use function func_get_args;
30
use function func_num_args;
31
use function get_class;
32
use function gettype;
33
use function is_array;
34
use function is_int;
35
use function is_object;
36
use function is_scalar;
37
use function is_string;
38
use function json_encode;
39
use function levenshtein;
40
use function max;
41
use function mb_convert_encoding;
42
use function mb_strlen;
43
use function mb_substr;
44
use function method_exists;
45
use function ord;
46
use function pack;
47
use function preg_match;
48
use function property_exists;
49
use function range;
50
use function restore_error_handler;
51
use function set_error_handler;
52
use function sprintf;
53
use function strtolower;
54
use function unpack;
55
56
class Utils
57
{
58 382
    public static function undefined()
59
    {
60 382
        static $undefined;
61
62 382
        return $undefined ?: $undefined = new stdClass();
63
    }
64
65
    /**
66
     * Check if the value is invalid
67
     *
68
     * @param mixed $value
69
     *
70
     * @return bool
71
     */
72 74
    public static function isInvalid($value)
73
    {
74 74
        return self::undefined() === $value;
75
    }
76
77
    /**
78
     * @param object   $obj
79
     * @param mixed[]  $vars
80
     * @param string[] $requiredKeys
81
     *
82
     * @return object
83
     */
84 977
    public static function assign($obj, array $vars, array $requiredKeys = [])
85
    {
86 977
        foreach ($requiredKeys as $key) {
87 1
            if (! isset($vars[$key])) {
88 1
                throw new InvalidArgumentException(sprintf('Key %s is expected to be set and not to be null', $key));
89
            }
90
        }
91
92 976
        foreach ($vars as $key => $value) {
93 976
            if (! property_exists($obj, $key)) {
94
                $cls = get_class($obj);
95
                Warning::warn(
96
                    sprintf("Trying to set non-existing property '%s' on class '%s'", $key, $cls),
97
                    Warning::WARNING_ASSIGN
98
                );
99
            }
100 976
            $obj->{$key} = $value;
101
        }
102
103 976
        return $obj;
104
    }
105
106
    /**
107
     * @param mixed|Traversable $traversable
108
     *
109
     * @return mixed|null
110
     */
111 519
    public static function find($traversable, callable $predicate)
112
    {
113 519
        self::invariant(
114 519
            is_array($traversable) || $traversable instanceof Traversable,
115 519
            __METHOD__ . ' expects array or Traversable'
116
        );
117
118 519
        foreach ($traversable as $key => $value) {
119 231
            if ($predicate($value, $key)) {
120 231
                return $value;
121
            }
122
        }
123
124 357
        return null;
125
    }
126
127
    /**
128
     * @param mixed|Traversable $traversable
129
     *
130
     * @return mixed[]
131
     *
132
     * @throws Exception
133
     */
134 192
    public static function filter($traversable, callable $predicate)
135
    {
136 192
        self::invariant(
137 192
            is_array($traversable) || $traversable instanceof Traversable,
138 192
            __METHOD__ . ' expects array or Traversable'
139
        );
140
141 192
        $result = [];
142 192
        $assoc  = false;
143 192
        foreach ($traversable as $key => $value) {
144 192
            if (! $assoc && ! is_int($key)) {
145
                $assoc = true;
146
            }
147 192
            if (! $predicate($value, $key)) {
148 84
                continue;
149
            }
150
151 190
            $result[$key] = $value;
152
        }
153
154 192
        return $assoc ? $result : array_values($result);
155
    }
156
157
    /**
158
     * @param mixed|Traversable $traversable
159
     *
160
     * @return mixed[]
161
     *
162
     * @throws Exception
163
     */
164 381
    public static function map($traversable, callable $fn)
165
    {
166 381
        self::invariant(
167 381
            is_array($traversable) || $traversable instanceof Traversable,
168 381
            __METHOD__ . ' expects array or Traversable'
169
        );
170
171 381
        $map = [];
172 381
        foreach ($traversable as $key => $value) {
173 350
            $map[$key] = $fn($value, $key);
174
        }
175
176 379
        return $map;
177
    }
178
179
    /**
180
     * @param mixed|Traversable $traversable
181
     *
182
     * @return mixed[]
183
     *
184
     * @throws Exception
185
     */
186
    public static function mapKeyValue($traversable, callable $fn)
187
    {
188
        self::invariant(
189
            is_array($traversable) || $traversable instanceof Traversable,
190
            __METHOD__ . ' expects array or Traversable'
191
        );
192
193
        $map = [];
194
        foreach ($traversable as $key => $value) {
195
            [$newKey, $newValue] = $fn($value, $key);
196
            $map[$newKey]        = $newValue;
197
        }
198
199
        return $map;
200
    }
201
202
    /**
203
     * @param mixed|Traversable $traversable
204
     *
205
     * @return mixed[]
206
     *
207
     * @throws Exception
208
     */
209 65
    public static function keyMap($traversable, callable $keyFn)
210
    {
211 65
        self::invariant(
212 65
            is_array($traversable) || $traversable instanceof Traversable,
213 65
            __METHOD__ . ' expects array or Traversable'
214
        );
215
216 65
        $map = [];
217 65
        foreach ($traversable as $key => $value) {
218 64
            $newKey = $keyFn($value, $key);
219 64
            if (! is_scalar($newKey)) {
220
                continue;
221
            }
222
223 64
            $map[$newKey] = $value;
224
        }
225
226 65
        return $map;
227
    }
228
229
    public static function each($traversable, callable $fn)
230
    {
231
        self::invariant(
232
            is_array($traversable) || $traversable instanceof Traversable,
233
            __METHOD__ . ' expects array or Traversable'
234
        );
235
236
        foreach ($traversable as $key => $item) {
237
            $fn($item, $key);
238
        }
239
    }
240
241
    /**
242
     * Splits original traversable to several arrays with keys equal to $keyFn return
243
     *
244
     * E.g. Utils::groupBy([1, 2, 3, 4, 5], function($value) {return $value % 3}) will output:
245
     * [
246
     *    1 => [1, 4],
247
     *    2 => [2, 5],
248
     *    0 => [3],
249
     * ]
250
     *
251
     * $keyFn is also allowed to return array of keys. Then value will be added to all arrays with given keys
252
     *
253
     * @param mixed[]|Traversable $traversable
254
     *
255
     * @return mixed[]
256
     */
257
    public static function groupBy($traversable, callable $keyFn)
258
    {
259
        self::invariant(
260
            is_array($traversable) || $traversable instanceof Traversable,
261
            __METHOD__ . ' expects array or Traversable'
262
        );
263
264
        $grouped = [];
265
        foreach ($traversable as $key => $value) {
266
            $newKeys = (array) $keyFn($value, $key);
267
            foreach ($newKeys as $newKey) {
268
                $grouped[$newKey][] = $value;
269
            }
270
        }
271
272
        return $grouped;
273
    }
274
275
    /**
276
     * @param mixed[]|Traversable $traversable
277
     *
278
     * @return mixed[][]
279
     */
280 156
    public static function keyValMap($traversable, callable $keyFn, callable $valFn)
281
    {
282 156
        $map = [];
283 156
        foreach ($traversable as $item) {
284 155
            $map[$keyFn($item)] = $valFn($item);
285
        }
286
287 154
        return $map;
288
    }
289
290
    /**
291
     * @param mixed[] $traversable
292
     *
293
     * @return bool
294
     */
295 81
    public static function every($traversable, callable $predicate)
296
    {
297 81
        foreach ($traversable as $key => $value) {
298 81
            if (! $predicate($value, $key)) {
299 81
                return false;
300
            }
301
        }
302
303 79
        return true;
304
    }
305
306
    /**
307
     * @param bool   $test
308
     * @param string $message
309
     */
310 1245
    public static function invariant($test, $message = '')
311
    {
312 1245
        if (! $test) {
313 37
            if (func_num_args() > 2) {
314 7
                $args = func_get_args();
315 7
                array_shift($args);
316 7
                $message = sprintf(...$args);
317
            }
318
            // TODO switch to Error here
319 37
            throw new InvariantViolation($message);
320
        }
321 1241
    }
322
323
    /**
324
     * @param Type|mixed $var
325
     *
326
     * @return string
327
     */
328 1107
    public static function getVariableType($var)
329
    {
330 1107
        if ($var instanceof Type) {
331
            // FIXME: Replace with schema printer call
332
            if ($var instanceof WrappingType) {
333
                $var = $var->getWrappedType(true);
334
            }
335
336
            return $var->name;
337
        }
338
339 1107
        return is_object($var) ? get_class($var) : gettype($var);
340
    }
341
342
    /**
343
     * @param mixed $var
344
     *
345
     * @return string
346
     */
347 39
    public static function printSafeJson($var)
348
    {
349 39
        if ($var instanceof stdClass) {
350
            $var = (array) $var;
351
        }
352 39
        if (is_array($var)) {
353 16
            return json_encode($var);
354
        }
355 24
        if ($var === '') {
356
            return '(empty string)';
357
        }
358 24
        if ($var === null) {
359
            return 'null';
360
        }
361 24
        if ($var === false) {
362 1
            return 'false';
363
        }
364 24
        if ($var === true) {
365 1
            return 'true';
366
        }
367 23
        if (is_string($var)) {
368 16
            return sprintf('"%s"', $var);
369
        }
370 8
        if (is_scalar($var)) {
371 8
            return (string) $var;
372
        }
373
374
        return gettype($var);
375
    }
376
377
    /**
378
     * @param Type|mixed $var
379
     *
380
     * @return string
381
     */
382 933
    public static function printSafe($var)
383
    {
384 933
        if ($var instanceof Type) {
385 818
            return $var->toString();
386
        }
387 239
        if (is_object($var)) {
388 150
            if (method_exists($var, '__toString')) {
389
                return (string) $var;
390
            }
391
392 150
            return 'instance of ' . get_class($var);
393
        }
394 103
        if (is_array($var)) {
395 21
            return json_encode($var);
396
        }
397 94
        if ($var === '') {
398 14
            return '(empty string)';
399
        }
400 89
        if ($var === null) {
401 29
            return 'null';
402
        }
403 68
        if ($var === false) {
404 7
            return 'false';
405
        }
406 67
        if ($var === true) {
407 8
            return 'true';
408
        }
409 65
        if (is_string($var)) {
410 36
            return $var;
411
        }
412 32
        if (is_scalar($var)) {
413 32
            return (string) $var;
414
        }
415
416
        return gettype($var);
417
    }
418
419
    /**
420
     * UTF-8 compatible chr()
421
     *
422
     * @param string $ord
423
     * @param string $encoding
424
     *
425
     * @return string
426
     */
427 23
    public static function chr($ord, $encoding = 'UTF-8')
428
    {
429 23
        if ($ord <= 255) {
430 20
            return chr($ord);
0 ignored issues
show
Bug introduced by
$ord of type string is incompatible with the type integer expected by parameter $ascii of chr(). ( Ignorable by Annotation )

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

430
            return chr(/** @scrutinizer ignore-type */ $ord);
Loading history...
431
        }
432 3
        if ($encoding === 'UCS-4BE') {
433 3
            return pack('N', $ord);
434
        }
435
436 3
        return mb_convert_encoding(self::chr($ord, 'UCS-4BE'), $encoding, 'UCS-4BE');
437
    }
438
439
    /**
440
     * UTF-8 compatible ord()
441
     *
442
     * @param string $char
443
     * @param string $encoding
444
     *
445
     * @return mixed
446
     */
447 5
    public static function ord($char, $encoding = 'UTF-8')
448
    {
449 5
        if (! $char && $char !== '0') {
450
            return 0;
451
        }
452 5
        if (! isset($char[1])) {
453
            return ord($char);
454
        }
455 5
        if ($encoding !== 'UCS-4BE') {
456 5
            $char = mb_convert_encoding($char, 'UCS-4BE', $encoding);
457
        }
458
459 5
        return unpack('N', $char)[1];
460
    }
461
462
    /**
463
     * Returns UTF-8 char code at given $positing of the $string
464
     *
465
     * @param string $string
466
     * @param int    $position
467
     *
468
     * @return mixed
469
     */
470
    public static function charCodeAt($string, $position)
471
    {
472
        $char = mb_substr($string, $position, 1, 'UTF-8');
473
474
        return self::ord($char);
475
    }
476
477
    /**
478
     * @param int|null $code
479
     *
480
     * @return string
481
     */
482 22
    public static function printCharCode($code)
483
    {
484 22
        if ($code === null) {
485 2
            return '<EOF>';
486
        }
487
488 20
        return $code < 0x007F
489
            // Trust JSON for ASCII.
490 18
            ? json_encode(self::chr($code))
491
            // Otherwise print the escaped form.
492 20
            : '"\\u' . dechex($code) . '"';
493
    }
494
495
    /**
496
     * Upholds the spec rules about naming.
497
     *
498
     * @param string $name
499
     *
500
     * @throws Error
501
     */
502 26
    public static function assertValidName($name)
503
    {
504 26
        $error = self::isValidNameError($name);
505 25
        if ($error) {
506 2
            throw $error;
507
        }
508 23
    }
509
510
    /**
511
     * Returns an Error if a name is invalid.
512
     *
513
     * @param string    $name
514
     * @param Node|null $node
515
     *
516
     * @return Error|null
517
     */
518 103
    public static function isValidNameError($name, $node = null)
519
    {
520 103
        self::invariant(is_string($name), 'Expected string');
521
522 102
        if (isset($name[1]) && $name[0] === '_' && $name[1] === '_') {
523 89
            return new Error(
524 89
                sprintf('Name "%s" must not begin with "__", which is reserved by ', $name) .
525 89
                'GraphQL introspection.',
526 89
                $node
527
            );
528
        }
529
530 101
        if (! preg_match('/^[_a-zA-Z][_a-zA-Z0-9]*$/', $name)) {
531 6
            return new Error(
532 6
                sprintf('Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "%s" does not.', $name),
533 6
                $node
534
            );
535
        }
536
537 100
        return null;
538
    }
539
540
    /**
541
     * Wraps original callable with PHP error handling (using set_error_handler).
542
     * Resulting callable will collect all PHP errors that occur during the call in $errors array.
543
     *
544
     * @param ErrorException[] $errors
545
     *
546
     * @return callable
547
     */
548
    public static function withErrorHandling(callable $fn, array &$errors)
549
    {
550
        return static function () use ($fn, &$errors) {
551
            // Catch custom errors (to report them in query results)
552
            set_error_handler(static function ($severity, $message, $file, $line) use (&$errors) {
553
                $errors[] = new ErrorException($message, 0, $severity, $file, $line);
554
            });
555
556
            try {
557
                return $fn();
558
            } finally {
559
                restore_error_handler();
560
            }
561
        };
562
    }
563
564
    /**
565
     * @param string[] $items
566
     *
567
     * @return string
568
     */
569 22
    public static function quotedOrList(array $items)
570
    {
571 22
        $items = array_map(
572
            static function ($item) {
573 21
                return sprintf('"%s"', $item);
574 22
            },
575 22
            $items
576
        );
577
578 22
        return self::orList($items);
579
    }
580
581
    /**
582
     * @param string[] $items
583
     *
584
     * @return string
585
     */
586 30
    public static function orList(array $items)
587
    {
588 30
        if (count($items) === 0) {
589 1
            throw new LogicException('items must not need to be empty.');
590
        }
591 29
        $selected       = array_slice($items, 0, 5);
592 29
        $selectedLength = count($selected);
593 29
        $firstSelected  = $selected[0];
594
595 29
        if ($selectedLength === 1) {
596 17
            return $firstSelected;
597
        }
598
599 12
        return array_reduce(
600 12
            range(1, $selectedLength - 1),
601
            static function ($list, $index) use ($selected, $selectedLength) {
602
                return $list .
603 12
                    ($selectedLength > 2 ? ', ' : ' ') .
604 12
                    ($index === $selectedLength - 1 ? 'or ' : '') .
605 12
                    $selected[$index];
606 12
            },
607 12
            $firstSelected
608
        );
609
    }
610
611
    /**
612
     * Given an invalid input string and a list of valid options, returns a filtered
613
     * list of valid options sorted based on their similarity with the input.
614
     *
615
     * Includes a custom alteration from Damerau-Levenshtein to treat case changes
616
     * as a single edit which helps identify mis-cased values with an edit distance
617
     * of 1
618
     *
619
     * @param string   $input
620
     * @param string[] $options
621
     *
622
     * @return string[]
623
     */
624 44
    public static function suggestionList($input, array $options)
625
    {
626 44
        $optionsByDistance = [];
627 44
        $inputThreshold    = mb_strlen($input) / 2;
628 44
        foreach ($options as $option) {
629 43
            if ($input === $option) {
630 1
                $distance = 0;
631
            } else {
632 43
                $distance = (strtolower($input) === strtolower($option)
633 4
                    ? 1
634 43
                    : levenshtein($input, $option));
635
            }
636 43
            $threshold = max($inputThreshold, mb_strlen($option) / 2, 1);
637 43
            if ($distance > $threshold) {
638 39
                continue;
639
            }
640
641 19
            $optionsByDistance[$option] = $distance;
642
        }
643
644 44
        asort($optionsByDistance);
645
646 44
        return array_keys($optionsByDistance);
647
    }
648
}
649