comparison lib/IMPL/Web/Handler/LocaleHandler.pm @ 407:c6e90e02dd17 ref20150831

renamed Lib->lib
author cin
date Fri, 04 Sep 2015 19:40:23 +0300
parents
children
comparison
equal deleted inserted replaced
406:f23fcb19d3c1 407:c6e90e02dd17
1 package IMPL::Web::Handler::LocaleHandler;
2 use strict;
3
4 use IMPL::Const qw(:prop);
5 use DateTime;
6 use IMPL::declare {
7 require => {
8 Resources => 'IMPL::Resources'
9 },
10 base => [
11 'IMPL::Object' => undef,
12 'IMPL::Object::Autofill' => '@_',
13 'IMPL::Object::Serializable' => undef
14 ],
15 props => [
16 locales => PROP_RO | PROP_LIST,
17 default => PROP_RO,
18 cookie => PROP_RO
19 ]
20 };
21
22 sub Invoke {
23 my ($this,$action,$nextHandler) = @_;
24
25 my $locale;
26
27 if ($this->cookie and my $cookie = $action->cookie($this->cookie)) {
28 ($locale) = grep /^$cookie/i, $this->locales;
29 }
30
31 unless($locale) {
32 my @matches;
33
34 my $best = [$this->default,0];
35
36 if(my $header = $action->header('Accept-Language')) {
37 foreach my $part (split(/\s*,\s*/, $header)) {
38 my ($lang,$quality) = ($part =~ /([a-z]+(?:\-[a-z]+)*)(?:\s*;\s*q=(0\.[\d]+|1))?/i );
39
40 $quality ||=1;
41
42 foreach my $tag ($this->locales) {
43 if ( $tag =~ m/^$lang/i ) {
44 push @matches, [$tag,$quality];
45 }
46 }
47 }
48
49 foreach my $match (@matches) {
50 if ($match->[1] > $best->[1]) {
51 $best = $match;
52 }
53 }
54
55 }
56
57 $locale = $best->[0];
58 }
59
60 if($locale) {
61 Resources->SetLocale($locale);
62 #$locale =~ tr/-/_/;
63 DateTime->DefaultLocale($locale);
64 }
65
66 return $nextHandler->($action);
67 }
68
69 1;
70
71 __END__
72
73 =pod
74
75 =head1 NAME
76
77 C<IMPL::Web::Handler::LocaleHandler> - handles locale for the request
78
79 =head1 SYNOPSIS
80
81 =begin code xml
82
83 <handlers type="ARRAY">
84 <item type="IMPL::Web::Handler::LocaleHandler">
85 <locales type="ARRAY">
86 <item>en-US</item>
87 <item>ru-RU</item>
88 </locales>
89 <default>en-US</default>
90 <cookie>lang</cookie>
91 </item>
92 </handlers>
93
94 =end code xml
95
96 =cut