File tree Expand file tree Collapse file tree 2 files changed +31
-4
lines changed
Expand file tree Collapse file tree 2 files changed +31
-4
lines changed Original file line number Diff line number Diff line change @@ -71,16 +71,28 @@ public function set($key, $value)
7171 /**
7272 * Get an item from the collection. Returns $default if item cannot be found.
7373 *
74- * @param string $key
74+ * Passing an array of item keys for the value of $key will result in multiple
75+ * items being returned. Keys that are missing from the collection will be
76+ * returned with a value of $default.
77+ *
78+ * @param mixed $key
7579 * @param mixed $default
7680 * @return mixed Will return $default if cannot find item
7781 */
7882 public function get ($ key , $ default = null )
7983 {
80- if (isset ($ this ->items [$ key ])) {
81- return $ this ->items [$ key ];
84+ if (is_array ($ key )) {
85+ // Get multiple items by their key
86+ $ items = [];
87+ foreach ($ key as $ k ) {
88+ $ items [$ k ] = isset ($ this ->items [$ k ]) ? $ this ->items [$ k ] : $ default ;
89+ }
90+
91+ return $ items ;
92+ } else {
93+ // Get a single item by its key
94+ return isset ($ this ->items [$ key ]) ? $ this ->items [$ key ] : $ default ;
8295 }
83- return $ default ;
8496 }
8597
8698 /**
Original file line number Diff line number Diff line change @@ -221,4 +221,19 @@ public function testMagicMethods()
221221 unset($ collection ['key1 ' ]);
222222 $ this ->assertFalse ($ collection ->has ('key1 ' ));
223223 }
224+
225+ /**
226+ * @covers Collection::get
227+ */
228+ public function testGetMultipleItems ()
229+ {
230+ $ collection = new Collection (['key1 ' => 'value1 ' , 'key2 ' => 'value2 ' ]);
231+ $ values = $ collection ->get (['key1 ' , 'key2 ' , 'key3 ' ]);
232+
233+ $ this ->assertTrue (array_key_exists ('key1 ' , $ values ) && $ values ['key1 ' ] == 'value1 ' );
234+ $ this ->assertTrue (array_key_exists ('key2 ' , $ values ) && $ values ['key2 ' ] == 'value2 ' );
235+
236+ // Assert the key3 equals the default (null)
237+ $ this ->assertTrue (array_key_exists ('key3 ' , $ values ) && $ values ['key3 ' ] == null );
238+ }
224239}
You can’t perform that action at this time.
0 commit comments