6e4c27f7cadcc09b67ac06721d43fcf756eb444a
[libwww-opensearch-perl.git] / lib / WWW / OpenSearch / Url.pm
1 package WWW::OpenSearch::Url;
2
3 use strict;
4 use warnings;
5
6 use base qw( Class::Accessor::Fast );
7
8 use URI::Template;
9
10 __PACKAGE__->mk_accessors( qw( type template method params ns ) );
11
12 =head1 NAME
13
14 WWW::OpenSearch::Url - Object to represent a target URL
15
16 =head1 SYNOPSIS
17
18 =head1 DESCRIPTION
19
20 =head1 CONSTRUCTOR
21
22 =head2 new( [%options] )
23
24 =head1 METHODS
25
26 =head2 prepare_query( [ \%params ] )
27
28 =head1 ACCESSORS
29
30 =over 4
31
32 =item * type
33
34 =item * template
35
36 =item * method
37
38 =item * params
39
40 =item * ns
41
42 =back
43
44 =head1 AUTHOR
45
46 =over 4
47
48 =item * Tatsuhiko Miyagawa E<lt>miyagawa@bulknews.netE<gt>
49
50 =item * Brian Cassidy E<lt>bricas@cpan.orgE<gt>
51
52 =back
53
54 =head1 COPYRIGHT AND LICENSE
55
56 Copyright 2007 by Tatsuhiko Miyagawa and Brian Cassidy
57
58 This library is free software; you can redistribute it and/or modify
59 it under the same terms as Perl itself. 
60
61 =cut
62
63 sub new {
64     my( $class, %options ) = @_;
65     
66     $options{ method } ||= 'GET';
67     $options{ template } = URI::Template->new( $options{ template } );
68     
69     my $self = $class->SUPER::new( \%options );
70
71     return $self;
72 }
73
74 sub prepare_query {
75     my( $self, $params ) = @_;
76     my $tmpl = $self->template;
77     
78     $params->{ startIndex     } ||= 1;
79     $params->{ startPage      } ||= 1;
80     $params->{ language       } ||= '*';
81     $params->{ outputEncoding } ||= 'UTF-8';
82     $params->{ inputEncoding  } ||= 'UTF-8';
83     
84     # fill the uri template
85     my $url = $tmpl->process( %$params );
86
87     # attempt to handle POST
88     if( $self->method eq 'post' ) {
89         my $post = $self->params;
90         for my $key ( keys %$post ) {
91             $post->{ $key } =~ s/{(.+)}/$params->{ $1 } || ''/eg;
92         }
93
94         return $url, [ %$post ];
95     }
96     
97     return $url;
98 }
99
100 1;