Skip to content

Commit 00d69fe

Browse files
authored
Merge pull request #13 from webdevium/from-flatten
Add auto parsing flat arrays when constructing Dot object
2 parents 6863e72 + 4ac28ef commit 00d69fe

File tree

4 files changed

+29
-5
lines changed

4 files changed

+29
-5
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,9 @@ $dot = new \Adbar\Dot;
5454

5555
// With existing array
5656
$dot = new \Adbar\Dot($array);
57+
58+
// Or with auto parsing dot notation keys in existing array
59+
$dot = new \Adbar\Dot($array, true);
5760
```
5861

5962
You can also use a helper function to create the object:
@@ -62,6 +65,9 @@ $dot = dot();
6265

6366
// With existing array
6467
$dot = dot($array);
68+
69+
// Or with auto parsing dot notation keys in existing array
70+
$dot = dot($array, true);
6571
```
6672

6773
## Methods

src/Dot.php

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,17 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
3333
* Create a new Dot instance
3434
*
3535
* @param mixed $items
36+
* @param bool $parse
3637
*/
37-
public function __construct($items = [])
38+
public function __construct($items = [], $parse = false)
3839
{
39-
$this->items = $this->getArrayItems($items);
40+
$items = $this->getArrayItems($items);
41+
if ($parse === true) {
42+
$this->set($items);
43+
return;
44+
}
45+
46+
$this->items = $items;
4047
}
4148

4249
/**
@@ -202,7 +209,9 @@ protected function getArrayItems($items)
202209
{
203210
if (is_array($items)) {
204211
return $items;
205-
} elseif ($items instanceof self) {
212+
}
213+
214+
if ($items instanceof self) {
206215
return $items->all();
207216
}
208217

src/helpers.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,11 @@
1414
* Create a new Dot object with the given items
1515
*
1616
* @param mixed $items
17+
* @param bool $parse
1718
* @return \Adbar\Dot
1819
*/
19-
function dot($items)
20+
function dot($items, $parse = false)
2021
{
21-
return new Dot($items);
22+
return new Dot($items, $parse);
2223
}
2324
}

tests/DotTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,14 @@ public function testConstructHelper()
5656
$this->assertEquals('bar', $dot->get('foo'));
5757
}
5858

59+
public function testConstructWithParsing()
60+
{
61+
$dot = new Dot(['foo.bar' => 'baz']);
62+
$this->assertEquals(['foo.bar' => 'baz'], $dot->get());
63+
$dot = new Dot(['foo.bar' => 'baz'], true);
64+
$this->assertEquals(['foo' => ['bar' => 'baz']], $dot->get());
65+
}
66+
5967
/*
6068
* --------------------------------------------------------------
6169
* Add

0 commit comments

Comments
 (0)