« blib/lib/WWW/Shopify/Liquid/Filter/Split.pm
↑ Summary
blib/lib/WWW/Shopify/Liquid/Filter/StripHtml.pm »
| 1 | #!/usr/bin/perl | ||
| 2 | |||
| 3 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 1 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | |||
| 6 | 1 | ▶ | use WWW::Shopify::Liquid; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 7 | |||
| 8 | package WWW::Shopify::Liquid::Beautifier; | ||
| 9 | use base 'WWW::Shopify::Liquid::Pipeline'; | ||
| 10 | use Scalar::Util qw(blessed); | ||
| 11 | |||
| 12 | sub new { my $package = shift; return bless { tag_enclosing => {}, @_ }, $package; } | ||
| 13 | |||
| 14 | sub register_tag { | ||
| 15 | my ($self, $tag) = @_; | ||
| 16 | $self->{tag_enclosing}->{$tag->name} = $tag->is_free ? 0 : 1; | ||
| 17 | } | ||
| 18 | |||
| 19 | sub beautify { | ||
| 20 | my ($self, @tokens) = @_; | ||
| 21 | # Essentially run through these and insert spaces whenever there's any whitespace. | ||
| 22 | @tokens = grep { blessed($_) && !$_->isa('WWW::Shopify::Liquid::Token::Text::Whitespace') } @tokens; | ||
| 23 | my @result; | ||
| 24 | my $level = 0; | ||
| 25 | my $modification = 0; | ||
| 26 | for my $idx (0..$#tokens) { | ||
| 27 | my $token = $tokens[$idx]; | ||
| 28 | $modification = 0 if $level == 0 && $token->isa('WWW::Shopify::Liquid::Token::Text') && $token->{core} =~ m/\n/s; | ||
| 29 | $level-- if $token->isa('WWW::Shopify::Liquid::Token::Tag') && ($token->{tag} eq "else" || $token->{tag} =~ m/^end/ && $self->{tag_enclosing}->{do { my $a = $token->{tag}; $a =~ s/^end//; $a }}); | ||
| 30 | push(@result, WWW::Shopify::Liquid::Token::Text::Whitespace->new(undef, "\n")) if $idx > 0 && (!$tokens[$idx-1]->isa('WWW::Shopify::Liquid::Token::Text') || ($tokens[$idx-1]->{core} !~ m/\n\s*$/ && $tokens[$idx-1]->{core} !~ m/^\s*$/s)) && (!$tokens[$idx]->isa('WWW::Shopify::Liquid::Token::Text') || $tokens[$idx]->{core} !~ m/^\n/); | ||
| 31 | push(@result, WWW::Shopify::Liquid::Token::Text::Whitespace->new(undef, join("", ("\t" x ($level+$modification))))) if $level+$modification > 0; | ||
| 32 | $modification = length($1) if $level == 0 && $token->isa('WWW::Shopify::Liquid::Token::Tag') && $idx > 0 && $tokens[$idx-1]->isa('WWW::Shopify::Liquid::Token::Text') && $tokens[$idx-1]->{core} =~ m/(\t*)$/; | ||
| 33 | $level++ if $token->isa('WWW::Shopify::Liquid::Token::Tag') && ($token->{tag} eq "else" || $self->{tag_enclosing}->{$token->{tag}}); | ||
| 34 | push(@result, $token); | ||
| 35 | } | ||
| 36 | return @result; | ||
| 37 | } | ||
| 38 | |||
| 39 | sub compress { | ||
| 40 | my ($self, @tokens) = @_; | ||
| 41 | # Essentially run through these and insert spaces whenever there's any whitespace. | ||
| 42 | @tokens = grep { blessed($_) && !$_->isa('WWW::Shopify::Liquid::Token::Text::Whitespace') } @tokens; | ||
| 43 | return @tokens; | ||
| 44 | } | ||
| 45 | |||
| 46 | 1; | ||