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,48 @@ public function jsonSerialize()
142148
143149 return new \GeoJson \Geometry \GeometryCollection ($ geometries );
144150 }
151+
152+ /**
153+ * Checks whether the items are valid to create this collection.
154+ *
155+ * @param array $items
156+ */
157+ protected function validateItems (array $ items ) {
158+ $ this ->validateItemCount ($ items );
159+
160+ foreach ($ items as $ item ) {
161+ $ this ->validateItemType ($ item );
162+ }
163+ }
164+
165+ /**
166+ * Checks whether the array has enough items to generate a valid WKT.
167+ *
168+ * @param array $items
169+ *
170+ * @see $minimumCollectionItems
171+ */
172+ protected function validateItemCount (array $ items ) {
173+ if (count ($ items ) < $ this ->minimumCollectionItems ) {
174+ $ entries = $ this ->minimumCollectionItems === 1 ? 'entry ' : 'entries ' ;
175+ throw new InvalidArgumentException (sprintf (
176+ '%s must contain at least %d %s ' , get_class ($ this ), $ this ->minimumCollectionItems , $ entries
177+ ));
178+ }
179+ }
180+
181+ /**
182+ * Checks the type of the items in the array.
183+ *
184+ * @param $item
185+ *
186+ * @see $collectionItemType
187+ */
188+ protected function validateItemType ($ item ) {
189+ if (!$ item instanceof $ this ->collectionItemType ) {
190+ throw new InvalidArgumentException (sprintf (
191+ '%s must be a collection of %s ' , get_class ($ this ), $ this ->collectionItemType
192+ ));
193+ }
194+ }
145195}
0 commit comments