blib/lib/XML/Simple/Sugar.pm

filter: Statementstmt 100% 49 / 49 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 13 / 13 Podpod n/a totaltotal 100% 62 / 62 CC 1 SCAR 0.0
CC
1
Cov
100%
__ANON__
1.0
__ANON__
1.0
__ANON__
1.0
CRAP 1.0
↑ Summary
1 1 ▶use 5.18.2;
Subroutine __ANON__: called CC=1 SCAR=0.0
2 1 ▶use Modern::Perl;
Subroutine __ANON__: called CC=1 SCAR=0.0
3 1 ▶use Moops;
Subroutine __ANON__: called CC=1 SCAR=0.0
4  
5 1 ▶class XML::Simple::Sugar 1.0.8 {
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
6 our $AUTOLOAD;
7 use XML::Simple;
8 use UNIVERSAL::isa;
9 use Data::Dumper;
10  
11 has 'xml_index' => ( 'is' => 'ro', 'isa' => 'Int', default => 0 );
12 has 'xml_node' => ( 'is' => 'ro', 'isa' => Maybe[Str] );
13 has 'xml_xs' => (
14 'is' => 'rw',
15 'isa' => 'XML::Simple',
16 'default' => sub { XML::Simple->new( XMLDecl => '<?xml version="1.0"?>' ); }
17 );
18 has 'xml_data' => (
19 'is' => 'rw',
20 'isa' => Maybe[HashRef|ArrayRef],
21 'default' => method { $self->xml_data ? $self->xml_data : {}; }
22 );
23 has 'xml_parent' => ( 'is' => 'ro', 'isa' => InstanceOf['XML::Simple::Sugar'] );
24 has 'xml_autovivify' => ( 'is' => 'rw', 'isa' => Bool, default => 1 );
25 has 'xml' => (
26 'is' => 'rw',
27 'isa' => Str,
28 'trigger' => method {
29 $self->xml_data(
30 XMLin(
31 $self->xml,
32 ForceContent => 1,
33 KeepRoot => 1,
34 ForceArray => 1,
35 ContentKey => 'xml_content',
36 )
37 );
38 }
39 );
40  
41 method xml_write {
42 return $self->xml_xs->XMLout(
43 $self->xml_root->xml_data,
44 KeepRoot => 1,
45 ContentKey => 'xml_content',
46 );
47 }
48  
49 method xml_read (Str $xml) {
50 $self->xml_data(
51 $self->xml_xs->XMLin(
52 $xml,
53 ForceContent => 1,
54 KeepRoot => 1,
55 ForceArray => 1,
56 ContentKey => 'xml_content',
57 )
58 );
59 return $self;
60 }
61  
62 method xml_root {
63 if ( defined( $self->xml_parent ) ) {
64 return $self->xml_parent->xml_root;
65 }
66 else {
67 return $self;
68 }
69 }
70  
71 multi method xml_attr (HashRef $attr) {
72 foreach my $attribute (keys %$attr) {
73 if (
74 $self->xml_autovivify
75 || grep( /^$attribute$/,
76 keys %{
77 $self->xml_parent->xml_data->{ $self->xml_node }
78 ->[ $self->xml_index ]
79 } )
80 )
81 {
82 $self->xml_parent->xml_data->{ $self->xml_node }
83 ->[ $self->xml_index ]->{$attribute} =
84 $attr->{$attribute};
85 }
86 else {
87 die qq|$attribute is not an attribute of | . $self->xml_node;
88 }
89 }
90 return $self;
91 }
92  
93 multi method xml_attr () {
94 my %attr;
95 foreach ( keys %{ $self->xml_data } ) {
96 $attr{$_} = $self->xml_data->{$_}
97 if ( !( UNIVERSAL::isa( $self->xml_data->{$_}, 'ARRAY' ) ) );
98 }
99 return \%attr;
100 }
101  
102 method xml_rmattr (Str $attr) {
103 delete $self->xml_parent->xml_data->{ $self->xml_node }
104 ->[ $self->xml_index ]->{$attr};
105 return $self;
106 }
107  
108 method xml_content (Str $content?) {
109 if ($content) {
110 $self->xml_data->{xml_content} = $content;
111 return $self;
112 }
113 else {
114 $self->xml_data->{xml_content};
115 }
116 }
117  
118 method xml_nest (InstanceOf['XML::Simple::Sugar'] $xs) {
119 $self->xml_parent->xml_data->{ $self->xml_node }->[ $self->xml_index ]
120 = $xs->xml_data;
121 return $self;
122 }
123  
124 multi method xml_subnode (Str $node, InstanceOf['XML::Simple::Sugar'] $content) {
125 $self->xml_data->{$node}->[ $self->xml_index ] = $content->xml_data;
126 }
127  
128 multi method xml_subnode (Str $node, HashRef $content) {
129 foreach my $attribute (keys %$content) {
130 if ( UNIVERSAL::isa( $self->xml_data->{$node}, 'ARRAY' ) ) {
131 if (
132 $self->xml_autovivify
133 || grep( /^$attribute$/,
134 keys %{
135 $self->xml_data->{$node}->[ $self->xml_index ]
136 } )
137 )
138 {
139 $self->xml_data->{$node}->[ $self->xml_index ]
140 ->{$attribute} = $content->{$attribute};
141 }
142 else {
143 die qq|$attribute is not an attribute of $node|;
144 }
145 }
146 else {
147 if (
148 $self->xml_autovivify
149 || grep( /^$attribute$/,
150 keys %{ $self->xml_data->{$node} } )
151 )
152 {
153 $self->xml_data->{$node}->{$attribute} =
154 { 'value' => $content->{$attribute} };
155 }
156 else {
157 die qq|$attribute is not an attribute of $node|;
158 }
159 }
160 }
161 return $self;
162 }
163  
164 multi method xml_subnode (Str $node, ArrayRef $content) {
165 if ( $content->[0] =~ m/^[0-9]+$/ )
166 {
167 if ( $self->xml_autovivify ) {
168 unless ( $self->xml_data->{$node} ) {
169 $self->xml_data->{$node} = [];
170 }
171 unless (
172 UNIVERSAL::isa(
173 $self->xml_data->{$node}->[ $content->[0] ], 'HASH'
174 )
175 )
176 {
177 $self->xml_data->{$node}->[ $content->[0] ] = {};
178 }
179 }
180 else {
181 unless ( $self->xml_data->{$node} ) {
182 die qq|$node not in |
183 . Data::Dumper::Dumper( $self->xml_data );
184 }
185 unless (
186 UNIVERSAL::isa(
187 $self->xml_data->{$node}->[ $content->[0] ], 'HASH'
188 )
189 )
190 {
191 die qq|Element $content->[0] not in |
192 . Data::Dumper::Dumper( $self->xml_data->{$node} );
193 }
194 }
195 my $xs = XML::Simple::Sugar->new(
196 {
197 xml_node => $node,
198 xml_data => $self->xml_data->{$node}->[ $content->[0] ],
199 xml_parent => $self,
200 xml_autovivify => $self->xml_autovivify,
201 xml_index => $content->[0]
202 }
203 );
204 if ( defined( $content->[1] )
205 && UNIVERSAL::isa( $content->[1], 'XML::Simple::Sugar' ) )
206 {
207 $xs->xml_nest( $content->[1] );
208 }
209 elsif ( defined( $content->[1] ) ) {
210 $xs->xml_content( $content->[1] );
211 }
212 if ( defined( $content->[2] )
213 && UNIVERSAL::isa( $content->[2], 'HASH' ) )
214 {
215 $xs->xml_attr( $content->[2] );
216 }
217 return $xs;
218 }
219 elsif ( $content->[0] =~ m/^all$/i )
220 {
221 if ( UNIVERSAL::isa( $self->xml_data->{$node}, 'ARRAY' ) ) {
222 return map {
223 XML::Simple::Sugar->new(
224 {
225 xml_node => $node,
226 xml_data => $self->xml_data->{$node}->[$_],
227 xml_parent => $self,
228 xml_autovivify => $self->xml_autovivify,
229 xml_index => $_
230 }
231 );
232 } 0 .. scalar @{ $self->xml_data->{$node} } - 1;
233 }
234 }
235 }
236
237 multi method xml_subnode (Str $node, Str $content) {
238 $self->xml_data->{$node}->[0]->{xml_content} = $content;
239 return $self;
240 }
241  
242 multi method xml_subnode (Str $node) {
243 unless ( $self->xml_data->{$node} ) {
244 if ( $self->xml_autovivify == 1 ) {
245 $self->xml_data->{$node}->[0] = {};
246 }
247 else {
248 die qq|$node not in |
249 . Data::Dumper::Dumper( $self->xml_data );
250 }
251 }
252  
253 if ( UNIVERSAL::isa( $self->xml_data->{$node}, 'ARRAY' ) ) {
254 return XML::Simple::Sugar->new(
255 {
256 xml_node => $node,
257 xml_data => $self->xml_data->{$node}->[0],
258 xml_parent => $self,
259 xml_autovivify => $self->xml_autovivify,
260 xml_index => $self->xml_index
261 }
262 );
263 }
264 else {
265 return XML::Simple::Sugar->new(
266 {
267 xml_node => $node,
268 xml_data => $self->xml_data->{$node},
269 xml_parent => $self,
270 xml_autovivify => $self->xml_autovivify,
271 xml_index => $self->xml_index
272 }
273 );
274 }
275 }
276  
277 method AUTOLOAD ($content?) {
278 my ($node) = $AUTOLOAD =~ m/([^:]*)$/;
279 $content ? $self->xml_subnode($node, $content) : $self->xml_subnode($node);
280 }
281 }
282  
283 1;
284  
285 # ABSTRACT: Sugar sprinkled on XML::Simple
286 # PODNAME: XML::Simple::Sugar
287  
288 __END__
289  
290 =pod
291  
292 =encoding UTF-8
293  
294 =head1 NAME
295  
296 XML::Simple::Sugar - Sugar sprinkled on XML::Simple
297  
298 =head1 VERSION
299  
300 version v1.0.8
301  
302 =head1 SYNOPSIS
303  
304 use Modern::Perl;
305 use XML::Simple::Sugar;
306
307 my $xs = XML::Simple::Sugar->new;
308
309 # Autovivify some XML elements
310 my $person = $xs->company->departments->department->person;
311
312 # Set some content and attributes
313 $person->first_name('John')
314 ->last_name('Smith')
315 ->email('jsmith@example.com')
316 ->salary(60000);
317
318 $person->xml_attr( { position => 'Engineer' } );
319
320 say $xs->xml_write;
321
322 # <?xml version="1.0"?>
323 # <company>
324 # <departments>
325 # <department>
326 # <person position="Engineer">
327 # <email>jsmith@example.com</email>
328 # <first_name>John</first_name>
329 # <last_name>Smith</last_name>
330 # <salary>60000</salary>
331 # </person>
332 # </department>
333 # </departments>
334 # </company>
335  
336 =head1 DESCRIPTION
337  
338 This module is a wrapper around L<XML::Simple> to provide AUTOLOADed accessors to XML nodes in a given XML document. All nodes of the XML document are XML::Simple::Sugar objects having the following attributes and methods.
339  
340 =head1 ATTRIBUTES
341  
342 =head2 xml (XML Str)
343  
344 This readonly attribute is for use during instantiation (XML::Simple::Sugar->new({ xml => $xml_string })). See also L</xml_read>.
345  
346 =head2 xml_autovivify (Bool DEFAULT true)
347  
348 This attribute determines on a per element basis whether new attributes or elements may be introduced. Child elements inherit this setting from their parent. Setting autovivify to false is useful when working with templates with a strict predefined XML structure. This attribute is true by default.
349  
350 my $xs = XML::Simple::Sugar->new(
351 {
352 xml => qq(
353 <strict_document>
354 <foo>bar</foo>
355 </strict_document>
356 ),
357 xml_autovivify => 0,
358 }
359 );
360  
361 $xs->strict_document->foo('baz'); # Changes bar to baz. Ok!
362 $xs->strict_document->biz('a new element'); # Error! Biz doesn't exist!
363  
364 =head2 xml_data (XML::Simple compliant Perl representation of an XML document)
365  
366 This is the Perl representation of the XML. This is ugly to work with directly (hence this module), but in lieu of methods yet unwritten there may be a use case for having direct access to this structure.
367  
368 =head2 xml_index
369  
370 The index number of an element in a collection
371  
372 =head2 xml_node
373  
374 The name of the current node
375  
376 =head2 xml_parent
377  
378 The parent XML::Simple::Sugar object to the current element
379  
380 =head2 xml_xs
381  
382 This is underlying XML::Simple object. If you need to adjust the XML declaration, you can do that by passing an an XML::Simple object with your preferred options to the C<new> constructor. Be wary of setting other XML::Simple options as this module will happily overwrite anything that conflicts with its assumptions.
383  
384 =head2 xml_root
385  
386 Returns the root element XML::Simple::Sugar object
387  
388 =head1 METHODS
389  
390 =head2 xml_read (XML Str)
391  
392 Parses an XML string and sets the data attribute
393  
394 =head2 xml_write
395  
396 Writes out an XML string
397  
398 =head2 xml_content (Str)
399  
400 Gets or sets the content of the element
401  
402 $xs->person->first_name->xml_content('Bob');
403  
404 # Which can be implicitly written
405 $xs->person->first_name('Bob');
406  
407 # Or using [ index, content, attributes ] notation
408 $xs->person->first_name([ 0, 'Bob', undef ]);
409  
410 say $xs->person->first_name->xml_content;
411 # Bob
412  
413 =head2 xml_attr (HashRef)
414  
415 Gets or sets the attributes of the element.
416  
417 $xs->person->xml_attr( { position => 'Accountant' } );
418  
419 # Which can be implicitly written as...
420 $xs->person( { position => 'Accountant' } );
421  
422 # Or using [ index, content, attributes ] notation
423 $xs->person([ 0, undef, { position => 'Accountant' } ]);
424  
425 my $attributes = $xs->person->xml_attr;
426 say $attributes->{'position'};
427 # Accountant
428  
429 =head2 xml_rmattr (Str)
430  
431 This method removes the passed scalar argument from the element's list of attributes.
432  
433 =head2 xml_nest (XML::Simple::Sugar)
434  
435 Merges another XML::Simple::Sugar object as a child of the current node.
436  
437 my $first_name = XML::Simple::Sugar->new({ xml => '<first_name>Bob</first_name>' });
438 $xs->person->xml_nest( $first_name );
439  
440 # Or using [ index, content, attributes ] notation
441 $xs->person( [ 0, $first_name, undef ] );
442  
443 =head1 Collections
444  
445 When working with a collection of same-named elements, you can access a specific element by index by passing the collection's name an ArrayRef with the index number. For example:
446  
447 my $person2 = $xs->people->person([1]); # Returns the second person element (index 1)
448  
449 You can also work with the entire collection of individual elements by passing an ArrayRef with the string 'all'.
450  
451 my @people = $xs->people->person(['all']); # Returns an array of XML::Simple::Sugar objects
452  
453 =head1 Using [ index, content, attributes ] Notation
454  
455 When authoring even simple XML documents, using [ index, content, attributes ] notation allows you to implicitly invoke L</xml_content>, L</xml_attr>, and L</xml_nest> methods on nodes deep within a collection. For example:
456  
457 # Sets the position attribute of the second person
458 $xs->people->person([ 1, undef, { position => 'Engineer' } ]);
459  
460 # Sets the third person's second favorite color to orange
461 # with a neon attribute
462 $xs->people->person([ 2 ])->favorite_colors->color([ 1, 'orange', { neon => 1 } ]);
463  
464 # Composing large documents from smaller ones
465 my $xs = XML::Simple::Sugar->new( {
466 xml_xs => XML::Simple->new( XMLDecl => '<!DOCTYPE html>' )
467 } );
468 my $xs2 = XML::Simple::Sugar->new;
469  
470 $xs2->table->tr->th([ 0, 'First Name', { style => 'text-align:left' } ]);
471 $xs2->table->tr->th([ 1, 'Last Name' ]);
472  
473 $xs->html->body->div([0])->h1('Page Title');
474 $xs->html->body->div([ 1, $xs2 ]);
475  
476 say $xs->xml_write;
477  
478 # <!DOCTYPE html>
479 # <html>
480 # <body>
481 # <div>
482 # <h1>Page Title</h1>
483 # </div>
484 # <div>
485 # <table>
486 # <tr>
487 # <th style="text-align:left">First Name</th>
488 # <th>Last Name</th>
489 # </tr>
490 # </table>
491 # </div>
492 # </body>
493 # </html>
494  
495 =head1 PLEASE BE ADVISED
496  
497 Most of the automagic happens with AUTOLOAD. Accessors/mutators and method names in this package cannot be used as element names in the XML document. XML naming rules prohibit the use of elements starting with the string "xml", so "xml_" is used as a prefix for all accessors/mutators/methods to avoid potential document conflicts.
498  
499 =head1 REPOSITORY
500  
501 L<https://github.com/Camspi/XML-Simple-Sugar>
502  
503 =head1 MINIMUM PERL VERSION SUPPORTED
504  
505 Perl 5.18.2 or later is required by this module. Lesser Perl versions struggle with deep recursion. Patches welcome.
506  
507 =head1 VERSIONING
508  
509 Semantic versioning is adopted by this module. See L<http://semver.org/>.
510  
511 =head1 SEE ALSO
512  
513 =over 4
514  
515 =item
516 * L<XML::Simple>
517  
518 =back
519  
520 =head1 CREDITS
521  
522 =over 4
523  
524 =item
525 * Jonathan Cast for excellent critique.
526  
527 =item
528 * Kyle Bolton for peeking over my shoulder and giving me pro tips.
529  
530 =item
531 * eMortgage Logic, LLC., for allowing me to publish this module to CPAN
532  
533 =back
534  
535 =head1 AUTHOR
536  
537 Chris Tijerina
538  
539 =head1 COPYRIGHT AND LICENSE
540  
541 This software is copyright (c) 2014 by eMortgage Logic LLC.
542  
543 This is free software; you can redistribute it and/or modify it under
544 the same terms as the Perl 5 programming language system itself.
545  
546 =cut
↑ Summary