File tree 2 files changed +105
-0
lines changed
spec/drupol/phptree/Importer
2 files changed +105
-0
lines changed Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ declare (strict_types = 1 );
4
+
5
+ namespace spec \drupol \phptree \Importer ;
6
+
7
+ use drupol \phptree \Importer \SimpleArray ;
8
+ use drupol \phptree \Node \NodeInterface ;
9
+ use PhpSpec \ObjectBehavior ;
10
+
11
+ class SimpleArraySpec extends ObjectBehavior
12
+ {
13
+ public function it_is_initializable ()
14
+ {
15
+ $ this ->shouldHaveType (SimpleArray::class);
16
+ }
17
+
18
+ public function it_can_import ()
19
+ {
20
+ $ array = [
21
+ 'value ' => 'root ' ,
22
+ 'children ' => [
23
+ 0 => [
24
+ 'value ' => 'child1 ' ,
25
+ ],
26
+ 1 => [
27
+ 'value ' => 'child2 ' ,
28
+ ],
29
+ ],
30
+ ];
31
+
32
+ $ this
33
+ ->import ($ array )
34
+ ->shouldImplement (NodeInterface::class);
35
+
36
+ $ this
37
+ ->import ($ array )
38
+ ->count ()
39
+ ->shouldReturn (2 );
40
+
41
+ $ this
42
+ ->import ($ array )
43
+ ->isRoot ()
44
+ ->shouldReturn (TRUE );
45
+ }
46
+ }
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ declare (strict_types = 1 );
4
+
5
+ namespace drupol \phptree \Importer ;
6
+
7
+ use drupol \phptree \Node \Node ;
8
+ use drupol \phptree \Node \NodeInterface ;
9
+
10
+ /**
11
+ * Class SimpleArray
12
+ */
13
+ class SimpleArray implements ImporterInterface
14
+ {
15
+ /**
16
+ * {@inheritdoc}
17
+ */
18
+ public function import ($ data ): NodeInterface
19
+ {
20
+ return $ this ->arrayToTree ($ data );
21
+ }
22
+
23
+ /**
24
+ * Convert an array into a tree.
25
+ *
26
+ * @param array $data
27
+ *
28
+ * @return \drupol\phptree\Node\NodeInterface
29
+ * The tree.
30
+ */
31
+ protected function arrayToTree (array $ data ): NodeInterface
32
+ {
33
+ $ data += [
34
+ 'children ' => [],
35
+ ];
36
+
37
+ $ node = $ this ->createNode ($ data ['value ' ]);
38
+
39
+ foreach ($ data ['children ' ] as $ key => $ child ) {
40
+ $ node ->add ($ this ->arrayToTree ($ child ));
41
+ }
42
+
43
+ return $ node ;
44
+ }
45
+
46
+ /**
47
+ * Create a node.
48
+ *
49
+ * @param mixed $data
50
+ * The arguments.
51
+ *
52
+ * @return \drupol\phptree\Node\NodeInterface
53
+ * The node.
54
+ */
55
+ protected function createNode ($ data ): NodeInterface
56
+ {
57
+ return new Node ();
58
+ }
59
+ }
You can’t perform that action at this time.
0 commit comments