package Role::TinyCommons::Tree::FromStruct;

our $DATE = '2016-03-22'; # DATE
our $VERSION = '0.02'; # VERSION

use Role::Tiny;

sub new_from_struct {
    my $role_class = shift;
    my $struct = shift;

    my $wanted_class = $struct->{_class} || $role_class;
    my %args = map { $_ => $struct->{$_} } grep {!/^_/} keys %$struct;

    my $node = $wanted_class->new(%args);

    $node->parent($struct->{_parent}) if $struct->{_parent};

    if ($struct->{_children}) {
        my @children;
        for my $child_struct (@{ $struct->{_children} }) {
            push @children, $role_class->new_from_struct(
                {%$child_struct, _parent => $node},
            );
        }
        $node->children(@children);
    }

    $node;
}

1;
# ABSTRACT: Role that provides methods to build tree object from data structure

__END__

=pod

=encoding UTF-8

=head1 NAME

Role::TinyCommons::Tree::FromStruct - Role that provides methods to build tree object from data structure

=head1 VERSION

This document describes version 0.02 of Role::TinyCommons::Tree::FromStruct (from Perl distribution Role-TinyCommons-Tree), released on 2016-03-22.

=head1 PROVIDED METHODS

=head2 new_from_struct($struct) => obj

Construct a tree object from a data structure C<$struct>. Structure must be a
hash. Node object will be constructed using:

 $class->new(%args)

where role consumer's class will be used as the new node object's class, unless
there's a key called C<_class> to set the class. C<%args> will be taken from the
hash's keys that are not prefixed with underscore. Node's children can be
specified in the C<_children> key and the value is array of structures.

Example:

 my $family_tree = My::Person->new_from_struct({
     name => 'Andi', _children => [
         {name => 'Budi', age => 30},
         {name => 'Cinta', _class => 'My::MarriedPerson', _children => [
              {name => 'Deni'},
              {name => 'Eno'},
          ]},
     ]});

=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/Role-TinyCommons-Tree>.

=head1 SOURCE

Source repository is at L<https://github.com/perlancar/perl-Role-TinyCommons-TreeNode>.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website L<https://rt.cpan.org/Public/Dist/Display.html?Name=Role-TinyCommons-Tree>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=head1 SEE ALSO

L<Role::TinyCommons::Tree::Node>

L<Role::TinyCommons>

=head1 AUTHOR

perlancar <perlancar@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2016 by perlancar@cpan.org.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
