Failed Conditions
Push — master ( a4f39b...12ee90 )
by Vladimir
11:17
created

Utils::filter()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7.0222

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 21
ccs 12
cts 13
cp 0.9231
rs 8.8333
c 0
b 0
f 0
cc 7
nc 10
nop 2
crap 7.0222
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 1004
    public static function assign($obj, array $vars, array $requiredKeys = [])
85
    {
86 1004
        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 1003
        foreach ($vars as $key => $value) {
93 1003
            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 1003
            $obj->{$key} = $value;
101
        }
102
103 1003
        return $obj;
104
    }
105
106
    /**
107
     * @param mixed|Traversable $traversable
108
     *
109
     * @return mixed|null
110
     */
111 527
    public static function find($traversable, callable $predicate)
112
    {
113 527
        self::invariant(
114 527
            is_array($traversable) || $traversable instanceof Traversable,
115 527
            __METHOD__ . ' expects array or Traversable'
116
        );
117
118 527
        foreach ($traversable as $key => $value) {
119 232
            if ($predicate($value, $key)) {
120 232
                return $value;
121
            }
122
        }
123
124 365
        return null;
125
    }
126
127
    /**
128
     * @param mixed|Traversable $traversable
129
     *
130
     * @return mixed[]
131
     *
132
     * @throws Exception
133
     */
134 287
    public static function filter($traversable, callable $predicate)
135
    {
136 287
        self::invariant(
137 287
            is_array($traversable) || $traversable instanceof Traversable,
138 287
            __METHOD__ . ' expects array or Traversable'
139
        );
140
141 287
        $result = [];
142 287
        $assoc  = false;
143 287
        foreach ($traversable as $key => $value) {
144 247
            if (! $assoc && ! is_int($key)) {
145
                $assoc = true;
146
            }
147 247
            if (! $predicate($value, $key)) {
148 93
                continue;
149
            }
150
151 245
            $result[$key] = $value;
152
        }
153
154 287
        return $assoc ? $result : array_values($result);
155
    }
156
157
    /**
158
     * @param mixed|Traversable $traversable
159
     *
160
     * @return mixed[]
161
     *
162
     * @throws Exception
163
     */
164 404
    public static function map($traversable, callable $fn)
165
    {
166 404
        self::invariant(
167 404
            is_array($traversable) || $traversable instanceof Traversable,
168 404
            __METHOD__ . ' expects array or Traversable'
169
        );
170
171 404
        $map = [];
172 404
        foreach ($traversable as $key => $value) {
173 373
            $map[$key] = $fn($value, $key);
174
        }
175
176 402
        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 217
    public static function keyMap($traversable, callable $keyFn)
210
    {
211 217
        self::invariant(
212 217
            is_array($traversable) || $traversable instanceof Traversable,
213 217
            __METHOD__ . ' expects array or Traversable'
214
        );
215
216 217
        $map = [];
217 217
        foreach ($traversable as $key => $value) {
218 216
            $newKey = $keyFn($value, $key);
219 216
            if (! is_scalar($newKey)) {
220
                continue;
221
            }
222
223 216
            $map[$newKey] = $value;
224
        }
225
226 217
        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 144
    public static function groupBy($traversable, callable $keyFn)
258
    {
259 144
        self::invariant(
260 144
            is_array($traversable) || $traversable instanceof Traversable,
261 144
            __METHOD__ . ' expects array or Traversable'
262
        );
263
264 144
        $grouped = [];
265 144
        foreach ($traversable as $key => $value) {
266 26
            $newKeys = (array) $keyFn($value, $key);
267 26
            foreach ($newKeys as $newKey) {
268 26
                $grouped[$newKey][] = $value;
269
            }
270
        }
271
272 144
        return $grouped;
273
    }
274
275
    /**
276
     * @param mixed[]|Traversable $traversable
277
     *
278
     * @return mixed[][]
279
     */
280 179
    public static function keyValMap($traversable, callable $keyFn, callable $valFn)
281
    {
282 179
        $map = [];
283 179
        foreach ($traversable as $item) {
284 162
            $map[$keyFn($item)] = $valFn($item);
285
        }
286
287 178
        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 mixed[] $traversable
308
     *
309
     * @return bool
310
     */
311 5
    public static function some($traversable, callable $predicate)
312
    {
313 5
        foreach ($traversable as $key => $value) {
314 5
            if ($predicate($value, $key)) {
315 5
                return true;
316
            }
317
        }
318
319
        return false;
320
    }
321
322
    /**
323
     * @param bool   $test
324
     * @param string $message
325
     */
326 1272
    public static function invariant($test, $message = '')
327
    {
328 1272
        if (! $test) {
329 37
            if (func_num_args() > 2) {
330 7
                $args = func_get_args();
331 7
                array_shift($args);
332 7
                $message = sprintf(...$args);
333
            }
334
            // TODO switch to Error here
335 37
            throw new InvariantViolation($message);
336
        }
337 1268
    }
338
339
    /**
340
     * @param Type|mixed $var
341
     *
342
     * @return string
343
     */
344 1134
    public static function getVariableType($var)
345
    {
346 1134
        if ($var instanceof Type) {
347
            // FIXME: Replace with schema printer call
348
            if ($var instanceof WrappingType) {
349
                $var = $var->getWrappedType(true);
350
            }
351
352
            return $var->name;
353
        }
354
355 1134
        return is_object($var) ? get_class($var) : gettype($var);
356
    }
357
358
    /**
359
     * @param mixed $var
360
     *
361
     * @return string
362
     */
363 39
    public static function printSafeJson($var)
364
    {
365 39
        if ($var instanceof stdClass) {
366
            $var = (array) $var;
367
        }
368 39
        if (is_array($var)) {
369 16
            return json_encode($var);
370
        }
371 24
        if ($var === '') {
372
            return '(empty string)';
373
        }
374 24
        if ($var === null) {
375
            return 'null';
376
        }
377 24
        if ($var === false) {
378 1
            return 'false';
379
        }
380 24
        if ($var === true) {
381 1
            return 'true';
382
        }
383 23
        if (is_string($var)) {
384 16
            return sprintf('"%s"', $var);
385
        }
386 8
        if (is_scalar($var)) {
387 8
            return (string) $var;
388
        }
389
390
        return gettype($var);
391
    }
392
393
    /**
394
     * @param Type|mixed $var
395
     *
396
     * @return string
397
     */
398 953
    public static function printSafe($var)
399
    {
400 953
        if ($var instanceof Type) {
401 825
            return $var->toString();
402
        }
403 267
        if (is_object($var)) {
404 178
            if (method_exists($var, '__toString')) {
405
                return (string) $var;
406
            }
407
408 178
            return 'instance of ' . get_class($var);
409
        }
410 103
        if (is_array($var)) {
411 21
            return json_encode($var);
412
        }
413 94
        if ($var === '') {
414 14
            return '(empty string)';
415
        }
416 89
        if ($var === null) {
417 29
            return 'null';
418
        }
419 68
        if ($var === false) {
420 7
            return 'false';
421
        }
422 67
        if ($var === true) {
423 8
            return 'true';
424
        }
425 65
        if (is_string($var)) {
426 36
            return $var;
427
        }
428 32
        if (is_scalar($var)) {
429 32
            return (string) $var;
430
        }
431
432
        return gettype($var);
433
    }
434
435
    /**
436
     * UTF-8 compatible chr()
437
     *
438
     * @param string $ord
439
     * @param string $encoding
440
     *
441
     * @return string
442
     */
443 23
    public static function chr($ord, $encoding = 'UTF-8')
444
    {
445 23
        if ($ord <= 255) {
446 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

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