Catalyst-View-CSS-Minifier-XS
view release on metacpan or search on metacpan
lib/Catalyst/View/CSS/Minifier/XS.pm view on Meta::CPAN
use MooseX::Aliases;
use Path::Class::Dir;
use URI;
my $dir_type = __PACKAGE__.'::Dir';
subtype $dir_type => as class_type('Path::Class::Dir');
coerce $dir_type,
from 'Str', via { Path::Class::Dir->new($_) },
from 'ArrayRef', via { Path::Class::Dir->new(@$_) };
has stash_variable => (
is => 'ro',
isa => 'Str',
default => 'css',
);
has css_dir => (
is => 'ro',
isa => $dir_type,
coerce => 1,
default => 'css',
alias => 'path',
);
has subinclude => (
is => 'ro',
isa => 'Bool',
default => undef,
);
# for backcompat. don't use this.
has 'INCLUDE_PATH' => (
is => 'ro',
isa => $dir_type,
coerce => 1,
);
sub process {
my ($self,$c) = @_;
my $original_stash = $c->stash->{$self->stash_variable};
my @files = $self->_expand_stash($original_stash);
$c->res->content_type('text/css');
push @files, $self->_subinclude($c, $original_stash, @files);
# the 'root' conf var might not be absolute
my $abs_root = Path::Class::Dir->new( $c->config->{'root'} )->absolute( $c->path_to );
my $dir = $self->css_dir->absolute( $abs_root );
# backcompat only
$dir = $self->INCLUDE_PATH->subdir($dir) if $self->INCLUDE_PATH;
@files = map {
$_ =~ s/\.css$//; $dir->file( "$_.css" )
} grep { defined $_ && $_ ne '' } @files;
my $output = $self->_combine_files($c, \@files);
$c->res->headers->last_modified( max map stat($_)->mtime, @files );
$c->res->body( $self->_minify($c, $output) );
}
sub _subinclude {
my ( $self, $c, $original_stash, @files ) = @_;
return unless $self->subinclude && $c->request->headers->referer;
unless ( $c->request->headers->referer ) {
$c->log->debug('javascripts called from no referer sending blank') if $c->debug;
$c->res->body( q{ } );
$c->detach();
}
my $referer = URI->new($c->request->headers->referer);
if ( $referer->path eq '/' ) {
$c->log->debug(q{we can't take css from index as it's too likely to enter an infinite loop!}) if $c->debug;
return;
}
$c->forward('/'.$referer->path);
$c->log->debug('css taken from referer : '.$referer->path) if $c->debug;
return $self->_expand_stash($c->stash->{$self->stash_variable})
if $c->stash->{$self->stash_variable} ne $original_stash;
}
sub _minify {
my ( $self, $c, $output ) = @_;
if ( @{$output} ) {
return $c->debug
? join "\n", @{$output}
: minify(join q{ }, @{$output} )
} else {
return q{ };
}
}
sub _combine_files {
my ( $self, $c, $files ) = @_;
my @output;
for my $file (@{$files}) {
$c->log->debug("loading css file ... $file") if $c->debug;
open my $in, '<', $file;
local $/;
push @output, scalar <$in>;
}
return \@output;
}
sub _expand_stash {
my ( $self, $stash_var ) = @_;
if ( $stash_var ) {
return ref $stash_var eq 'ARRAY'
? @{ $stash_var }
: split /\s+/, $stash_var;
( run in 1.137 second using v1.01-cache-2.11-cpan-39bf76dae61 )