summaryrefslogtreecommitdiff
path: root/lib/WebService/TFL/Bus/Response.pm
blob: 4251228b7df799cc210287a6ce7527d7d043767f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package WebService::TFL::Bus::Response; 
use Moo;
use Class::Load 'load_class';
use Type::Utils -all;
use Types::Standard -all;
use JSON;
use namespace::autoclean;
 
sub line_class {
    "WebService::TFL::Bus::Response::$_[0]";
}
 
my %line_map = (
    => 'Stop',
    => 'Prediction',
    => 'FlexibleMessage',
    => 'BaseVersion',
    => 'URAVersion',
);
 
for my $field (values %line_map) {
    my $class = line_class($field);
    load_class($class);
    has $field => (
        is => 'ro',
        isa => ArrayRef[class_type { class => $class }],
    );
}
 
sub new_from_json {
    my ($class,$return_list,$json) = @_;
 
    my $parser = JSON->new->utf8;
 
    my %return_set;@return_set{@$return_list}=();
    unless (%return_set) {
        @return_set{qw(StopPointName LineName EstimatedTime)}=();
    }
    my %args;
 
    while ($json) {
        my ($array,$consumed) = $parser->decode_prefix($json);
 
        my $array_type = $line_map{$array->[0]};
        my $line_class = line_class($array_type);
        push @{$args{$array_type}},
            $line_class->new_from_array(\%return_set,$array);
 
        substr($json,0,$consumed)='';
    }
 
    return $class->new(\%args);
}
 
1;