Plack-Middleware-Text-Minify

 view release on metacpan or  search on metacpan

lib/Plack/Middleware/Text/Minify.pm  view on Meta::CPAN

package Plack::Middleware::Text::Minify;

# ABSTRACT: remove HTML indentation on the fly

use v5.14;
use warnings;

use parent qw/ Plack::Middleware /;

use Plack::Util;
use Plack::Util::Accessor qw/ path type /;
use Ref::Util qw/ is_arrayref is_coderef /;
use Text::Minify::XS v0.7.0 ();

# RECOMMEND PREREQ:  Ref::Util::XS

our $VERSION = 'v0.4.1';

sub call {
    my ($self, $env) = @_;

    my $res = $self->app->($env);

    return $res if $env->{'psgix.no-minify'};

    my $method = $env->{REQUEST_METHOD};
    unless ($method =~ /^(GET|POST)$/) {
        return $res;
    }

    if (my $match = $self->path) {

        my $path = $env->{PATH_INFO};

        unless ( ( is_coderef($match) && $match->( $path, $env ) )
            || ( $path =~ $match ) )
        {
            return $res;
        }
    }

    return Plack::Util::response_cb(
        $res,
        sub {
            my ($res) = @_;

            return unless is_arrayref($res);

            return if @$res < 3;

            return if Plack::Util::status_with_no_entity_body( $res->[0] );

            my $type = Plack::Util::header_get( $res->[1], 'content-type' );
            if ( my $match = $self->type ) {
                return
                  unless ( ( is_coderef($match) && $match->( $type, $res ) )
                    || ( $type =~ $match ) );
            }
            else {
                return unless $type =~ m{^text/};
            }

            my $body = $res->[2];
            if ( is_arrayref($body) ) {    # no reason to call a function for each line in the body
                $res->[2] = [ Text::Minify::XS::minify( join( "", @$body ) ) ];
            }
            else {
                my $text = "";
                Plack::Util::foreach( $body, sub { $text .= $_[0] } );
                $res->[2] = [ Text::Minify::XS::minify($text) ];
            }

            if (Plack::Util::header_exists( $res->[1], 'content-length' )) {
                Plack::Util::header_set( $res->[1], 'content-length', length( $res->[2][0] ) );
            }



( run in 3.664 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )