| 1 | package Switchvox::API::Response; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use HTTP::Response; | ||
| 6 | use XML::Simple qw(:strict); | ||
| 7 | use XML::Parser; | ||
| 8 | |||
| 9 | use base 'HTTP::Response'; | ||
| 10 | |||
| 11 | our $VERSION = '1.02'; | ||
| 12 | |||
| 13 | #- Force a non sax parser for error validation | ||
| 14 | $XML::Simple::PREFERRED_PARSER = 'XML::Parser'; | ||
| 15 | |||
| 16 | sub new | ||
| 17 | { | ||
| 18 | my ($class,%in) = @_; | ||
| 19 | warn "Missing response in call to constructor" unless defined $in{response}; | ||
| 20 | my $self = $in{response}; | ||
| 21 | bless $self,$class; | ||
| 22 | |||
| 23 | $self->{api_errors} = []; | ||
| 24 | $self->{api_result} = undef; | ||
| 25 | $self->{api_status} = 'unprocessed'; | ||
| 26 | return $self; | ||
| 27 | } | ||
| 28 | |||
| 29 | sub process | ||
| 30 | { | ||
| 31 | my $self = shift; | ||
| 32 | |||
| 33 | #- Ok check all the status | ||
| 34 | if(!$self->is_success()) | ||
| 35 | { | ||
| 36 | return $self->_failed( errors => [{ code => -1, message => 'HTTP Request failed (' . $self->message . ')' }]); | ||
| 37 | } | ||
| 38 | |||
| 39 | #- Parse the XML and check for problems | ||
| 40 | my $xmlin = eval | ||
| 41 | { | ||
| 42 | XML::Simple::XMLin($self->content, KeyAttr => {}, ForceArray => 1, KeepRoot => 1 ); | ||
| 43 | }; | ||
| 44 | |||
| 45 | #- XML Parse issues | ||
| 46 | if($@) | ||
| 47 | { | ||
| 48 | return $self->_failed( errors => [{ code => -1, message => "Returned XML did not parse correctly ($@)" }]); | ||
| 49 | } | ||
| 50 | |||
| 51 | #- Check on result | ||
| 52 | if(exists $xmlin->{response}[0]{result}) | ||
| 53 | { | ||
| 54 | $self->{api_result} = $xmlin; | ||
| 55 | $self->{api_status} = 'success'; | ||
| 56 | return; | ||
| 57 | } | ||
| 58 | elsif(exists $xmlin->{response}[0]{errors}) | ||
| 59 | { | ||
| 60 | my $errors = []; | ||
| 61 | foreach my $error ( @{$xmlin->{response}[0]{errors}[0]{error}} ) | ||
| 62 | { | ||
| 63 | push(@$errors,{ code => $error->{code}, message => $error->{message} }); | ||
| 64 | } | ||
| 65 | return $self->_fault( errors => $errors ); | ||
| 66 | } | ||
| 67 | else | ||
| 68 | { | ||
| 69 | return $self->_failed( errors => [ {code => -1, message => 'Valid XML was not returned by the API'}] ); | ||
| 70 | } | ||
| 71 | return; | ||
| 72 | } | ||
| 73 | |||
| 74 | sub _failed | ||
| 75 | { | ||
| 76 | my ($self,%in) = @_; | ||
| 77 | $self->{api_status} = 'failed'; | ||
| 78 | $self->{api_errors} = $in{errors} || []; | ||
| 79 | } | ||
| 80 | |||
| 81 | sub _fault | ||
| 82 | { | ||
| 83 | my ($self,%in) = @_; | ||
| 84 | $self->{api_status} = 'fault'; | ||
| 85 | $self->{api_errors} = $in{errors} || []; | ||
| 86 | } | ||
| 87 | |||
| 88 | 1; #- Switchvox Rules! | ||
| 89 | |||
| 90 | __END__ |