Commits

Shlomi Fish  committed eb6742a

Add the body of ToJSON.

  • Participants
  • Parent commits f4a2f0e

Comments (0)

Files changed (2)

File HTML-Widgets-NavMenu-ToJSON/Build.PL

         'Test::More' => 0,
     },
     requires => {
-        #'ABC'              => 1.6,
-        #'Foo::Bar::Module' => 5.0401,
+        'Carp' => 0,
+        'HTML::Widgets::NavMenu::Object' => 0,
+        'JSON' => 0,
+        'parent' => 0,
+        'strict' => 0,
+        'warnings' => 0,
     },
     add_to_cleanup     => [ 'HTML-Widgets-NavMenu-ToJSON-*' ],
     create_makefile_pl => 'traditional',

File HTML-Widgets-NavMenu-ToJSON/lib/HTML/Widgets/NavMenu/ToJSON.pm

 use strict;
 use warnings FATAL => 'all';
 
+use Carp;
+
+use parent 'HTML::Widgets::NavMenu::Object';
+
+use JSON qw(encode_json);
+
 =head1 NAME
 
 HTML::Widgets::NavMenu::ToJSON - convert HTML::Widgets::NavMenu to JSON
 
 our $VERSION = '0.0.1';
 
-
 =head1 SYNOPSIS
 
     use HTML::Widgets::NavMenu::ToJSON;
 
 =head1 SUBROUTINES/METHODS
 
+=cut
+
+__PACKAGE__->mk_acc_ref(
+    [
+        qw(
+        _data_persistence_store
+        _tree_contents
+        ),
+    ]
+);
+
+sub _init
+{
+    my ($self, $args) = @_;
+
+    $self->_data_persistence_store(
+        $args->{'data_persistence_store'}
+    ) or Carp::confess("No data_persistence_store specified.");
+
+    $self->_tree_contents(
+        $args->{'tree_contents'}
+    ) or Carp::confess("No tree_contents specified.");
+
+    return;
+}
+
+sub _get_id_for_url
+{
+    my ($self, $url) = @_;
+    return $self->_data_persistence_store->get_id_for_path($url);
+}
+
+=head2 $self->output_as_json()
+
+=cut
+
+sub output_as_json
+{
+    my $self = shift;
+
+    my $persistence = $self->_data_persistence_store();
+
+    $persistence->load;
+
+    my $process_sub_tree;
+
+    $process_sub_tree = sub
+    {
+        my ($sub_tree) = @_;
+
+        my @keys = (grep { $_ ne 'subs' } keys %{$sub_tree});
+
+        my $has_subs = exists($sub_tree->{subs});
+
+        return
+        {
+            (exists($sub_tree->{url})
+                ? (id => $self->_get_id_for_url($sub_tree->{url}), )
+                : ()
+            ),
+            (map { $_ => $sub_tree->{$_} } @keys),
+            $has_subs
+            ?  (subs => [ map { $process_sub_tree->($_) }
+                    grep { ! exists($_->{separator}) }
+                    @{$sub_tree->{subs}}
+                ])
+            : (),
+        };
+    };
+
+    my $ret = encode_json(
+        $process_sub_tree->($self->_tree_contents)->{'subs'}
+    );
+
+    $persistence->save;
+
+    return $ret;
+}
+
 =head1 AUTHOR
 
 Shlomi Fish, C<< <shlomif at cpan.org> >>