line |
stmt |
bran |
cond |
sub |
pod |
time |
code |
1
|
|
|
|
|
|
|
package Mojolicious::Plugin::CSSCompressor; |
2
|
|
|
|
|
|
|
|
3
|
2
|
|
|
2
|
|
28943
|
use strict; |
|
2
|
|
|
|
|
5
|
|
|
2
|
|
|
|
|
133
|
|
4
|
2
|
|
|
2
|
|
13
|
use warnings; |
|
2
|
|
|
|
|
5
|
|
|
2
|
|
|
|
|
98
|
|
5
|
|
|
|
|
|
|
|
6
|
2
|
|
|
2
|
|
957
|
use Mojo::Base qw( Mojolicious::Plugin ); |
|
2
|
|
|
|
|
13720
|
|
|
2
|
|
|
|
|
20
|
|
7
|
|
|
|
|
|
|
|
8
|
2
|
|
|
2
|
|
4402
|
use CSS::Compressor qw( css_compress ); |
|
2
|
|
|
|
|
6711
|
|
|
2
|
|
|
|
|
1205
|
|
9
|
|
|
|
|
|
|
|
10
|
|
|
|
|
|
|
our $VERSION = '0.01'; |
11
|
|
|
|
|
|
|
|
12
|
|
|
|
|
|
|
sub HEADER() |
13
|
|
|
|
|
|
|
{ |
14
|
|
|
|
|
|
|
'X-CSS-Compressor-Path' |
15
|
|
|
|
|
|
|
} |
16
|
|
|
|
|
|
|
|
17
|
|
|
|
|
|
|
sub register |
18
|
|
|
|
|
|
|
{ |
19
|
1
|
|
|
1
|
1
|
157
|
my ( $self, $app, $conf ) = @_; |
20
|
1
|
|
50
|
|
|
11
|
my $suffix = $conf->{suffix} // '-min'; |
21
|
1
|
50
|
|
|
|
7
|
my $re = ref( $suffix ) |
22
|
|
|
|
|
|
|
? $suffix |
23
|
|
|
|
|
|
|
: quotemeta( $suffix ) |
24
|
|
|
|
|
|
|
; |
25
|
|
|
|
|
|
|
|
26
|
|
|
|
|
|
|
$app->hook( before_dispatch => sub { |
27
|
2
|
|
|
2
|
|
143452
|
my $self = shift; |
28
|
2
|
|
|
|
|
12
|
my $req = $self->req(); |
29
|
2
|
|
|
|
|
151
|
my $urlpath = $req->url->path(); |
30
|
|
|
|
|
|
|
|
31
|
|
|
|
|
|
|
# skip it without a matching suffix |
32
|
|
|
|
|
|
|
return unless |
33
|
2
|
100
|
|
|
|
109
|
my ( $path ) = $urlpath =~ m!\A (.*) $re \. css \z!x; |
34
|
|
|
|
|
|
|
|
35
|
|
|
|
|
|
|
# adjust request path for static dispatch |
36
|
1
|
|
|
|
|
106
|
$req->url->path( $path . '.css' ); |
37
|
|
|
|
|
|
|
|
38
|
|
|
|
|
|
|
# keep the original path around to restore later |
39
|
1
|
|
|
|
|
56
|
$req->headers->remove( HEADER )->add( HEADER, $urlpath ); |
40
|
1
|
|
|
|
|
16
|
} ); |
41
|
|
|
|
|
|
|
|
42
|
|
|
|
|
|
|
$app->hook( after_dispatch => sub { |
43
|
2
|
|
|
2
|
|
16510
|
my $self = shift; |
44
|
2
|
|
|
|
|
11
|
my $req = $self->req(); |
45
|
2
|
|
|
|
|
112
|
my $res = $self->res(); |
46
|
|
|
|
|
|
|
|
47
|
|
|
|
|
|
|
# the original path indicates when to do something |
48
|
|
|
|
|
|
|
return unless |
49
|
2
|
100
|
|
|
|
6426
|
my $urlpath = $req->headers->header( HEADER ); |
50
|
|
|
|
|
|
|
|
51
|
|
|
|
|
|
|
# restore original path |
52
|
1
|
|
|
|
|
188
|
$req->url->path( $urlpath ); |
53
|
|
|
|
|
|
|
|
54
|
|
|
|
|
|
|
# only compress when the content type looks ok |
55
|
|
|
|
|
|
|
return unless |
56
|
1
|
50
|
50
|
|
|
52
|
( $res->headers->content_type() // '' ) =~ m!\A text / css \b!x; |
57
|
|
|
|
|
|
|
|
58
|
|
|
|
|
|
|
# get static output |
59
|
1
|
|
|
|
|
90
|
my $body = $res->body(); |
60
|
|
|
|
|
|
|
|
61
|
|
|
|
|
|
|
# and deliver compressed version instead |
62
|
1
|
|
|
|
|
76
|
$res->body( css_compress( $body ) ); |
63
|
1
|
|
|
|
|
68
|
} ); |
64
|
|
|
|
|
|
|
} |
65
|
|
|
|
|
|
|
|
66
|
|
|
|
|
|
|
1; |
67
|
|
|
|
|
|
|
|
68
|
|
|
|
|
|
|
__END__ |