| 1 | package Hopkins::TaskOptionChoices; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | |||
| 5 | =head1 NAME | ||
| 6 | |||
| 7 | Hopkins::TaskOptionChoices - task option choices object | ||
| 8 | |||
| 9 | =head1 DESCRIPTION | ||
| 10 | |||
| 11 | Hopkins::TaskOptionChoices represents the possible choices | ||
| 12 | for a task option. | ||
| 13 | |||
| 14 | =cut | ||
| 15 | |||
| 16 | use base 'Class::Accessor::Fast'; | ||
| 17 | |||
| 18 | use LWP::UserAgent; | ||
| 19 | use JSON; | ||
| 20 | |||
| 21 | __PACKAGE__->mk_accessors(qw(type src root name value choice)); | ||
| 22 | |||
| 23 | my $mimemap = { json => 'application/json', xml => 'text/xml' }; | ||
| 24 | |||
| 25 | sub new | ||
| 26 | { | ||
| 27 | my $self = shift->SUPER::new(@_); | ||
| 28 | |||
| 29 | $self->name('name') if not defined $self->name; | ||
| 30 | $self->value('value') if not defined $self->value; | ||
| 31 | |||
| 32 | return $self; | ||
| 33 | } | ||
| 34 | |||
| 35 | sub all { return @{ shift->choice || [] } } | ||
| 36 | |||
| 37 | sub fetch | ||
| 38 | { | ||
| 39 | my $self = shift; | ||
| 40 | |||
| 41 | if ($self->src) { | ||
| 42 | my $parser = 'parse_' . $self->type; | ||
| 43 | my $type = $mimemap->{$self->type}; | ||
| 44 | my $ua = new LWP::UserAgent; | ||
| 45 | my $res = $ua->get($self->src, 'Content-Type' => $type); | ||
| 46 | |||
| 47 | $self->choice($self->$parser($res->content)); | ||
| 48 | } | ||
| 49 | } | ||
| 50 | |||
| 51 | sub parse_json | ||
| 52 | { | ||
| 53 | my $self = shift; | ||
| 54 | my $content = shift; | ||
| 55 | |||
| 56 | my $json = new JSON; | ||
| 57 | my $ref = $json->decode($content); | ||
| 58 | my @choices = (); | ||
| 59 | |||
| 60 | $ref = $ref->{$self->root} if $self->root and ref $ref eq 'HASH'; | ||
| 61 | |||
| 62 | return [] if ref $ref ne 'ARRAY'; | ||
| 63 | |||
| 64 | foreach my $href (@$ref) { | ||
| 65 | next if not ref $href eq 'HASH'; | ||
| 66 | |||
| 67 | push @choices, { name => $href->{$self->name}, value => $href->{$self->value} }; | ||
| 68 | } | ||
| 69 | |||
| 70 | |||
| 71 | |||
| 72 | #use Data::Dumper; | ||
| 73 | #$Data::Dumper::Indent=1; | ||
| 74 | # print STDERR Dumper($href); | ||
| 75 | |||
| 76 | return [ sort { $a->{name} cmp $b->{name} } @choices ]; | ||
| 77 | |||
| 78 | |||
| 79 | #print STDERR "CONTENT=$content\n"; | ||
| 80 | } | ||
| 81 | |||
| 82 | =back | ||
| 83 | |||
| 84 | =head1 AUTHOR | ||
| 85 | |||
| 86 | Mike Eldridge <diz@cpan.org> | ||
| 87 | |||
| 88 | =head1 LICENSE | ||
| 89 | |||
| 90 | =cut | ||
| 91 | |||
| 92 | 1; | ||
| 93 |