Composer.pm

filter: Statementstmt 100% 96 / 96 Branchbran 91.3% 53 / 58 Conditioncond 65.6% 21 / 32 MC/DCmcdc 47.6% 10 / 21 Subroutinesub 100% 12 / 12 Podpod 100% 4 / 4 totaltotal 87.8% 196 / 223 CC 42 SCAR 28.0
CC
42
Cov
91%
_render
24.2
html
17.1
partial
3.0
CRAP 16.4
↑ Summary Composer/Unsafe.pm »
1 # MIT License
2 #
3 # Copyright (c) 2026 Rawley Fowler <rawleyfowler@proton.me>
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in all
13 # copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 # SOFTWARE.
22  
23 package HTML::Composer;
24  
25 =head1 NAME
26  
27 HTML::Composer - Compose validated HTML from Perl data structures
28  
29 =head1 SYNOPSIS
30  
31 HTML::Composer is inspired by TyXML and Hiccup to provide a data-driven HTML builder for Perl that allows
32 developers to compose data to validated HTML in an efficient, intuitive, high-performance way.
33  
34 use HTML::Composer;
35
36 my $h = HTML::Composer->new();
37 my $html = $h->html([
38 head => [
39 title => ["My Site"],
40 script => {
41 src => "/js/myScript.js",
42 type => "text/javascript"
43 }
44 ],
45 body => [
46 h1 => ["Hello World!"],
47 br => {},
48 div => { class => [ "p-3", "background-red" ] } => [
49 "Hello World!", h2 => ["Test 123"]
50 ]
51 ]
52 ]
53 );
54  
55 This will output the following HTML:
56  
57 <!DOCTYPE html>
58 <html>
59 <head>
60 <title>My Site</title>
61 <script src="/js/myScript.js" type="text/javascript"></script>
62 </head>
63 <body>
64 <h1>Hello World</h1>
65 <br>
66 <div class="p-3 background-red">
67 Hello World!
68 <h2>Test 123</h2>
69 </div>
70 </body>
71 </html>
72  
73 HTML elements that allow children are created like:
74  
75 [div => ["Text!", h1 => ["Text!"]]] # <div>Text!<h1>Text!</h1></div>
76  
77 To provide attributes to a tag:
78  
79 [div => { class => ["p-3", "m-2"] } => ["Text!", h1 => ["Text!"]]] # <div class="p-3 m-2">Text!<h1>Text!</h1></div>
80  
81 If a tag doesn't have any children, ie a <link> tag:
82  
83 [link => { href => "www.google.com" }] # <link href="www.google.com">
84  
85 If a tag doesn't have any attributes:
86  
87 [br => {}] # <br>
88  
89 To render just text, make sure it isn't followed up by an array, or hash:
90  
91 ["Text!"]
92  
93 =cut
94  
95 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
96 8 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
97 8 ▶use feature qw(state);
Subroutine BEGIN: called CC=1 SCAR=0.0
98  
99 8 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
100 8 ▶use HTML::Escape qw(escape_html);
Subroutine BEGIN: called CC=1 SCAR=0.0
101  
102 8 ▶use Sereal::Encoder;
Subroutine BEGIN: called CC=1 SCAR=0.0
103 8 ▶use HTML::Composer::Unsafe;
Subroutine BEGIN: called CC=1 SCAR=0.0
104  
105 8 my @allowed_head_tags = qw(
106 title meta link style script noscript base template
107 );
108  
109 8 my @allowed_body_tags = qw();
110  
111 8 my @disallowed_body_tags = qw(
112 title meta base link
113 );
114  
115 =head2 new(%ARGS)
116  
117 Create a new instance of HTML::Composer. Optionally, pass a cache argument, to tell
118 HTML::Hash to cache the result against the hash you pass. (Caching defaults to false).
119  
120 my $h = HTML::Composer->new(); # Cached instance of HTML::Composer
121 $h->html(...);
122  
123 my $hc = HTML::Composer->new(cache => 0); # Don't cache templates
124 $hc->html(...);
125  
126 =cut
127  
128 sub new {
129 11 ▶ my ( $class, %args ) = @_;
Subroutine new: called CC=2 SCAR=6.9
Pod documented
130 return bless {
131 11 ▶ cache => $args{cache} // 0,
Condition100%2/2
$args{"cache"} // 0
l!l
110
MC/DC100%1/1
$args{"cache"} // 0
$args{"cache"}
Truth table100%2/2
A
A= $args{"cache"}
Aresult
11
00
132 store => {},
133 encoder => Sereal::Encoder->new(
134 {
135 snappy => 1,
136 croak_on_bless => 1,
137 stringify_unknown => 1,
138 canonical => 1
139 }
140 )
141 }, $class;
142 }
143  
144 =head2 html(ARRAY)
145  
146 Create a string containing the HTML page described in ARRAY. Croaks if HTML validation fails.
147  
148 my $h = HTML::Composer->new();
149 my $html = $h->html([
150 head => [
151 title => ["My Site"],
152 script => {
153 src => "/js/myScript.js",
154 type => "text/javascript"
155 }
156 ],
157 body => [
158 h1 => ["Hello World!"],
159 br => {},
160 div => { class => [ "p-3", "background-red" ] } => [
161 "Hello World!", h2 => ["Test 123"]
162 ]
163 ]
164 ]
165 );
166  
167 If you need to pass attributes to the root <html> tag you can do so with:
168  
169 my $h = HTML::Composer->new();
170 my $html = $h->html({lang => 'en'} => [
171 head => [
172 title => ["My Site"],
173 script => {
174 src => "/js/myScript.js",
175 type => "text/javascript"
176 }
177 ],
178 body => [
179 h1 => ["Hello World!"],
180 br => {},
181 div => { class => [ "p-3", "background-red" ] } => [
182 "Hello World!", h2 => ["Test 123"]
183 ]
184 ]
185 ]
186 );
187  
188 =cut
189  
190 sub html {
191 36 ▶ my ( $self, @args ) = @_;
Subroutine html: called CC=17 SCAR=28.4
Pod documented
192  
193 36 my $h;
194 my $ha;
195 36 ▶ if ( @args > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args > 1) 4 32 36
196 4 $ha = shift(@args);
197 }
198 36 $h = shift(@args);
199  
200 36 my $rh = ref($h);
201 36 my $rha = ref($ha);
202  
203 36 ▶ croak "Bad value passed to HTML::Composer for"
Branch: 1 branch
BranchTrueFalseTotal
if $rha and $rha ne "HASH" 1 35 36
Condition100%3/3
$rha and $rha ne "HASH"
!ll&&!rl&&r
3231
MC/DC100%2/2
$rha and $rha ne "HASH"
$rha $rha ne "HASH"
Truth table100%3/3
A and B
A= $rhaB= $rha ne "HASH"
ABresult
0X0
100
111
204 . "html attrs expected HASH got $rha"
205 if ( $rha && $rha ne 'HASH' );
206 35 ▶ croak "Bad value passed to HTML::Composer, expected ARRAY got $rh"
Branch: 1 branch
BranchTrueFalseTotal
if not $rh or $rh ne "ARRAY" 0 35 35
Condition33%1/3
not $rh or $rh ne "ARRAY"
l!l&&r!l&&!r
0035
MC/DC0%0/2
not $rh or $rh ne "ARRAY"
not $rh $rh ne "ARRAY"
Truth table33%1/3
not(A) or B
A= not $rhB= $rh ne "ARRAY"
ABresult
1X1
011
000
207 if ( !$rh || $rh ne 'ARRAY' );
208  
209 35 my $s = scalar(@$h);
210  
211 # We expect 4 args, head, (head elements), body, (body elements)
212 35 ▶ croak "Invalid number of elements in ARRAY, expected 4 got $s"
Branch: 1 branch
BranchTrueFalseTotal
unless $s == 4 2 33 35
213 unless $s == 4;
214  
215 33 my ( $hs, $hb, $bs, $bb ) = @$h;
216  
217 33 ▶ croak "Invalid head tag: $hs expected head" unless $hs eq 'head';
Branch: 1 branch
BranchTrueFalseTotal
unless $hs eq "head" 1 32 33
218 32 ▶ croak "Invalid body tag: $bs expected body" unless $bs eq 'body';
Branch: 1 branch
BranchTrueFalseTotal
unless $bs eq "body" 1 31 32
219  
220 31 my $hr = ref($hb);
221 31 ▶ croak "Invalid head type, expected ARRAY got $hb"
Branch: 1 branch
BranchTrueFalseTotal
unless $hr and $hr eq "ARRAY" 1 30 31
Condition66%2/3
$hr and $hr eq "ARRAY"
!ll&&!rl&&r
1030
MC/DC50%1/2
$hr and $hr eq "ARRAY"
$hr $hr eq "ARRAY"
Truth table66%2/3
A and B
A= $hrB= $hr eq "ARRAY"
ABresult
0X0
100
111
222 unless $hr && $hr eq 'ARRAY';
223 30 my $br = ref($bb);
224 30 ▶ croak "Invalid body type, expected ARRAY got $br"
Branch: 1 branch
BranchTrueFalseTotal
unless $br and $br eq "ARRAY" 1 29 30
Condition66%2/3
$br and $br eq "ARRAY"
!ll&&!rl&&r
1029
MC/DC50%1/2
$br and $br eq "ARRAY"
$br $br eq "ARRAY"
Truth table66%2/3
A and B
A= $brB= $br eq "ARRAY"
ABresult
0X0
100
111
225 unless $br && $br eq 'ARRAY';
226  
227 29 ▶ my $html = [ html => ( $ha ? $ha : () ) => $h ];
Branch: 1 branch
BranchTrueFalseTotal
$ha ? : 3 26 29
228  
229 29 ▶ if ( $self->{cache} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 4 25 29
230 4 my $encoded = $self->{encoder}->encode($html);
231 4 ▶ if ( $self->{store}->{$encoded} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"store"}{$encoded}) 2 2 4
232 2 return $self->{store}->{$encoded};
233 }
234 }
235  
236 27 my $root = _render( $html, "<!DOCTYPE html>" );
237  
238 25 ▶ if ( $self->{cache} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 2 23 25
239 2 $self->{store}->{ $self->{encoder}->encode($html) } = $root;
240 }
241  
242 25 return $root;
243 }
244  
245 =head2 partial(ARRAY)
246  
247 Create a string containing the HTML partial described in ARRAY. Must have one root element.
248  
249 use HTML::Composer;
250
251 my $h = HTML::Composer->new;
252 my $html = $h->partial([
253 div => [
254 "Hello, World!",
255 a => { href => "https://www.google.com" } => ["www.google.com"]
256 ]
257 ]);
258
259 say $html; # <div>Hello, World!<a href="https://www.google.com">www.google.com</a></div>
260  
261 =cut
262  
263 sub partial {
264 7 ▶ my ( $self, $h ) = @_;
Subroutine partial: called CC=3 SCAR=11.0
Pod documented
265  
266 7 ▶ croak 'partial expects a single argument of type ARRAY'
Branch: 1 branch
BranchTrueFalseTotal
if not ref $h or ref $h ne "ARRAY" 2 5 7
Condition100%3/3
not ref $h or ref $h ne "ARRAY"
l!l&&r!l&&!r
115
MC/DC100%2/2
not ref $h or ref $h ne "ARRAY"
not ref $h ref $h ne "ARRAY"
Truth table100%3/3
not(A) or B
A= not ref $hB= ref $h ne "ARRAY"
ABresult
1X1
011
000
267 if !ref($h) || ref($h) ne 'ARRAY';
268  
269 5 return _render( $h, '' );
270 }
271  
272 =head2 unsafe(SCALAR)
273  
274 Create an instance of L<HTML::Composer::Unsafe>, these objects encapsulate the value you provide,
275 and are not escaped by HTML::Composer when the HTML is rendered.
276  
277 use HTML::Composer;
278
279 my $h = HTML::Composer->new;
280 my $unsafe_text = $h->unsafe(q[document.body.addEventListener('htmx:configRequest', (event) => {})]);
281
282 ref($unsafe_text) # HTML::Composer::Unsafe
283
284 my $html = $h->html([
285 head => [
286 title => ["My Site!"],
287 script => [$unsafe_text]
288 ],
289 body => [
290 div => [
291 "Hello World!"
292 ]
293 ]
294 ]);
295  
296 =cut
297  
298 sub unsafe {
299 2 ▶ my ( $self, $str ) = @_;
Subroutine unsafe: called CC=1 SCAR=0.0
Pod documented
300 2 return HTML::Composer::Unsafe->new($str);
301 }
302  
303 sub _render {
304 32 ▶ my ( $html, $root ) = @_;
Subroutine _render: called CC=23 SCAR=31.9
305  
306 32 my @stack = reverse(@$html);
307 32 my @a = ($root);
308 32 ▶ while (@stack) {
Branch: 1 branch
BranchTrueFalseTotal
if (@stack) 5834 30 5864
309 5834 my $o = pop(@stack);
310 5834 my $ro = ref($o);
311 5834 ▶ if ( !$ro ) { # Plain text or tag
Branch: 5 branches
BranchTrueFalseTotal
if (not $ro) { } 2358 3476 5834
elsif ($ro eq 'HASH') { } 739 2737 3476
elsif ($ro eq 'ARRAY') { } 1369 1368 2737
elsif ($ro eq 'SCALAR') { } 1367 1 1368
elsif ($ro eq 'HTML::Composer::Unsafe') { } 1 0 1
312 2358 ▶ if ( my $rsp = ref( $stack[-1] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rsp = ref $stack[-1]) { } 2354 4 2358
313 2354 my $rsp_array = $rsp eq 'ARRAY';
314 2354 my $rsp_hash = $rsp eq 'HASH';
315 2354 ▶ if ( $rsp && ( $rsp_array | $rsp_hash ) )
Branch: 1 branch
BranchTrueFalseTotal
if ($rsp and $rsp_array | $rsp_hash) { } 1388 966 2354
Condition66%2/3
$rsp and $rsp_array | $rsp_hash
!ll&&!rl&&r
09661388
MC/DC50%1/2
$rsp and $rsp_array | $rsp_hash
$rsp $rsp_array | $rsp_hash
Truth table66%2/3
A and B
A= $rspB= $rsp_array | $rsp_hash
ABresult
0X0
100
111
316 { # It is a tag if it has a follow up attr HASH or, body ARRAY
317 1388 push @a, '<', my $eo = escape_html($o);
318  
319 1388 ▶ if ( !grep { $_ eq $eo }
Branch: 1 branch
BranchTrueFalseTotal
if (not grep({$_ eq $eo;} 'br', 'img', 'input', 'meta', 'link', 'hr', 'col', 'source')) { } 1371 17 1388
320 qw(br img input meta link hr col source) )
321 {
322 1371 ▶ if ($rsp_array) { # If no attributes
Branch: 2 branches
BranchTrueFalseTotal
if ($rsp_array) { } 647 724 1371
elsif ($rsp_hash) { } 724 0 724
323 647 push @a, '>';
324 647 splice( @stack, scalar(@stack) - 1, 0, \$o );
325 }
326 elsif ($rsp_hash) {
327 724 my $rsb = ref( $stack[-2] );
328  
329 724 ▶ if ( $rsb && $rsb eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rsb and $rsb eq 'ARRAY') { } 722 2 724
Condition66%2/3
$rsb and $rsb eq "ARRAY"
!ll&&!rl&&r
02722
MC/DC50%1/2
$rsb and $rsb eq "ARRAY"
$rsb $rsb eq "ARRAY"
Truth table66%2/3
A and B
A= $rsbB= $rsb eq "ARRAY"
ABresult
0X0
100
111
330 722 splice( @stack, scalar(@stack) - 2, 0, \$o );
331 }
332 else {
333 2 splice( @stack, scalar(@stack) - 1, 0, \$o );
334 }
335 }
336 }
337 else {
338 17 ▶ croak "Cannot pass children to tag of type $o"
Branch: 1 branch
BranchTrueFalseTotal
if $rsp ne "HASH" 2 15 17
339 if ( $rsp ne 'HASH' )
340 ; # Non child elements, ie meta, link, etc (CANNOT HAVE CHILDREN)
341 }
342 }
343 else {
344 966 push @a, escape_html($o);
345 }
346 }
347 else {
348 4 push @a, escape_html($o);
349 }
350 }
351 elsif ( $ro eq 'HASH' ) { # Attributes
352 739 for ( sort keys %$o ) {
353 950 my $ra = ref( $o->{$_} );
354 my $av = ( $ra && $ra eq 'ARRAY' )
355 ? join(
356 ' ',
357 map {
358 409 ▶ ref($_)
Branch: 1 branch
BranchTrueFalseTotal
ref $_ && ref $_ eq 'HTML::Composer::Unsafe' ? : 0 409 409
Condition33%1/3
ref $_ and ref $_ eq "HTML::Composer::Unsafe"
!ll&&!rl&&r
40900
MC/DC0%0/2
ref $_ and ref $_ eq "HTML::Composer::Unsafe"
ref $_ ref $_ eq "HTML::Composer::Unsafe"
Truth table33%1/3
A and B
A= ref $_B= ref $_ eq "HTML::Composer::Unsafe"
ABresult
0X0
100
111
359 && ref($_) eq 'HTML::Composer::Unsafe'
360 ? $_
361 : escape_html($_)
362 204 ▶ } @{ $o->{$_} }
Branch: 1 branch
BranchTrueFalseTotal
$ra && $ra eq 'HTML::Composer::Unsafe' ? : 0 746 746
Condition33%1/3
$ra and $ra eq "HTML::Composer::Unsafe"
!ll&&!rl&&r
74600
MC/DC0%0/2
$ra and $ra eq "HTML::Composer::Unsafe"
$ra $ra eq "HTML::Composer::Unsafe"
Truth table33%1/3
A and B
A= $raB= $ra eq "HTML::Composer::Unsafe"
ABresult
0X0
100
111
363 )
364 : ( $ra && $ra eq 'HTML::Composer::Unsafe' ) ? $o->{$_}
365 950 ▶ : escape_html( $o->{$_} );
Branch: 1 branch
BranchTrueFalseTotal
$ra && $ra eq 'ARRAY' ? : 204 746 950
Condition66%2/3
$ra and $ra eq "ARRAY"
!ll&&!rl&&r
7460204
MC/DC50%1/2
$ra and $ra eq "ARRAY"
$ra $ra eq "ARRAY"
Truth table66%2/3
A and B
A= $raB= $ra eq "ARRAY"
ABresult
0X0
100
111
366 950 push @a, ' ', escape_html($_), '="', $av, '"';
367 }
368  
369 739 push @a, '>';
370 }
371 elsif ( $ro eq 'ARRAY' ) { # Child elements
372 1369 my $elems = scalar @$o;
373 1369 push @stack, reverse(@$o);
374 }
375 elsif ( $ro eq 'SCALAR' )
376 { # This is our close marker, they are pushed to be after the child elements of a tag
377 1367 my $elem = $$o;
378 1367 push @a, '</', escape_html($elem), '>';
379 }
380 elsif ( $ro eq 'HTML::Composer::Unsafe' ) {
381 1 push @a, $o . '';
382 }
383 }
384  
385 30 return join( '', @a );
386 }
387  
388 8 1;
↑ Summary Composer/Unsafe.pm »