File tree 2 files changed +75
-0
lines changed
spec/drupol/phptree/Modifier
2 files changed +75
-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 \Modifier ;
6
+
7
+ use drupol \phptree \Modifier \Reverse ;
8
+ use drupol \phptree \Node \ValueNode ;
9
+ use PhpSpec \ObjectBehavior ;
10
+
11
+ class ReverseSpec extends ObjectBehavior
12
+ {
13
+ public function it_is_initializable ()
14
+ {
15
+ $ this ->shouldHaveType (Reverse::class);
16
+ }
17
+
18
+ public function it_can_reverse_a_tree ()
19
+ {
20
+ $ tree1 = new ValueNode ('root ' );
21
+
22
+ $ nodes = [];
23
+ foreach (\range ('A ' , 'E ' ) as $ value ) {
24
+ $ nodes [] = new ValueNode ($ value );
25
+ }
26
+ $ tree1 ->add (...$ nodes );
27
+
28
+ $ tree2 = new ValueNode ('root ' );
29
+ $ tree2 ->add (...\array_reverse ($ nodes ));
30
+
31
+ $ this
32
+ ->modify ($ tree1 )
33
+ ->count ()
34
+ ->shouldReturn (5 );
35
+
36
+ // @todo write better test here and test all children and recursively.
37
+ $ this
38
+ ->modify ($ tree1 )
39
+ ->children ()->current ()->getValue ()
40
+ ->shouldReturn ('E ' );
41
+ }
42
+ }
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ declare (strict_types = 1 );
4
+
5
+ namespace drupol \phptree \Modifier ;
6
+
7
+ use drupol \phptree \Node \NodeInterface ;
8
+
9
+ /**
10
+ * Class Reverse
11
+ */
12
+ class Reverse implements ModifierInterface
13
+ {
14
+ /**
15
+ * {@inheritdoc}
16
+ */
17
+ public function modify (NodeInterface $ tree ): NodeInterface
18
+ {
19
+ $ children = new \ArrayObject ();
20
+
21
+ foreach ($ tree ->children () as $ child ) {
22
+ $ children ->append ($ this ->modify ($ child ));
23
+ }
24
+
25
+ $ newTree = $ tree ->withChildren ();
26
+
27
+ for ($ i = $ children ->count ()-1 ; $ i >= 0 ; $ i --) {
28
+ $ newTree ->add ($ children [$ i ]);
29
+ }
30
+
31
+ return $ newTree ;
32
+ }
33
+ }
You can’t perform that action at this time.
0 commit comments