packages/sql-semantics-sqlite/src/Rules/ClosedList.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\Sqlite\Rules;
6
7use SqlSemantics\Platform\Sqlite\Model\Diagnostic\Check;
8use SqlSemantics\Platform\Sqlite\Model\Diagnostic\InvalidConstruction;
9
10/**
11 * Narrows a constructor argument to an ordered list whose items are of one of several admitted classes.
12 *
13 * PHP does not check array element types, so every list a constructor accepts
14 * passes through here whatever its PHPDoc promises; a list of one class goes
15 * through the core check instead.
16 *
17 * @visibility SqlSemantics\Platform\Sqlite
18 */
19final class ClosedList
20{
21 /**
22 * Answers the items as a list, rejecting any item that is of none of the classes, a non-list array, or too few items.
23 *
24 * @template T of object
25 *
26 * @param array<array-key, object|array<array-key, object|scalar|null>|scalar|null> $items
27 * @param list<class-string<T>> $classes
28 *
29 * @return ($minimum is positive-int ? non-empty-list<T> : list<T>)
30 *
31 * @throws InvalidConstruction When the argument is not a list of the admitted classes, or is shorter than the minimum
32 */
33 public function of(array $items, array $classes, string $message, int $minimum = 0): array
34 {
35 $list = [];
36 foreach ($items as $item) {
37 $accepted = null;
38 foreach ($classes as $class) {
39 if ($item instanceof $class) {
40 $accepted = $item;
41 }
42 }
43 if ($accepted === null) {
44 throw new InvalidConstruction($message);
45 }
46 $list[] = $accepted;
47 }
48 if (!array_is_list($items) || count($list) < $minimum) {
49 throw new InvalidConstruction($message);
50 }
51
52 return $list;
53 }
54}
55