Skip to content
This repository has been archived by the owner on Mar 27, 2022. It is now read-only.

Commit

Permalink
Add option to set root name
Browse files Browse the repository at this point in the history
  • Loading branch information
DASPRiD committed Apr 6, 2017
1 parent 282ab97 commit 52816a4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
6 changes: 3 additions & 3 deletions src/TreeReader.php
Expand Up @@ -18,10 +18,10 @@ final class TreeReader
*/
private $parentKeys;

public function __construct(array $data, string ...$parentKeys)
public function __construct(array $data, string $name = 'root', string ...$parentKeys)
{
$this->data = $data;
$this->parentKeys = $parentKeys;
$this->parentKeys = array_merge($parentKeys, [$name]);
}

public function hasKey(string $key) : bool
Expand Down Expand Up @@ -56,7 +56,7 @@ public function getBool(string $key, bool $default = null) : bool

public function getChildren(string $key, array $default = null) : self
{
return new TreeReader($this->getValue($key, 'array', $default), ...array_merge($this->parentKeys, [$key]));
return new TreeReader($this->getValue($key, 'array', $default), $key, ...$this->parentKeys);
}

private function getValue(string $key, string $expectedType, $default)
Expand Down
13 changes: 11 additions & 2 deletions test/TreeReaderTest.php
Expand Up @@ -137,7 +137,7 @@ public function testChildrenValidValue(string $method, array $value, array $defa
{
$treeReader = new TreeReader(['foo' => $value]);
$children = $treeReader->{$method}('foo', $default);
$this->assertAttributeSame(['foo'], 'parentKeys', $children);
$this->assertAttributeSame(['root', 'foo'], 'parentKeys', $children);
$this->assertAttributeSame($value, 'data', $children);
}

Expand All @@ -146,7 +146,16 @@ public function testKeyNotFoundExceptionWithMultipleParents()
$treeReader = new TreeReader(['foo' => ['bar' => []]]);

$this->expectException(KeyNotFoundException::class);
$this->expectExceptionMessage('in tree "foo->bar"');
$this->expectExceptionMessage('in tree "root->foo->bar"');
$treeReader->getChildren('foo')->getChildren('bar')->getString('baz');
}

public function testKeyNotFoundExceptionWithMultipleParentsAndAlternativeRootName()
{
$treeReader = new TreeReader(['foo' => ['bar' => []]], 'config');

$this->expectException(KeyNotFoundException::class);
$this->expectExceptionMessage('in tree "config->foo->bar"');
$treeReader->getChildren('foo')->getChildren('bar')->getString('baz');
}
}

0 comments on commit 52816a4

Please sign in to comment.