lib/WWW/Shopify/Liquid.pm

filter: Statementstmt 88.8% 16 / 18 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.6% 22 / 24 CC 1 SCAR 0.5
CC
1
Cov
89%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« lib/WWW/Shopify/Liquid/Filter/Round.pm ↑ Summary lib/WWW/Shopify/Liquid/Dialect/Web.pm »
1 #!/usr/bin/perl
2  
3 38 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 38 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6  
7 package WWW::Shopify::Liquid;
8 38 ▶use File::Slurp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 38 ▶use List::MoreUtils qw(firstidx part);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 38 ▶use Module::Find;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 our $VERSION = '0.08';
13  
14 =head1 NAME
15  
16 WWW::Shopify::Liquid - Fully featured liquid preprocessor with shopify tags & filters added in.
17  
18 =cut
19  
20 =head1 DESCRIPTION
21  
22 A concise and clear liquid processor. Runs a superset of what Shopify can do. For a strict shopify implementation
23 see L<Template::Liquid> for one that emulates all the quirks and ridiculousness of the real thing, but without the tags.
24 (Meaning no actual arithemtic is literal tags without filters, insanity on acutal number processing and conversion,
25 insane array handling, no real optimization, or partial AST reduction, etc.., etc..).
26  
27 Combines a lexer, parser, optimizer and a renderer. Can be invoked in any number of ways. Simplest is to use the sub this module exports,
28 liquid_render_file.
29  
30 use WWW::Shopify::Liquid qw/liquid_render_file/;
31
32 $contents = liquid_render_file({ collection => { handle => "test" } }, "myfile.liquid");
33 print $contents;
34
35 This is the simplest method. There are auxiliary methods which provide a lot of flexibility over how you render your
36 liquid (see below), and an OO interface.
37  
38 This method represents the whole pipeline, so to get an overview of this module, we'll describe it here.
39 Fundamentally, what liquid_render_file does, is it slurps the whole file into a string, and then passes that string to
40 the lexer. This then generates a stream of tokens. These tokens are then transformed into an abstract syntax tree, by the
41 the parser if the syntax is valid. This AST represents the canonical form of the file, and can, from here, either
42 transformed back into almost the same file, statically optimized to remove any unecessary calls, or partially optimized to
43 remove branches of the tree for which you have variables to fill at this time, though both these steps are optional.
44  
45 Finally, these tokens are passed to the renderer, which interprets the tokens and then produces a string representing the
46 final content that can be printed.
47  
48 Has better error handling than Shopify's liquid processor, so if you use this to validate your liquid, you should get better
49 errors than if you're simply submitting them. This module is integrated into the L<Padre::Plugin::Shopify> module, so if you
50 use Padre as your Shopify IDE, you can automatically check the liquid of the file you're currently looking at with the click
51 of a button.
52  
53 You can invoke each stage individually if you like.
54  
55 use WWW::Shopify::Liquid;
56 my $text = ...
57 my $liquid = WWW::Shopify::Liquid->new;
58 my @tokens = $liquid->lexer->parse_text($text);
59 my $ast = $liquid->parser->parse_tokens(@tokens);
60
61 # Here we have a partial tree optimization. Meaning, if you have some of your
62 # variables, but not all of them, you can simplify the template.
63 $ast = $liquid->optimizer->optimize({ a => 2 }, $ast);
64
65 # Finally, you can render.
66 $result = $liquid->renderer->render({ b => 3 }, $ast);
67
68 If you're simply looking to check whether a liquid file is valid, you can do the following:
69  
70 use WWW::Shopify::Liquid qw/liquid_verify_file/;
71 liquid_verify_file("my-snippet.liquid");
72
73 If sucessful, it'll return nothing, if it fails, it'll throw an exception, detailing the fault's location and description.
74  
75 =cut
76  
77 =head1 STATUS
78  
79 This module is currently in beta. That means that while it is able to parse and validate liquid documents from Shopify, it may
80 be missing a few tags. In addition to this, the optimizer is not yet fully complete; it does not do advanced optimizations such as loop
81 unrolling. However, it does do partial tree rendering. Essentially what's missing is the ability to generate liquid from syntax trees.
82  
83 This is close to complete, but not quite there yet. When done, this will be extremely beneficial to application proxies, as it will allow
84 the use of custom liquid syntax, with partial evaluation, before passing the remaining liquid back to Shopify for full evaluation. This
85 will allow you to do things like have custom tags that a user can customize which will be filled with your data, yet still allow Shopify to
86 evaluate stuff like asset_urls, includes, and whatnot.
87  
88 =cut
89  
90 0 ▶use WWW::Shopify::Liquid::Parser;
Subroutine BEGIN: called CC=1 SCAR=2.6
91 use WWW::Shopify::Liquid::Optimizer;
92 use WWW::Shopify::Liquid::Lexer;
93 use WWW::Shopify::Liquid::Renderer;
94 use WWW::Shopify::Liquid::Debugger;
95 use WWW::Shopify::Liquid::Operator;
96 use WWW::Shopify::Liquid::Tag;
97 use Scalar::Util qw(blessed);
98  
99 sub new {
100 my $package = shift;
101 my %hash = ();
102 if ($_[0] && ref($_[0]) eq 'HASH') {
103 %hash = %{$_[0]};
104 } else {
105 %hash = @_;
106 }
107 my $self = bless {
108 filters => [],
109 operators => [],
110 tags => [],
111
112 lexer => WWW::Shopify::Liquid::Lexer->new,
113 parser => WWW::Shopify::Liquid::Parser->new,
114 optimizer => WWW::Shopify::Liquid::Optimizer->new,
115 renderer => WWW::Shopify::Liquid::Renderer->new,
116 debugger => WWW::Shopify::Liquid::Debugger->new,
117
118 dialects => [],
119
120 %hash
121 }, $package;
122
123 $self->lexer->parent($self) if $self->lexer;
124 $self->parser->parent($self) if $self->parser;
125 $self->optimizer->parent($self) if $self->optimizer;
126 $self->renderer->parent($self) if $self->renderer;
127
128 $self->load_modules;
129
130 return $self;
131 }
132  
133 sub load_modules {
134 my ($self) = @_;
135 $self->register_operator($_) for (findallmod WWW::Shopify::Liquid::Operator);
136 $self->register_filter($_) for (findallmod WWW::Shopify::Liquid::Filter);
137 $self->register_tag($_) for (findallmod WWW::Shopify::Liquid::Tag);
138 $_->apply($self) for (@{$self->{dialects}});
139 }
140  
141 sub lexer { return $_[0]->{lexer}; }
142 sub parser { return $_[0]->{parser}; }
143 sub optimizer { return $_[0]->{optimizer}; }
144 sub renderer { return $_[0]->{renderer}; }
145 sub debugger { return $_[0]->{debugger}; }
146  
147 sub register_tag {
148 if (!$_[1]->abstract) {
149 push(@{$_[0]->tags}, $_[1]);
150 $_->register_tag($_[1]) for (grep { blessed($_) && $_->can('register_tag') } values(%{$_[0]}));
151 }
152 }
153 sub register_filter {
154 push(@{$_[0]->filters}, $_[1]);
155 $_->register_filter($_[1]) for (grep { blessed($_) && $_->can('register_filter') } values(%{$_[0]}));
156 }
157 sub register_operator {
158 WWW::Shopify::Liquid::Pipeline->register_operator($_[1]);
159 push(@{$_[0]->operators}, $_[1]);
160 $_->register_operator($_[1]) for (grep { blessed($_) && $_->can('register_operator') } values(%{$_[0]}));
161 }
162 sub tags { return $_[0]->{tags}; }
163 sub filters { return $_[0]->{filters}; }
164 sub operators { return $_[0]->{operators}; }
165 sub order_of_operations { return $_[0]->{order_of_operations}; }
166 sub free_tags { return $_[0]->{free_tags}; }
167 sub enclosing_tags { return $_[0]->{enclosing_tags}; }
168 sub processing_variables { return $_[0]->{processing_variables}; }
169 sub money_format { return $_[0]->{money_format}; }
170 sub money_with_currency_format { return $_[0]->{money_with_currency_format}; }
171 sub tag_list { return (keys(%{$_[0]->free_tags}), keys(%{$_[0]->enclosing_tags})); }
172 sub file_context {
173 my ($self, $file) = @_;
174 $self->lexer->file_context($file);
175 $self->parser->file_context($file);
176 $self->renderer->file_context($file) if $self->renderer;
177 }
178  
179 sub operate { return $_[0]->operators->{$_[3]}->($_[0], $_[1], $_[2], $_[4]); }
180  
181 sub render_ast { my ($self, $hash, $ast) = @_; return $self->renderer->render($hash, $ast); }
182 sub render_resume { my ($self, $state, $ast) = @_; return $self->renderer->resume($state, $ast); }
183 sub unpack_ast { my ($self, $ast) = @_; return $self->parser->unparse_tokens($ast); }
184 sub unparse_text { my ($self, @tokens) = @_; return $self->lexer->unparse_text(@tokens); }
185 sub optimize_ast { my ($self, $hash, $ast) = @_; return $self->optimizer->optimize($hash, $ast); }
186 sub tokenize_text { my ($self, $text) = @_; return $self->lexer->parse_text($text); }
187 sub parse_tokens { my ($self, @tokens) = @_; return $self->parser->parse_tokens(@tokens); }
188 sub parse_text { my ($self, $text) = @_; return $self->parse_tokens($self->tokenize_text($text)); }
189 sub parse_file { my ($self, $file) = @_; return $self->parse_tokens($self->tokenize_file($file)); }
190  
191 use Encode;
192 sub tokenize_file {
193 my ($self, $file) = @_;
194 $self->file_context($file);
195 my $text = decode("UTF-8", scalar(read_file($file)));
196 my @tokens = $self->tokenize_text($text);
197 $self->file_context(undef);
198 return @tokens;
199 }
200  
201  
202 sub verify_text { my ($self, $text) = @_; $self->parse_tokens($self->parse_text($text)); }
203 sub verify_file {
204 my ($self, $file) = @_;
205 $self->file_context($file);
206 $self->verify_text(decode("UTF-8", scalar(read_file($file))));
207 $self->file_context(undef);
208 }
209 sub render_text { my ($self, $hash, $text) = @_; return $self->render_ast($hash, $self->parse_tokens($self->tokenize_text($text))); }
210 sub render_file {
211 my ($self, $hash, $file) = @_;
212 $self->file_context($file);
213 my @results = $self->render_text($hash, decode("UTF-8", scalar(read_file($file))));
214 $self->file_context(undef);
215 return $results[0] unless wantarray;
216 return @results;
217 }
218  
219 use Exporter;
220 use base 'Exporter';
221 our @EXPORT_OK = qw(liquid_render_file liquid_render_text liquid_verify_file liquid_verify_text liquid_parse_file);
222 sub liquid_render_text { my ($hash, $text) = @_; my $self = WWW::Shopify::Liquid->new; return $self->render_text($hash, $text); }
223 sub liquid_verify_text { my ($text) = @_; my $self = WWW::Shopify::Liquid->new; $self->verify_text($text); }
224 sub liquid_parse_file { my ($file) = @_; my $self = WWW::Shopify::Liquid->new; return $self->parse_file($file); }
225 sub liquid_render_file { my ($hash, $file) = @_; my $self = WWW::Shopify::Liquid->new; return $self->render_file($hash, $file); }
226 sub liquid_verify_file { my ($file) = @_; my $self = WWW::Shopify::Liquid->new; $self->verify_file($file); }
227  
228 sub liquify_item {
229 my ($self, $item) = @_;
230 die new WWW::Shopify::Liquid::Exception("Can only liquify shopify objects.") unless ref($item) && $item->isa('WWW::Shopify::Model::Item');
231
232 my $fields = $item->fields();
233 my $final = {};
234 foreach my $key (keys(%$item)) {
235 next unless exists $fields->{$key};
236 if ($fields->{$key}->is_relation()) {
237 if ($fields->{$key}->is_many()) {
238 # Since metafields don't come prepackaged, we don't get them. Unless we've already got them.
239 next if $key eq "metafields" && !$item->{metafields};
240 my @results = $item->$key();
241 if (int(@results)) {
242 $final->{$key} = [map { $self->liquify_item($_) } @results];
243 }
244 else {
245 $final->{$key} = [];
246 }
247 }
248 if ($fields->{$key}->is_one() && $fields->{$key}->is_reference()) {
249 if (defined $item->$key()) {
250 # This is inconsistent; this if is a stop-gap measure.
251 # Getting directly from teh database seems to make this automatically an id.
252 if (ref($item->$key())) {
253 $final->{$key} = $item->$key()->id();
254 }
255 else {
256 $final->{$key} = $item->$key();
257 }
258 }
259 else {
260 $final->{$key} = undef;
261 }
262 }
263 $final->{$key} = ($item->$key ? $item->$key->to_json() : undef) if ($fields->{$key}->is_one() && $fields->{$key}->is_own());
264 } elsif (ref($fields->{$key}) !~ m/Date$/) {
265 $final->{$key} = $fields->{$key}->to_shopify($item->$key);
266 } else {
267 $final->{$key} = $item->$key;
268 }
269 }
270 return $final;
271 }
272  
273  
274 =head1 SEE ALSO
275  
276 L<WWW::Shopify>, L<WWW::Shoipfy::Tools::Themer>, L<Padre::Plugin::Shopify>
277  
278 =head1 AUTHOR
279  
280 Adam Harrison (adamdharrison@gmail.com)
281  
282 =head1 LICENSE
283  
284 Copyright (C) 2016 Adam Harrison
285  
286 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
287  
288 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
289  
290 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
291  
292 =cut
293  
294 1;
« lib/WWW/Shopify/Liquid/Filter/Round.pm ↑ Summary lib/WWW/Shopify/Liquid/Dialect/Web.pm »