Skip to content
Snippets Groups Projects
Commit 9c253bb1 authored by Beau Simensen's avatar Beau Simensen
Browse files

Merge pull request #4 from cfrutos/master

Adding has() method
parents 7a0960d0 ec305d27
No related branches found
No related tags found
No related merge requests found
language: php
php:
- 5.3.3
- 5.3
- 5.4
- 5.5
......
......@@ -33,6 +33,12 @@ $data->get('a.b.d');
// array('E0', 'E1', 'E2')
$data->get('a.b.e');
// true
$data->has('a.b.c');
// false
$data->has('a.b.d.j');
```
A more concrete example:
......@@ -92,6 +98,9 @@ $data->set('hosts.april', array(
'password' => '@---S',
'roles' => array('web'),
));
// Check if a key exists (true to this case)
$hasKey = $data->has('hosts.dewey.username');
```
......
......@@ -15,6 +15,11 @@
"name": "Beau Simensen",
"email": "beau@dflydev.com",
"homepage": "http://beausimensen.com"
},
{
"name": "Carlos Frutos",
"email": "carlos@kiwing.it",
"homepage": "https://github.com/cfrutos"
}
],
"require": {
......
......@@ -159,6 +159,28 @@ class Data implements DataInterface
return $currentValue === null ? $default : $currentValue;
}
/**
* {@inheritdoc}
*/
public function has($key)
{
$currentValue = &$this->data;
$keyPath = explode('.', $key);
for ( $i = 0; $i < count($keyPath); $i++ ) {
$currentKey = $keyPath[$i];
if (
!is_array($currentValue) ||
!isset($currentValue[$currentKey])
) {
return false;
}
$currentValue = &$currentValue[$currentKey];
}
return true;
}
/**
* {@inheritdoc}
*/
......
......@@ -46,6 +46,15 @@ interface DataInterface
*/
public function get($key, $default = null);
/**
* Check if the key exists
*
* @param string $key
*
* @return bool
*/
public function has($key);
/**
* Get a data instance for a key
*
......
......@@ -146,6 +146,23 @@ class DataTest extends \PHPUnit_Framework_TestCase
$this->runSampleDataTests($data);
}
public function testHas()
{
$data = new Data($this->getSampleData());
foreach (
array('a', 'i', 'b.d', 'f.g.h', 'h.i', 'b.d.d1') as $existentKey
) {
$this->assertTrue($data->has($existentKey));
}
foreach (
array('p', 'b.b1', 'b.c.C1', 'h.i.I', 'b.d.d1.D1') as $notExistentKey
) {
$this->assertFalse($data->has($notExistentKey));
}
}
public function testGetData()
{
$wrappedData = new Data(array(
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment