Imported Upstream version 0.17
[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 2005-2013 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     for ( qw( startIndex startPage ) ) {
79         $params->{ $_ } = 1 if !defined $params->{ $_ };
80     }
81     $params->{ language }       ||= '*';
82     $params->{ outputEncoding } ||= 'UTF-8';
83     $params->{ inputEncoding }  ||= 'UTF-8';
84
85     # fill the uri template
86     my $url = $tmpl->process( %$params );
87
88     # attempt to handle POST
89     if ( $self->method eq 'post' ) {
90         my $post = $self->params;
91         for my $key ( keys %$post ) {
92             $post->{ $key } =~ s/{(.+)}/$params->{ $1 } || ''/eg;
93         }
94
95         return $url, [ %$post ];
96     }
97
98     return $url;
99 }
100
101 1;