11
11
12
12
namespace Linna \TypedArrayObject ;
13
13
14
- use ArrayObject ;
15
14
use InvalidArgumentException ;
16
15
17
16
/**
18
17
* Provide a way for create an array of typed elements with php.
19
18
*/
20
- class ArrayOfClasses extends ArrayObject
19
+ class ArrayOfClasses extends AbstractArray
21
20
{
22
21
/**
23
22
* @var string Current type for array
24
23
*/
25
24
protected string $ class ;
25
+
26
+ /**
27
+ * It overrides parent message
28
+ * @var string Exception message
29
+ */
26
30
protected string $ exceptionMessage ;
27
31
28
32
@@ -40,56 +44,24 @@ public function __construct(string $class, array $input = [], int $flags = 0, st
40
44
{
41
45
$ this ->class = $ class ;
42
46
$ this ->exceptionMessage = "Elements passed must be of the type < {$ class }>. " ;
43
-
44
- if (!\class_exists ($ class )) {
45
- throw new InvalidArgumentException ("Type < {$ this ->class }> provided isn't a class. " );
46
- }
47
-
48
- if (!\array_product (\array_map (function ($ x ) use ($ class ) {
49
- return $ x instanceof $ class ;
50
- }, $ input ))) {
51
- throw new InvalidArgumentException ($ this ->exceptionMessage );
52
- }
53
-
54
- parent ::__construct ($ input , $ flags , $ iterator_class );
55
- }
56
-
57
- /**
58
- * Array style value assignment.
59
- *
60
- * @ignore
61
- *
62
- * @param mixed $index
63
- * @param object $newval
64
- *
65
- * @throws InvalidArgumentException If value passed with $newval are not of the expected type
66
- *
67
- * @return void
68
- */
69
- public function offsetSet ($ index , $ newval ): void
70
- {
71
- if (!($ newval instanceof $ this ->class )) {
72
- throw new InvalidArgumentException ($ this ->exceptionMessage );
73
- }
74
-
75
- parent ::offsetSet ($ index , $ newval );
47
+ // first argument is the php8.1 method to pass function reference as closure.
48
+ // check https://www.php.net/manual/en/functions.first_class_callable_syntax.php
49
+ parent ::__construct ($ this ->is_class (...), $ input , $ flags , $ iterator_class );
76
50
}
77
51
78
52
/**
79
- * Append a value at the end of the array.
80
- *
81
- * @param object $value
53
+ * Check if argument is instance of specific class.
82
54
*
83
- * @return void
55
+ * @param mixed $value
84
56
*
85
- * @throws InvalidArgumentException If value passed with $value are not of the expected type
57
+ * @return bool
86
58
*/
87
- public function append ( $ value ): void
59
+ protected function is_class ( mixed $ value ): bool
88
60
{
89
- if (!( $ value instanceof $ this ->class ) ) {
90
- throw new InvalidArgumentException ( $ this -> exceptionMessage ) ;
61
+ if ($ value instanceof $ this ->class ) {
62
+ return true ;
91
63
}
92
64
93
- parent :: append ( $ value ) ;
65
+ return false ;
94
66
}
95
67
}
0 commit comments