blib/lib/Markdown/Parser/Element.pm untested

filter: Statementstmt 0.0% 0 / 320 Branchbran 0.0% 0 / 130 Conditioncond 0.0% 0 / 41 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 84 Podpod 0.0% 0 / 73 totaltotal 0.0% 0 / 648 CC 66 SCAR 39.6
CC
66
Cov
0%
look
240.0
init
182.0
encode_html
90.0
CRAP 52.5
1 ##----------------------------------------------------------------------------
2 ## Markdown Parser Only - ~/lib/Markdown/Parser/Element.pm
3 ## Version v0.2.1
4 ## Copyright(c) 2022 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/08/23
7 ## Modified 2022/09/22
8 ## All rights reserved
9 ##
10 ## This program is free software; you can redistribute it and/or modify it
11 ## under the same terms as Perl itself.
12 ##----------------------------------------------------------------------------
13 package Markdown::Parser::Element;
14 BEGIN
15 {
16 use strict;
17 use warnings;
18 use warnings::register;
19 use parent qw( Module::Generic );
20 use vars qw( $VERSION );
21 use Nice::Try;
22 use CSS::Object;
23 use Devel::Confess;
24 our $VERSION = 'v0.2.1';
25 };
26  
27 use strict;
28 use warnings;
29  
30 sub init
31 {
32 my $self = shift( @_ );
33 ## print( STDERR ref( $self ), "::new: Markdown::Parser::Element::init() Parameters provided are: '", join( "', '", @_ ), "'\n" );
34 my $opts = {};
35 $opts = shift( @_ ) if( $self->_is_hash( $_[0] ) );
36 if( !( scalar( @_ ) % 2 ) && scalar( keys( %$opts ) ) )
37 {
38 my $hash = { @_ };
39 my @keys = keys( %$hash );
40 @$opts{ @keys } = @$hash{ @keys };
41 }
42 elsif( !( scalar( @_ ) % 2 ) )
43 {
44 $opts = { @_ };
45 }
46 $self->{attr} = {} unless( CORE::exists( $self->{attr} ) );
47 $self->{children} = [] unless( CORE::exists( $self->{children} ) );
48 $self->{class} = [] unless( CORE::exists( $self->{class} ) );
49 ## To contain the CSS::Object
50 $self->{css} = '' unless( CORE::exists( $self->{css} ) );
51 ## Dictionary hash object of abbreviations
52 $self->{dict} = {} unless( CORE::exists( $self->{dict} ) );
53 $self->{parent} = '' unless( CORE::exists( $self->{parent} ) );
54 $self->{pos} = '' unless( CORE::exists( $self->{pos} ) );
55 $self->{raw} = '' unless( CORE::exists( $self->{raw} ) );
56 $self->{tag_name} = '' unless( CORE::exists( $self->{tag_name} ) );
57 $self->{_init_strict_use_sub} = 1;
58 ## print( STDERR ref( $self ), "::new: Calling SUPER::init with: ", $self->dump( $opts ) );
59 return( $self->SUPER::init( $opts ) );
60 ## $self->SUPER::init( $opts );
61 ## print( STDERR ref( $self ), "::new: Debug value: ", $self->debug, "\n" );
62 ## return( $self );
63 }
64  
65 sub add_attributes
66 {
67 my $self = shift( @_ );
68 ## A string something like {#id1} or {.cl} or {#id.cl.class}
69 my $def = shift( @_ );
70 return if( !length( $def ) );
71 my( @ids, @classes, @attributes );
72 while( $def =~ s/
73 [[:blank:]\h]*
74 (?<attr_name>[a-zA-Z][\w\-]+)
75 [[:blank:]\h]*
76 =
77 [[:blank:]\h]*
78 (?<quote>["'])?
79 (?(<quote>)
80 (?:(?<attr_value>.*?)\g{quote})
81 |
82 (?<attr_value>\S+)
83 )
84 //xs )
85 {
86 push( @attributes, [ $+{attr_name} => $+{attr_value} ] );
87 }
88 while( $def =~ s/[[:blank:]\h]*\#(?<id>[^[:space:]\h\.\#]+)//s )
89 {
90 push( @ids, $+{id} );
91 }
92 while( $def =~ s/[[:blank:]\h]*\.(?<class>[^[:space:]\h\.\#]+)//s )
93 {
94 push( @classes, $+{class} );
95 }
96 $self->id->push( @ids );
97 $self->class->push( @classes ) if( scalar( @classes ) );
98 if( scalar( @attributes ) )
99 {
100 foreach my $ref ( @attributes )
101 {
102 ## If the user had defined it twice, it might very well override previous data set
103 $self->attributes->set( $ref->[0] => $ref->[1] );
104 }
105 }
106 return( $self );
107 }
108  
109 sub add_element
110 {
111 my $self = shift( @_ );
112 my $obj = shift( @_ );
113 my $base = $self->base_class;
114 return( $self->error( "Element provided \"$obj\" is not an Markdown::Parser::Element object." ) ) if( !$self->_is_a( $obj, "${base}::Element" ) );
115 $obj->parent( $self );
116 $self->children->push( $obj );
117 return( $self );
118 }
119  
120 sub add_to
121 {
122 my $self = shift( @_ );
123 my $obj = shift( @_ );
124 return( $self->error( "Element provided \"$obj\" is not an Markdown::Parser::Element object." ) ) if( !$self->_is_a( $obj, 'Markdown::Parser::Element' ) );
125 $obj->children->push( $self );
126 return( $self );
127 }
128  
129 sub as_markdown
130 {
131 my $self = shift( @_ );
132 warn( "as_markdown method not implemented for ", ref( $self ), "\n" );
133 return;
134 }
135  
136 sub as_pod
137 {
138 my $self = shift( @_ );
139 warn( "as_pod method not implemented for ", ref( $self ), "\n" );
140 return;
141 }
142  
143 sub as_string
144 {
145 my $self = shift( @_ );
146 warn( "as_string method not implemented for ", ref( $self ), "\n" );
147 return;
148 }
149  
150 sub attr { return( shift->_set_get_hash_as_mix_object( 'attr', @_ ) ); }
151  
152 # Alias
153 sub attributes { return( shift-> _set_get_hash_as_mix_object( 'attr', @_ ) ); }
154  
155 sub base_class
156 {
157 my $self = shift( @_ );
158 my $class = ref( $self ) || $self;
159 my @frag = split( /\::/, $class );
160 return( join( '::', @frag[ 0..( $#frag-1 ) ] ) );
161 }
162  
163 sub children { return( shift->_set_get_array_as_object( 'children', @_ ) ); }
164  
165 sub class { return( shift->_set_get_array_as_object( 'class', @_ ) ); }
166  
167 # Returns the closest non-new line element or the one specified
168 sub closest
169 {
170 my $self = shift( @_ );
171 my $target;
172 $target = shift( @_ ) if( @_ );
173 my $elem;
174 # Starting from the latest to the oldest
175 $self->children->reverse->foreach(sub
176 {
177 return(1) if( $_->tag_name eq 'nl' );
178 # We exit (return false) after the first element we found if there is no target specified
179 if( !defined( $target ) ||
180 ( defined( $target ) && $_->tag_name eq $target ) )
181 {
182 $elem = $_;
183 return;
184 }
185 return(1);
186 });
187 return( $elem );
188 }
189  
190 sub create_abbreviation { return( shift->_create_element( 'Abbr', @_ ) ); }
191  
192 sub create_blockquote { return( shift->_create_element( 'Blockquote', @_ ) ); }
193  
194 sub create_bold { return( shift->_create_element( 'Bold', @_ ) ); }
195  
196 sub create_checkbox { return( shift->_create_element( 'Checkbox', @_ ) ); }
197  
198 sub create_code { return( shift->_create_element( 'Code', @_ ) ); }
199  
200 sub create_em { return( shift->_create_element( 'Emphasis', @_ ) ); }
201  
202 sub create_footnote { return( shift->_create_element( 'Footnote', @_ ) ); }
203  
204 sub create_footnote_ref { return( shift->_create_element( 'FootnoteReference', @_ ) ); }
205  
206 sub create_header { return( shift->_create_element( 'Header', @_ ) ); }
207  
208 sub create_image { return( shift->_create_element( 'Image', @_ ) ); }
209  
210 sub create_html { return( shift->_create_element( 'HTML', @_ ) ); }
211  
212 sub create_insertion { return( shift->_create_element( 'Insertion', @_ ) ); }
213  
214 sub create_line { return( shift->_create_element( 'Line', @_ ) ); }
215  
216 sub create_link_definition { return( shift->_create_element( 'LinkDefinition', @_ ) ); }
217  
218 sub create_link { return( shift->_create_element( 'Link', @_ ) ); }
219  
220 sub create_list { return( shift->_create_element( 'List', @_ ) ); }
221  
222 sub create_list_item { return( shift->_create_element( 'ListItem', @_ ) ); }
223  
224 sub create_new_line { return( shift->_create_element( 'NewLine', @_ ) ); }
225  
226 sub create_paragraph { return( shift->_create_element( 'Paragraph', @_ ) ); }
227  
228 sub create_strikethrough { return( shift->_create_element( 'StrikeThrough', @_ ) ); }
229  
230 sub create_subscript { return( shift->_create_element( 'Subscript', @_ ) ); }
231  
232 sub create_superscript { return( shift->_create_element( 'Superscript', @_ ) ); }
233  
234 sub create_table { return( shift->_create_element( 'Table', @_ ) ); }
235  
236 sub create_table_body { return( shift->_create_element( 'TableBody', @_ ) ); }
237  
238 sub create_table_caption { return( shift->_create_element( 'TableCaption', @_ ) ); }
239  
240 sub create_table_cell { return( shift->_create_element( 'TableCell', @_ ) ); }
241  
242 sub create_table_column { return( shift->_create_element( 'TableColumn', @_ ) ); }
243  
244 sub create_table_header { return( shift->_create_element( 'TableHeader', @_ ) ); }
245  
246 sub create_table_row { return( shift->_create_element( 'TableRow', @_ ) ); }
247  
248 sub create_text { return( shift->_create_element( 'Text', @_ ) ); }
249  
250 sub css { return( shift->_set_get_object( 'css', 'CSS::Object', @_ ) ); }
251  
252 sub css_inline
253 {
254 return( CSS::Object->new( format => 'CSS::Object::Format::Inline' ) );
255 }
256  
257 sub detach
258 {
259 my $self = shift( @_ );
260 my $arr = $self->children->clone;
261 $self->children->reset;
262 return( $arr );
263 }
264  
265 sub document { return( shift->_set_get_object( 'document', 'Markdown::Parser::Document', @_ ) ); }
266  
267 sub empty
268 {
269 my $self = shift( @_ );
270 $self->children->reset;
271 return( $self );
272 }
273  
274 sub encode_html
275 {
276 my $self = shift( @_ );
277 my( $what, $text ) = @_;
278 return if( !defined( $text ) );
279 my $map =
280 {
281 '<' => '&lt;',
282 '>' => '&gt;',
283 ## Also &#38;
284 '&' => '&amp;',
285 ## Also &#63;
286 '?' => '&quest;',
287 ## Also known as &num;
288 '#' => '&#35;',
289 '"' => '&quot;',
290 "'" => '&#39;',
291 };
292 my $data = $self->_is_scalar( $text ) ? $text : \$text;
293 $what = [keys( %$map )] if( $what eq 'all' );
294 return( $self->error( "List of items to encode is not an array reference." ) ) if( !$self->_is_array( $what ) );
295 return( $$data ) if( !scalar( @$what ) );
296 ## return( $self->error( "Text to encode is not a scalar reference." ) ) if( !$self->_is_scalar( $text ) );
297 my $todo = {};
298 ## Make a hash of characters to encode
299 @$todo{ @$what } = ( 1 ) x scalar( @$what );
300 if( my $amp = delete( $todo->{ '&' } ) )
301 {
302 ## 1 while( $$data =~ s/(?<!\\)(\&)(?!\d+\;)/$map->{ $1 }/gs );
303 $$data =~ s/(?<!\\)(\&)(?!(?:amp|gt|lt)\;)/$map->{ $1 }/gs;
304 }
305 if( my $amp = delete( $todo->{ '#' } ) )
306 {
307 ## 1 while( $$data =~ s/(?<!\\)(\#)(?!(?:amp|gt|lt)\;)/$map->{ $1 }/gs );
308 $$data =~ s/(?:(?<!\\)|(?<!\&))(\#)(?!\d+\;)/$map->{ $1 }/gs;
309 }
310 if( scalar( %$todo ) )
311 {
312 my $re = join( '|', map( quotemeta( $_ ), keys( %$todo ) ) );
313 ## 1 while( $$data =~ s/(?<!\\)($re)/$map->{ $1 }/gs );
314 $$data =~ s/(?<!\\)($re)/$map->{ $1 }/gs;
315 }
316 # return( $self );
317 return( $$data );
318 }
319  
320 sub extract_links
321 {
322 my $self = shift( @_ );
323 # my $links = $self->new_array;
324 # $self->children->for(sub
325 # {
326 # my( $i, $link ) = @_;
327 # if( $self->_is_a( $link => 'Markdown::Parser::Link' ) )
328 # {
329 # $links->push( $link );
330 # }
331 # if( $link->children->length > 0 )
332 # {
333 # my $more_links = $link->extract_links;
334 # $links->push( $more_links->list ) if( $more_links->length );
335 # }
336 # });
337 my $links = $self->look_down( tag => 'link' );
338 return( $links );
339 }
340  
341 sub format_attributes
342 {
343 my $self = shift( @_ );
344 my $attr = $self->attributes;
345 ## Return an empty array if there is nothing
346 return( $self->new_array ) if( !$attr->length );
347 return( $attr->map_array(sub{ sprintf( '%s="%s"', $_, $attr->{ $_ } ) }) );
348 }
349  
350 sub format_class
351 {
352 my $self = shift( @_ );
353 if( $self->class->length )
354 {
355 return( sprintf( 'class="%s"', $self->class->join( ' ' )->scalar ) );
356 }
357 return( '' );
358 }
359  
360 sub format_id
361 {
362 my $self = shift( @_ );
363 if( $self->id->length )
364 {
365 return( sprintf( 'id="%s"', $self->id->join( ' ' )->scalar ) );
366 }
367 return( '' );
368 }
369  
370 sub id { return( shift->_set_get_array_as_object( 'id', @_ ) ); }
371  
372 sub insert_after
373 {
374 my $self = shift( @_ );
375 my $elem = shift( @_ );
376 return if( !length( $elem ) );
377 my $base_class = $self->base_class;
378 return( $self->error( "Element provided is not ${base_class}::Element object." ) ) if( !$self->_is_a( "${base_class}::Element", $elem ) );
379 return if( !$self->parent );
380 my $children = $self->parent->children;
381 my $pos = $children->pos( $self );
382 return if( !defined( $pos ) );
383 $children->splice( $pos + 1, 0, $elem );
384 return( $elem );
385 }
386  
387 sub insert_before
388 {
389 my $self = shift( @_ );
390 my $elem = shift( @_ );
391 return if( !length( $elem ) );
392 my $base_class = $self->base_class;
393 return( $self->error( "Element provided is not ${base_class}::Element object." ) ) if( !$self->_is_a( "${base_class}::Element", $elem ) );
394 return if( !$self->parent );
395 my $children = $self->parent->children;
396 my $pos = $children->pos( $self );
397 return if( !defined( $pos ) );
398 $children->splice( $pos, 0, $elem );
399 return( $elem );
400 }
401  
402 sub look
403 {
404 my $self = shift( @_ );
405 my $opts = $self->_get_args_as_hash( @_ );
406 $opts->{direction} //= 'down';
407 unless( $opts->{direction} eq 'down' ||
408 $opts->{direction} eq 'up' )
409 {
410 return( $self->error( "Unknown direction provided '$opts->{direction}'" ) );
411 }
412 my $a = $self->new_array;
413 my( $check_elem, $crawl_down );
414 $check_elem = sub
415 {
416 my $e = shift( @_ );
417 my $def = shift( @_ );
418 $def->{level} //= 0;
419 # Assume not ok, then check otherwise
420 my $ok = 0;
421 if( defined( $opts->{tag} ) && length( $opts->{tag} ) )
422 {
423 if( ref( $opts->{tag} ) eq 'Regexp' )
424 {
425 $ok = 1 if( $e->tag_name =~ /$opts->{tag}/ );
426 }
427 else
428 {
429 $ok = 1 if( $e->tag_name eq $opts->{tag} );
430 }
431 }
432 if( defined( $opts->{class} ) && length( $opts->{class} ) )
433 {
434 $ok = $self->_is_a( $e => $opts->{class} ) ? 1 : 0;
435 }
436
437 # We passed all checks, no checking our children
438 $a->push( $e ) if( $ok );
439 # Stop here since we reached the maximum number of matches
440 return if( CORE::exists( $opts->{max_match} ) && $a->length >= $opts->{max_match} );
441 # Don't go down or up further if we reached the maximum level
442 return(1) if( CORE::exists( $opts->{max_level} ) && ( $def->{level} + 1 ) > $opts->{max_level} );
443 $def->{level}++;
444 if( $opts->{direction} eq 'down' )
445 {
446 $crawl_down->( $e->children, $def ) if( $e->children->length > 0 );
447 }
448 elsif( $opts->{direction} eq 'up' )
449 {
450 $check_elem->( $e->parent ) if( $e->parent );
451 }
452 $def->{level}--;
453 return(1);
454 };
455
456 $crawl_down = sub
457 {
458 my $kids = shift( @_ );
459 my $def = shift( @_ );
460 $kids->foreach(sub
461 {
462 $check_elem->( $_, $def );
463 });
464 };
465
466 my $def = { level => 0 };
467 $check_elem->( $self, $def );
468 # return( $a->length > 0 ? $a : '' );
469 return( $a );
470 }
471  
472 sub look_down
473 {
474 my $self = shift( @_ );
475 my $opts = $self->_get_args_as_hash( @_ );
476 $opts->{direction} = 'down';
477 return( $self->look( $opts ) );
478 }
479  
480 sub look_up
481 {
482 my $self = shift( @_ );
483 my $opts = $self->_get_args_as_hash( @_ );
484 $opts->{direction} = 'up';
485 return( $self->look( $opts ) );
486 }
487  
488 sub make_html_parser
489 {
490 my $self = shift( @_ );
491 require HTML::Object;
492 return( HTML::Object->new );
493 }
494  
495 sub object_id
496 {
497 my $self = shift( @_ );
498 return( $self->{object_id} ) if( length( $self->{object_id} ) );
499 $self->{object_id} = Scalar::Util::refaddr( $self );
500 return( $self->{object_id} );
501 }
502  
503 sub package { return( ref( $_[0] ) ); }
504  
505 sub parent { return( shift->_set_get_object( 'parent', 'Markdown::Parser::Element', @_ ) ); }
506  
507 sub parse_html
508 {
509 my $self = shift( @_ );
510 my $html = shift( @_ ) || return;
511 my $p = $self->make_html_parser;
512 my $doc = $p->parse_data( $html ) ||
513 return( $self->pass_error( $p->error ) );
514 return( $doc );
515 }
516  
517 sub pos { return( shift->_set_get_number_as_object( 'pos', @_ ) ); }
518  
519 sub raw { return( shift->_set_get_scalar_as_object( 'raw', @_ ) ); }
520  
521 sub remove
522 {
523 my $self = shift( @_ );
524 if( @_ )
525 {
526 my $elem = shift( @_ );
527 return if( !length( $elem ) );
528 my $base_class = $self->base_class;
529 return( $self->error( "Element provided is not a ${base_class}::Element object." ) ) if( !$self->_is_a( "${base_class}::Element", $elem ) );
530 my $pos = $self->children->pos( $elem );
531 return if( !defined( $pos ) );
532 return( $self->children->delete( $pos, 1 ) );
533 }
534 ## Called without argument: remove itself from its parent
535 elsif( $self->_is_object( $self->parent ) )
536 {
537 return( $self->parent->remove( $self ) );
538 }
539 return;
540 }
541  
542 sub remove_children { return( shift->children->reset ); }
543  
544 sub tag_name { return( shift->_set_get_scalar_as_object( 'tag_name', @_ ) ); }
545  
546 sub wrap
547 {
548 my $self = shift( @_ );
549 my $elem = shift( @_ );
550 my $base_class = $self->base_class;
551 return( $self->error( "Element provided to wrap children is not a ${base_class}::Element object." ) ) if( !$self->_is_a( $elem, "${base_class}::Element" ) );
552 ## Copy our children to the element provided and set the parent property accordingly
553 $self->children->foreach(sub
554 {
555 $elem->add_element( $_ );
556 });
557 $self->remove_children;
558 ## Set this element as our only child and set the parent property accordingly
559 $self->add_element( $elem );
560 return( $self );
561 }
562  
563 sub _append_text
564 {
565 my $self = shift( @_ );
566 my $what = shift( @_ ) || return;
567 my $elem_class = $self->base_class . '::Element';
568 if( $self->_is_a( $what, $elem_class ) )
569 {
570 $self->children->push( $what );
571 }
572 elsif( ref( $what ) )
573 {
574 return( $self->error( "I do not know what to do with this reference \"$what\". I was expecting either a string or a $elem_class class object." ) );
575 }
576 ## Simple string, i.e. a text chunk
577 else
578 {
579 if( $self->children->last->tag_name eq 'text' )
580 {
581 $self->children->last->append( " $what" );
582 }
583 else
584 {
585 $self->children->push( $self->create_text({
586 text => $what,
587 raw => $what,
588 }) );
589 }
590 }
591 return( $self );
592 }
593  
594 sub _create_element
595 {
596 my $self = shift( @_ );
597 my $mod = shift( @_ );
598 my $base = $self->base_class;
599 my $class = "${base}::${mod}";
600 $self->_load_class( $class ) || return;
601 my $obj = $class->new( @_, debug => $self->debug ) || return( $self->pass_error( $class->error ) );
602 ## Assign the top document object, which is used by children element to access the document object methods
603 if( $self->isa( 'Markdown::Parser::Document' ) )
604 {
605 $obj->document( $self );
606 }
607 elsif( my $doc = $self->document )
608 {
609 $obj->document( $doc );
610 }
611 return( $obj );
612 }
613  
614 1;
615 # NOTE: POD
616 __END__