Skip to content

Commit 24f7fcc

Browse files
author
Benno Eggnauer
committed
Add a default value to the getter.
1 parent e66b3b0 commit 24f7fcc

File tree

3 files changed

+9
-6
lines changed

3 files changed

+9
-6
lines changed

src/Dflydev/DotAccessData/Data.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -140,23 +140,23 @@ public function remove($key)
140140
/**
141141
* {@inheritdoc}
142142
*/
143-
public function get($key)
143+
public function get($key, $default = null)
144144
{
145145
$currentValue = $this->data;
146146
$keyPath = explode('.', $key);
147147

148148
for ( $i = 0; $i < count($keyPath); $i++ ) {
149149
$currentKey = $keyPath[$i];
150150
if (!isset($currentValue[$currentKey]) ) {
151-
return null;
151+
return $default;
152152
}
153153
if (!is_array($currentValue)) {
154-
return null;
154+
return $default;
155155
}
156156
$currentValue = $currentValue[$currentKey];
157157
}
158158

159-
return $currentValue;
159+
return $currentValue === null ? $default : $currentValue;
160160
}
161161

162162
/**

src/Dflydev/DotAccessData/DataInterface.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,11 @@ public function remove($key);
4040
* Get the raw value for a key
4141
*
4242
* @param string $key
43+
* @param mixed $default
4344
*
4445
* @return mixed
4546
*/
46-
public function get($key);
47+
public function get($key, $default = null);
4748

4849
/**
4950
* Get a data instance for a key

tests/Dflydev/DotAccessData/DataTest.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
/*
44
* This file is a part of dflydev/dot-access-data.
5-
*
5+
*
66
* (c) Dragonfly Development Inc.
77
*
88
* For the full copyright and license information, please view the LICENSE
@@ -50,6 +50,8 @@ protected function runSampleDataTests(DataInterface $data)
5050
$this->assertEquals(array('c1', 'c2', 'c3'), $data->get('c'));
5151
$this->assertNull($data->get('foo'), 'Foo should not exist');
5252
$this->assertNull($data->get('f.g.h.i'));
53+
$this->assertEquals($data->get('foo', 'default-value-1'), 'default-value-1', 'Return default value');
54+
$this->assertEquals($data->get('f.g.h.i', 'default-value-2'), 'default-value-2');
5355
}
5456

5557
public function testAppend()

0 commit comments

Comments
 (0)