@@ -251,6 +251,92 @@ public function providerCanDetermineKeyExists(): Generator
251251 ];
252252 }
253253
254+ /**
255+ * Tests that the helper will return default with key not found.
256+ *
257+ * @covers ::get()
258+ */
259+ public function testCanReturnDefaultWhenGetArrayValueByKeyNotFound () : void
260+ {
261+ $ this ->assertNull (ArrayHelper::get ([], 'key ' ), 'ArrayHelper::get() does not return null by default as expected ' );
262+ $ this ->assertEquals ('myDefault ' , ArrayHelper::get ([], 'key ' , 'myDefault ' ));
263+ $ this ->assertNotEquals ('myDefault ' , ArrayHelper::get (['key ' => 'value ' ], 'key ' , 'myDefault ' ));
264+ }
265+
266+ /**
267+ * Tests that can retrieve array value by key without PHP error/warning.
268+ *
269+ * @covers ::get()
270+ * @dataProvider providerCanGetArrayValueByKey
271+ *
272+ * @param mixed $array
273+ * @param int|string $key
274+ * @param mixed $expected
275+ * @return void
276+ */
277+ public function testCanGetArrayValueByKey ($ array , $ key , $ expected ) : void
278+ {
279+ $ this ->assertSame ($ expected , ArrayHelper::get ($ array , $ key ));
280+ }
281+
282+ /** @see testCanGetArrayValueByKey() */
283+ public function providerCanGetArrayValueByKey () : Generator
284+ {
285+ yield 'Existing string key in a key/value array ' => [
286+ 'array ' => ['key ' => 'found ' ],
287+ 'key ' => 'key ' ,
288+ 'expected ' => 'found ' ,
289+ ];
290+
291+ yield 'Nonexistent string key in a key/value array ' => [
292+ 'array ' => ['key ' => 'notfound ' ],
293+ 'key ' => 'value ' ,
294+ 'expected ' => null ,
295+ ];
296+
297+ yield 'Existing nested key with dot notation ' => [
298+ 'array ' => ['key ' => ['nested ' => ['deeply ' => 'found ' ]]],
299+ 'key ' => 'key.nested.deeply ' ,
300+ 'expected ' => 'found ' ,
301+ ];
302+
303+ yield 'Nonexistent nested key with dot notation ' => [
304+ 'array ' => ['key ' => ['nested ' => ['deeply ' => 'notfound ' ]]],
305+ 'key ' => 'key.nested.more.deeply ' ,
306+ 'expected ' => null ,
307+ ];
308+
309+ yield 'Existing dot-notated key as key is returned without iteration ' => [
310+ 'array ' => ['dot.notated.key ' => 'found ' ],
311+ 'key ' => 'dot.notated.key ' ,
312+ 'expected ' => 'found ' ,
313+ ];
314+
315+ yield 'Existing numeric index ' => [
316+ 'array ' => ['foo ' , 'bar ' , 'baz ' ],
317+ 'key ' => 1 ,
318+ 'expected ' => 'bar ' ,
319+ ];
320+
321+ yield 'Nonexistent numeric index ' => [
322+ 'array ' => ['foo ' , 'bar ' , 'baz ' ],
323+ 'key ' => 3 ,
324+ 'expected ' => null ,
325+ ];
326+
327+ yield 'Existing numeric string index ' => [
328+ 'array ' => ['foo ' , 'bar ' , 'baz ' ],
329+ 'key ' => '2 ' ,
330+ 'expected ' => 'baz ' ,
331+ ];
332+
333+ yield 'Nonexistent numeric string index ' => [
334+ 'array ' => ['foo ' , 'bar ' , 'baz ' ],
335+ 'key ' => '3 ' ,
336+ 'expected ' => null ,
337+ ];
338+ }
339+
254340 protected function getArrayAccessObject (): ArrayAccess
255341 {
256342 return new class implements ArrayAccess
0 commit comments