1package Tree::Simple::Visitor::FromNestedArray;
2
3use strict;
4use warnings;
5
6our $VERSION = '0.16';
7
8use Scalar::Util qw(blessed);
9
10use base qw(Tree::Simple::Visitor);
11
12sub new {
13    my ($_class) = @_;
14    my $class = ref($_class) || $_class;
15    my $visitor = {};
16    bless($visitor, $class);
17    $visitor->_init();
18    return $visitor;
19}
20
21sub _init {
22    my ($self) = @_;
23    $self->{array_tree} = undef;
24    $self->SUPER::_init();
25}
26
27sub setArrayTree {
28    my ($self, $array_tree) = @_;
29    (defined($array_tree) && ref($array_tree) eq 'ARRAY')
30        || die "Insufficient Arguments : You must supply a valid ARRAY reference";
31    # validate the tree ...
32    # it must not be empty
33    (scalar @{$array_tree} != 0)
34        || die "Insufficient Arguments : The array tree provided is empty";
35    # it's first element must not be an array
36    (ref($array_tree->[0]) ne 'ARRAY')
37        || die "Incorrect Object Type : The first value in the array tree is an array reference";
38    # and it must be a single rooted tree
39    (ref($array_tree->[1]) eq 'ARRAY')
40        || die "Incorrect Object Type : The second value in the array tree must be an array reference"
41            if defined($array_tree->[1]);
42    $self->{array_tree} = $array_tree;
43}
44
45sub visit {
46	my ($self, $tree) = @_;
47	(blessed($tree) && $tree->isa("Tree::Simple"))
48		|| die "Insufficient Arguments : You must supply a valid Tree::Simple object";
49	$self->_buildTree(
50                $tree,
51                # our array tree
52                $self->{array_tree},
53                # get a node filter if we have one
54                $self->getNodeFilter(),
55                # pass the value of includeTrunk too
56                $self->includeTrunk()
57                );
58}
59
60sub _buildTree {
61    my ($self, $tree, $array, $node_filter, $include_trunk) = @_;
62    my $i = 0;
63    while ($i < scalar @{$array}) {
64        my $node = $array->[$i];
65        # check to make sure we have a well formed tree
66        (ref($node) ne 'ARRAY')
67            || die "Incorrect Object Type : The node value should never be an array reference";
68        # filter the node if necessary
69        $node = $node_filter->($node) if defined($node_filter);
70        # create the new tree
71        my $new_tree;
72        if ($include_trunk) {
73            $tree->setNodeValue($node);
74            $new_tree = $tree;
75        }
76        else {
77            $new_tree = Tree::Simple->new($node);
78            $tree->addChild($new_tree);
79        }
80        # increment the index value
81        $i++;
82        # NOTE:
83        # the value of include trunk is only
84        # passed in the recursion, so that
85        # the trunk/root can be populated,
86        # we have no more need for it after
87        # that time.
88        $self->_buildTree($new_tree, $array->[$i++], $node_filter)
89            if ref($array->[$i]) eq 'ARRAY';
90    }
91}
92
931;
94
95__END__
96
97=head1 NAME
98
99Tree::Simple::Visitor::FromNestedArray - A Visitor for creating Tree::Simple objects from nested array trees.
100
101=head1 SYNOPSIS
102
103  use Tree::Simple::Visitor::FromNestedArray;
104
105  my $visitor = Tree::Simple::Visitor::FromNestedArray->new();
106
107  # given this nested array tree
108  my $array_tree = [
109                    'Root', [
110                        'Child1', [
111                                'GrandChild1',
112                                'GrandChild2'
113                                ],
114                        'Child2'
115                        ]
116                    ];
117  # set the array tree we
118  # are going to convert
119  $visitor->setArrayTree($array_tree);
120
121  $tree->accept($visitor);
122
123  # this then creates the equivalent Tree::Simple object:
124  # Tree::Simple->new("Root")
125  #     ->addChildren(
126  #         Tree::Simple->new("Child1")
127  #             ->addChildren(
128  #                 Tree::Simple->new("GrandChild1"),
129  #                 Tree::Simple->new("GrandChild2")
130  #             ),
131  #         Tree::Simple->new("Child2"),
132  #     );
133
134=head1 DESCRIPTION
135
136Given a tree constructed from nested arrays, this Visitor will create the equivalent Tree::Simple hierarchy.
137
138=head1 METHODS
139
140=over 4
141
142=item B<new>
143
144There are no arguments to the constructor the object will be in its default state. You can use the C<setNodeFilter>, C<includTrunk> and C<setArrayTree> methods to customize its behavior.
145
146=item B<includTrunk ($boolean)>
147
148Setting the C<$boolean> value to true (C<1>) will cause the node value of the C<$tree> object passed into C<visit> to be set with the root value found in the C<$array_tree>. Setting it to false (C<0>), or not setting it, will result in the first value in the C<$array_tree> creating a new node level.
149
150=item B<setNodeFilter ($filter_function)>
151
152This method accepts a CODE reference as its C<$filter_function> argument and throws an exception if it is not a code reference. This code reference is used to filter the tree nodes as they are created, the C<$filter_function> is passed the node value extracted from the array prior to it being inserted into the tree being built. The C<$filter_function> is expected to return the value desired for inclusion into the tree.
153
154=item B<setArrayTree ($array_tree)>
155
156This method is used to set the C<$array_tree> that our Tree::Simple hierarchy will be constructed from. It must be in the following form:
157
158  [
159    'Root', [
160        'Child1', [
161              'GrandChild1',
162              'GrandChild2'
163              ],
164        'Child2'
165      ]
166  ]
167
168Basically each element in the array is considered a node, unless it is an array reference, in which case it is interpreted as containing the children of the node created from the previous element in the array.
169
170The tree is validated prior being accepted, if it fails validation an exception will be thrown. The rules are as follows;
171
172=over 4
173
174=item The array tree must not be empty.
175
176It makes not sense to create a tree out of nothing, so it is assumed that this is a sign of something wrong.
177
178=item All nodes of the array tree must not be array references.
179
180The root node is validated against this in this function, but all subsequent nodes are checked as the tree is built. Any nodes found to be array references are rejected and an exception is thrown. If you desire your node values to be array references, you can use the node filtering mechanism to achieve this as the node is filtered I<after> it is validated.
181
182=item The array tree must be a single rooted tree.
183
184If there is a second element in the array tree, it is assumed to be the children of the root, and therefore must be in the form of an array reference.
185
186=back
187
188=item B<visit ($tree)>
189
190This is the method that is used by the Tree::Simple C<accept> method. It can also be used on its
191own, it requires the C<$tree> argument to be a Tree::Simple object (or derived from a
192Tree::Simple object), and will throw and exception otherwise.
193
194=back
195
196=head1 BUGS
197
198None that I am aware of. Of course, if you find a bug, let me know, and I will be sure to fix it.
199
200=head1 CODE COVERAGE
201
202See the B<CODE COVERAGE> section in L<Tree::Simple::VisitorFactory> for more information.
203
204=head1 SEE ALSO
205
206These Visitor classes are all subclasses of B<Tree::Simple::Visitor>, which can be found in the
207B<Tree::Simple> module, you should refer to that module for more information.
208
209=head1 AUTHOR
210
211stevan little, E<lt>stevan@iinteractive.comE<gt>
212
213=head1 COPYRIGHT AND LICENSE
214
215Copyright 2004, 2005 by Infinity Interactive, Inc.
216
217L<http://www.iinteractive.com>
218
219This library is free software; you can redistribute it and/or modify
220it under the same terms as Perl itself.
221
222=cut
223