1414
1515class GeometryCollection extends Geometry implements IteratorAggregate, ArrayAccess, Arrayable, Countable
1616{
17+ /**
18+ * The minimum number of items required to create this collection.
19+ *
20+ * @var int
21+ */
22+ protected $ minimumCollectionItems = 1 ;
23+
24+ /**
25+ * The class of the items in the collection.
26+ *
27+ * @var string
28+ */
29+ protected $ collectionItemType = GeometryInterface::class;
30+
1731 /**
1832 * The items contained in the spatial collection.
1933 *
@@ -28,13 +42,7 @@ class GeometryCollection extends Geometry implements IteratorAggregate, ArrayAcc
2842 */
2943 public function __construct (array $ geometries )
3044 {
31- $ validated = array_filter ($ geometries , function ($ value ) {
32- return $ value instanceof GeometryInterface;
33- });
34-
35- if (count ($ geometries ) !== count ($ validated )) {
36- throw new InvalidArgumentException ('$geometries must be an array of Geometry objects ' );
37- }
45+ $ this ->validateItems ($ geometries );
3846
3947 $ this ->items = $ geometries ;
4048 }
@@ -89,9 +97,7 @@ public function offsetGet($offset)
8997
9098 public function offsetSet ($ offset , $ value )
9199 {
92- if (!($ value instanceof GeometryInterface)) {
93- throw new InvalidArgumentException ('$value must be an instance of GeometryInterface ' );
94- }
100+ $ this ->validateItemType ($ value );
95101
96102 if (is_null ($ offset )) {
97103 $ this ->items [] = $ value ;
@@ -142,4 +148,33 @@ public function jsonSerialize()
142148
143149 return new \GeoJson \Geometry \GeometryCollection ($ geometries );
144150 }
151+
152+ /**
153+ * Checks
154+ * @param array $items
155+ */
156+ protected function validateItems (array $ items ) {
157+ $ this ->validateItemCount ($ items );
158+
159+ foreach ($ items as $ item ) {
160+ $ this ->validateItemType ($ item );
161+ }
162+ }
163+
164+ protected function validateItemCount (array $ items ) {
165+ if (count ($ items ) < $ this ->minimumCollectionItems ) {
166+ $ entries = $ this ->minimumCollectionItems === 1 ? 'entry ' : 'entries ' ;
167+ throw new InvalidArgumentException (sprintf (
168+ '%s must contain at least %d %s ' , get_class ($ this ), $ this ->minimumCollectionItems , $ entries
169+ ));
170+ }
171+ }
172+
173+ protected function validateItemType ($ item ) {
174+ if (!$ item instanceof $ this ->collectionItemType ) {
175+ throw new InvalidArgumentException (sprintf (
176+ '%s must be a collection of %s ' , get_class ($ this ), $ this ->collectionItemType
177+ ));
178+ }
179+ }
145180}
0 commit comments