| 1 | package APISchema::Schema; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use 5.014; | ||
| 5 | |||
| 6 | use APISchema::Route; | ||
| 7 | use APISchema::Resource; | ||
| 8 | |||
| 9 | use Class::Accessor::Lite ( | ||
| 10 | rw => [qw(title description)], | ||
| 11 | ); | ||
| 12 | |||
| 13 | sub new { | ||
| 14 | my ($class) = @_; | ||
| 15 | |||
| 16 | bless { | ||
| 17 | resources => {}, | ||
| 18 | routes => [], | ||
| 19 | }, $class; | ||
| 20 | } | ||
| 21 | |||
| 22 | sub register_resource { | ||
| 23 | my ($self, $title, $definition) = @_; | ||
| 24 | |||
| 25 | my $resource = APISchema::Resource->new( | ||
| 26 | title => $title, | ||
| 27 | definition => $definition, | ||
| 28 | ); | ||
| 29 | $self->{resources}->{$title} = $resource; | ||
| 30 | |||
| 31 | return $resource; | ||
| 32 | } | ||
| 33 | |||
| 34 | sub get_resources { | ||
| 35 | my ($self) = @_; | ||
| 36 | |||
| 37 | [ sort { $a->title cmp $b->title } values %{$self->{resources}} ]; | ||
| 38 | } | ||
| 39 | |||
| 40 | sub get_resource_by_name { | ||
| 41 | my ($self, $name) = @_; | ||
| 42 | |||
| 43 | $self->{resources}->{$name || ''}; | ||
| 44 | } | ||
| 45 | |||
| 46 | sub get_resource_root { | ||
| 47 | my ($self) = @_; | ||
| 48 | return +{ | ||
| 49 | resource => +{ map { | ||
| 50 | $_ => $self->{resources}->{$_}->definition; | ||
| 51 | } keys %{$self->{resources}} }, | ||
| 52 | properties => {}, | ||
| 53 | }; | ||
| 54 | } | ||
| 55 | |||
| 56 | sub _next_title_candidate { | ||
| 57 | my ($self, $base_title) = @_; | ||
| 58 | if ($base_title =~ /\(([0-9]+)\)$/) { | ||
| 59 | my $index = $1 + 1; | ||
| 60 | return $base_title =~ s/\([0-9]+\)$/($index)/r; | ||
| 61 | } else { | ||
| 62 | return $base_title . '(1)'; | ||
| 63 | } | ||
| 64 | } | ||
| 65 | |||
| 66 | sub register_route { | ||
| 67 | my ($self, %values) = @_; | ||
| 68 | |||
| 69 | # make fresh title | ||
| 70 | my $title = $values{title} // $values{route} // 'empty_route'; | ||
| 71 | while ($self->get_route_by_name($title)) { | ||
| 72 | $title = $self->_next_title_candidate($title); | ||
| 73 | } | ||
| 74 | |||
| 75 | my $route = APISchema::Route->new( | ||
| 76 | %values, | ||
| 77 | title => $title, | ||
| 78 | ); | ||
| 79 | push @{$self->{routes}}, $route; | ||
| 80 | return $route; | ||
| 81 | } | ||
| 82 | |||
| 83 | sub get_routes { | ||
| 84 | my ($self) = @_; | ||
| 85 | |||
| 86 | $self->{routes}; | ||
| 87 | } | ||
| 88 | |||
| 89 | sub get_route_by_name { | ||
| 90 | my ($self, $name) = @_; | ||
| 91 | my ($route) = grep { ($_->title||'') eq $name } @{$self->get_routes}; | ||
| 92 | return $route; | ||
| 93 | } | ||
| 94 | |||
| 95 | 1; |