comparison Lib/IMPL/Web/Handler/LocaleHandler.pm @ 361:eff7f75a4408

added cookie support for the request language detection
author cin
date Wed, 27 Nov 2013 17:12:38 +0400
parents 39842eedd923
children 212cc86e470b
comparison
equal deleted inserted replaced
360:39842eedd923 361:eff7f75a4408
11 'IMPL::Object::Autofill' => '@_', 11 'IMPL::Object::Autofill' => '@_',
12 'IMPL::Object::Serializable' => undef 12 'IMPL::Object::Serializable' => undef
13 ], 13 ],
14 props => [ 14 props => [
15 locales => PROP_RO | PROP_LIST, 15 locales => PROP_RO | PROP_LIST,
16 default => PROP_RO 16 default => PROP_RO,
17 cookie => PROP_RO
17 ] 18 ]
18 }; 19 };
19 20
20 sub Invoke { 21 sub Invoke {
21 my ($this,$action,$nextHandler) = @_; 22 my ($this,$action,$nextHandler) = @_;
22 23
23 my @matches; 24 my $locale;
24 25
25 my $best = [$this->default,0]; 26 if ($this->cookie and my $cookie = $action->cookie($this->cookie)) {
26 27 ($locale) = grep /^$cookie/i, $this->locales;
27 if(my $header = $action->header('Accept-Language')) {
28 foreach my $part (split(/\s*,\s*/, $header)) {
29 my ($lang,$quality) = ($part =~ /([a-z]+(?:\-[a-z]+)*)(?:\s*;\s*q=(0\.[\d]+|1))?/i );
30
31 $quality ||=1;
32
33 foreach my $tag ($this->locales) {
34 if ( $tag =~ m/^$lang/i ) {
35 push @matches, [$tag,$quality];
36 }
37 }
38 }
39
40 foreach my $match (@matches) {
41 if ($match->[1] > $best->[1]) {
42 $best = $match;
43 }
44 }
45
46
47 } 28 }
48 29
49 if (my $locale = $best->[0]) { 30 unless($locale) {
50 Resources->SetLocale($locale); 31 my @matches;
32
33 my $best = [$this->default,0];
34
35 if(my $header = $action->header('Accept-Language')) {
36 foreach my $part (split(/\s*,\s*/, $header)) {
37 my ($lang,$quality) = ($part =~ /([a-z]+(?:\-[a-z]+)*)(?:\s*;\s*q=(0\.[\d]+|1))?/i );
38
39 $quality ||=1;
40
41 foreach my $tag ($this->locales) {
42 if ( $tag =~ m/^$lang/i ) {
43 push @matches, [$tag,$quality];
44 }
45 }
46 }
47
48 foreach my $match (@matches) {
49 if ($match->[1] > $best->[1]) {
50 $best = $match;
51 }
52 }
53
54 }
55
56 $locale = $best->[0];
51 } 57 }
58
59 Resources->SetLocale($locale) if $locale;
52 60
53 return $nextHandler->($action); 61 return $nextHandler->($action);
54 } 62 }
55 63
56 1; 64 1;
66 =head1 SYNOPSIS 74 =head1 SYNOPSIS
67 75
68 =begin code xml 76 =begin code xml
69 77
70 <handlers type="ARRAY"> 78 <handlers type="ARRAY">
71 <item type="IMPL::Web::Handler::LocationHandler"/> 79 <item type="IMPL::Web::Handler::LocaleHandler">
80 <locales type="ARRAY">
81 <item>en-US</item>
82 <item>ru-RU</item>
83 </locales>
84 <default>en-US</default>
85 <cookie>lang</cookie>
86 </item>
72 </handlers> 87 </handlers>
73 88
74 =end code xml 89 =end code xml
75 90
76 =cut 91 =cut