package Code::Includable::Tree::FromStruct;

our $DATE = '2016-03-23'; # DATE
our $VERSION = '0.04'; # VERSION

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

    my $wanted_class = $struct->{_class} || $role_class;

    my @args;
    if ($struct->{_args}) {
        @args = @{ $struct->{_args} };
    } else {
        @args = map { $_ => $struct->{$_} } grep {!/^_/} keys %$struct;
    }

    my $constructor = $struct->{_constructor} || "new";

    my $node = $wanted_class->$constructor(@args);

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

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

    $node;
}

1;
# ABSTRACT: Routine to build tree object from struct

__END__

=pod

=encoding UTF-8

=head1 NAME

Code::Includable::Tree::FromStruct - Routine to build tree object from struct

=head1 VERSION

This document describes version 0.04 of Code::Includable::Tree::FromStruct (from Perl distribution Role-TinyCommons-Tree), released on 2016-03-23.

=for Pod::Coverage .+

The routines in this module can be imported manually to your tree class/role.
The only requirement is that your tree class supports C<parent> and C<children>
methods.

The routines can also be called as a normal function call, with your tree node
object as the first argument, e.g.:

 new_from_struct($class, $struct)

=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 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
