import of 0.08
[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;
9 use URI::Escape;
10
11 __PACKAGE__->mk_accessors( qw( type template method params macros ) );
12
13 =head1 NAME
14
15 WWW::OpenSearch::Url - Object to represent a target URL
16
17 =head1 SYNOPSIS
18
19 =head1 DESCRIPTION
20
21 =head1 CONSTRUCTOR
22
23 =head2 new( [%options] )
24
25 =head1 METHODS
26
27 =head2 parse_macros( )
28
29 =head2 prepare_query( [ \%params ] )
30
31 =head1 ACCESSORS
32
33 =over 4
34
35 =item * type
36
37 =item * template
38
39 =item * method
40
41 =item * params
42
43 =item * macros
44
45 =back
46
47 =head1 AUTHOR
48
49 =over 4
50
51 =item * Tatsuhiko Miyagawa E<lt>miyagawa@bulknews.netE<gt>
52
53 =item * Brian Cassidy E<lt>bricas@cpan.orgE<gt>
54
55 =back
56
57 =head1 COPYRIGHT AND LICENSE
58
59 Copyright 2006 by Tatsuhiko Miyagawa and Brian Cassidy
60
61 This library is free software; you can redistribute it and/or modify
62 it under the same terms as Perl itself. 
63
64 =cut
65
66 sub new {
67     my( $class, %options ) = @_;
68     
69     $options{ method } ||= 'GET';
70     $options{ template } = URI->new( $options{ template } );
71     
72     my $self = $class->SUPER::new( \%options );
73     $self->parse_macros;
74
75     return $self;
76 }
77
78 sub parse_macros {
79     my $self = shift;
80     
81     my %query = $self->method eq 'post'
82         ? %{ $self->params }
83         : $self->template->query_form;
84     
85     my %macros;
86     for( keys %query ) {
87         if( $query{ $_ } =~ /^{(.+)}$/ ) {
88             $macros{ $1 } = $_;
89         }
90     }
91     
92     $self->macros( \%macros );
93 }
94
95 sub prepare_query {
96     my( $self, $params ) = @_;
97     my $url   = $self->template->clone;
98     
99     $params->{ startIndex     } ||= 1;
100     $params->{ startPage      } ||= 1;
101     $params->{ language       } ||= '*';
102     $params->{ outputEncoding } ||= 'UTF-8';
103     $params->{ inputEncoding  } ||= 'UTF-8';
104     
105     my $macros = $self->macros;
106
107     # attempt to handle POST
108     if( $self->method eq 'post' ) {
109         my $post = $self->params;
110         for( keys %$macros ) {
111             $post->{ $macros->{ $_ } } = $params->{ $_ };
112         }
113         return [ $url, $post ];
114     }
115
116     my $query = { $url->query_form };
117     for( keys %$macros ) {
118         $query->{ $macros->{ $_ } } = $params->{ $_ };
119     }
120     
121     $url->query_form( $query );
122     return $url;
123 }
124
125 1;