File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -161,22 +161,25 @@ public function changeSeparator($separator)
161161
162162 /**
163163 * Return a value from the array corresponding to the path.
164+ * If the path is not set in the array, then $default is returned.
164165 *
165166 * ex:
166167 * $a = ['a' => ['b' => 'yeah']];
167168 * echo $this->get('a.b'); // yeah
169+ * echo $this->get('a.b.c', 'nope'); // nope
168170 *
169171 * @param string|int|null $path Path to the value. If null, return all the content.
172+ * @param mixed $default Default value to return when path is not contained in the array.
170173 *
171174 * @return mixed|null Value on the array corresponding to the path, null if the key does not exist.
172175 */
173- public function get ($ path = null )
176+ public function get ($ path = null , $ default = null )
174177 {
175178 if ($ path === null ) {
176179 return $ this ->content ;
177180 }
178181
179- $ value = null ;
182+ $ value = $ default ;
180183 $ this ->callAtPath ($ path , function (&$ offset ) use (&$ value ) {
181184 $ value = $ offset ;
182185 });
Original file line number Diff line number Diff line change @@ -229,4 +229,21 @@ public function testGetWithoutParamWillReturnAllTheArray()
229229
230230 $ this ->assertEquals ('end ' , $ content ['a ' ]['b ' ]['c ' ]);
231231 }
232+
233+ public function testGetAcceptsADefaultArgument ()
234+ {
235+ // ensure the default value is not returned when
236+ // the array does have the key
237+ $ this ->assertEquals (
238+ "is defined " ,
239+ (new ArrayFinder (["some " => ["key " => "is defined " ]]))->get ("some.key " , "default value " )
240+ );
241+
242+ // ensure that when the key is not defined, the default
243+ // value is used
244+ $ this ->assertEquals (
245+ "default value " ,
246+ (new ArrayFinder ([]))->get ("some.key " , "default value " )
247+ );
248+ }
232249}
You can’t perform that action at this time.
0 commit comments