blib/lib/CSS/Simple.pm untested

filter: Statementstmt 0.0% 0 / 186 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 28 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 288 CC 18 SCAR 26.4
CC
18
Cov
0%
read
56.0
new
12.0
BEGIN
6.0
CRAP 14.0
1 package CSS::Simple;
2 use strict;
3 use warnings;
4  
5 our $VERSION = '3223';
6  
7 use Carp;
8  
9 use Tie::IxHash;
10 use Storable qw(dclone);
11  
12 =pod
13  
14 =head1 NAME
15  
16 CSS::Simple - Interface through which to read/write/manipulate CSS files while respecting the cascade order
17  
18 =head1 SYNOPSIS
19  
20 use CSS::Simple;
21  
22 my $css = new CSS::Simple();
23  
24 $css->read_file({ filename => 'input.css' });
25  
26 #perform manipulations...
27  
28 $css->write_file({ filename => 'output.css' });
29  
30 =head1 DESCRIPTION
31  
32 Class for reading, manipulating and writing CSS. Unlike other CSS classes on CPAN this particular module
33 focuses on respecting the order of selectors while providing a common sense API through which to manipulate the
34 rules.
35  
36 Please note that while ordering is respected, the exact order of selectors may change. I.e. the rules
37 implied by the styles and their ordering will not change, but the actual ordering of the styles may shift around.
38 See the read method for more information.
39  
40 =cut
41  
42 BEGIN {
43 my $members = ['ordered','stylesheet','warns_as_errors','content_warnings','browser_specific_properties'];
44  
45 #generate all the getter/setter we need
46 foreach my $member (@{$members}) {
47 no strict 'refs';
48  
49 *{'_' . $member} = sub {
50 my ($self,$value) = @_;
51  
52 $self->_check_object();
53  
54 $self->{$member} = $value if defined($value);
55  
56 return $self->{$member};
57 }
58 }
59 }
60  
61  
62 =pod
63  
64 =head1 CONSTRUCTOR
65  
66 =over 4
67  
68 =item new ([ OPTIONS ])
69  
70 Instantiates the CSS::Simple object. Sets up class variables that are used during file parsing/processing.
71  
72 B<warns_as_errors> (optional). Boolean value to indicate whether fatal errors should occur during parse failures.
73  
74 B<browser_specific_properties> (optional). Boolean value to indicate whether browser specific properties should be processed.
75  
76 =back
77  
78 =cut
79  
80 sub new {
81 my ($proto, $params) = @_;
82  
83 my $class = ref($proto) || $proto;
84  
85 my $css = {};
86  
87 my $self = {
88 stylesheet => undef,
89 ordered => tie(%{$css}, 'Tie::IxHash'),
90 content_warnings => undef,
91 warns_as_errors => (defined($$params{warns_as_errors}) && $$params{warns_as_errors}) ? 1 : 0,
92 browser_specific_properties => (defined($$params{browser_specific_properties}) && $$params{browser_specific_properties}) ? 1 : 0
93 };
94  
95 bless $self, $class;
96 return $self;
97 }
98  
99 =head1 METHODS
100  
101 =cut
102  
103 =pod
104  
105 =over 4
106  
107 =item read_file( params )
108  
109 Opens and reads a CSS file, then subsequently performs the parsing of the CSS file
110 necessary for later manipulation.
111  
112 This method requires you to pass in a params hash that contains a
113 filename argument. For example:
114  
115 $self->read_file({filename => 'myfile.css'});
116  
117 =cut
118  
119 sub read_file {
120 my ($self,$params) = @_;
121  
122 $self->_check_object();
123  
124 unless ($params && $$params{filename}) {
125 croak "You must pass in hash params that contain a filename argument";
126 }
127  
128 open FILE, "<", $$params{filename} or croak $!;
129 my $css = do { local( $/ ) ; <FILE> } ;
130 close FILE;
131  
132 $self->read({css => $css});
133  
134 return();
135 }
136  
137 =pod
138  
139 =item read( params )
140  
141 Reads css data and parses it. The intermediate data is stored in class variables.
142  
143 Compound selectors (i.e. "a, span") are split apart during parsing and stored
144 separately, so the output of any given stylesheet may not match the output 100%, but the
145 rules themselves should apply as expected.
146  
147 Ordering of selectors may shift if the same selector is seen twice within the stylesheet.
148 The precendence for any given selector is the last time it was seen by the parser.
149  
150 This method requires you to pass in a params hash that contains scalar
151 css data. For example:
152  
153 $self->read({css => $css});
154  
155 =cut
156  
157 sub read {
158 my ($self,$params) = @_;
159  
160 $self->_check_object();
161  
162 $self->_content_warnings({}); # overwrite any existing warnings
163  
164 unless (exists $$params{css}) {
165 croak 'You must pass in hash params that contains the css data';
166 }
167  
168 if ($params && $$params{css}) {
169 # Flatten whitespace and remove /* comment */ style comments
170 my $string = $$params{css};
171 $string =~ tr/\n\t/ /;
172 $string =~ s!/\*.*?\*\/!!g;
173  
174 # Split into styles
175 foreach (grep { /\S/ } split /(?<=\})/, $string) {
176  
177 unless ( /^\s*([^{]+?)\s*\{(.*)\}\s*$/ ) {
178 $self->_report_warning({ info => "Invalid or unexpected style data '$_'" });
179 next;
180 }
181  
182 # Split in such a way as to support grouped styles
183 my $rule = $1;
184 my $props = $2;
185  
186 $rule =~ s/\s{2,}/ /g;
187  
188 # Split into properties
189 my $properties = {};
190 foreach ( grep { /\S/ } split /\;/, $props ) {
191  
192 # skip over browser specific properties unless specified in constructor
193 if (!$self->_browser_specific_properties() && (( /^\s*[*-_]/ ) || ( /\\/ ))) {
194 next;
195 }
196  
197 # check if properties are valid, reporting error as configured
198 unless ( /^\s*([\w._-]+)\s*:\s*(.*?)\s*$/ ) {
199 $self->_report_warning({ info => "Invalid or unexpected property '$_' in style '$rule'" });
200 next;
201 }
202  
203 #store the property for later
204 $$properties{lc $1} = $2;
205 }
206  
207 my @selectors = split /,/, $rule; # break the rule into the component selector(s)
208  
209 #apply the found rules to each selector
210 foreach my $selector (@selectors) {
211 $selector =~ s/^\s+|\s+$//g;
212 if ($self->check_selector({selector => $selector})) { #check if we already exist
213 my $old_properties = $self->get_properties({selector => $selector});
214 $self->delete_selector({selector => $selector});
215  
216 my %merged = (%$old_properties, %$properties);
217  
218 $self->add_selector({selector => $selector, properties => \%merged});
219 }
220 else {
221 #store the properties within this selector
222 $self->add_selector({selector => $selector, properties => $properties});
223 }
224 }
225 }
226 }
227 else {
228 $self->_report_warning({ info => 'No stylesheet data was found in the document'});
229 }
230  
231 return();
232 }
233  
234 =pod
235  
236 =item write_file()
237  
238 Write the parsed and manipulated CSS out to a file parameter
239  
240 This method requires you to pass in a params hash that contains a
241 filename argument. For example:
242  
243 $self->write_file({filename => 'myfile.css'});
244  
245 =cut
246  
247 sub write_file {
248 my ($self,$params) = @_;
249  
250 $self->_check_object();
251  
252 unless (exists $$params{filename}) {
253 croak "No filename specified for write operation";
254 }
255  
256 # Write the file
257 open( CSS, '>'. $$params{filename} ) or croak "Failed to open file '$$params{filename}' for writing: $!";
258 print CSS $self->write();
259 close( CSS );
260  
261 return();
262 }
263  
264 =pod
265  
266 =item write()
267  
268 Write the parsed and manipulated CSS out to a scalar and return it
269  
270 =cut
271  
272 sub write {
273 my ($self,$params) = @_;
274  
275 $self->_check_object();
276  
277 my $contents = '';
278  
279 foreach my $selector ( $self->_ordered()->Keys ) {
280  
281 #grab the properties that make up this particular selector
282 my $properties = $self->get_properties({selector => $selector});
283  
284 if (keys(%{$properties})) { # only output if the selector has properties
285 $contents .= "$selector {\n";
286 foreach my $property ( sort keys %{ $properties } ) {
287 $contents .= "\t" . lc($property) . ": ".$properties->{$property}. ";\n";
288 }
289 $contents .= "}\n";
290 }
291 }
292  
293 return $contents;
294 }
295  
296 =pod
297
298 =item content_warnings()
299
300 Return back any warnings thrown while parsing a given block of css
301  
302 Note: content warnings are initialized at read time. In order to
303 receive back content feedback you must perform read() first.
304  
305 =cut
306  
307 sub content_warnings {
308 my ($self,$params) = @_;
309  
310 $self->_check_object();
311  
312 my @content_warnings = keys %{$self->_content_warnings()};
313  
314 return \@content_warnings;
315 }
316  
317 ####################################################################
318 # #
319 # The following are all get/set methods for manipulating the #
320 # stored stylesheet #
321 # #
322 # Provides a nicer interface than dealing with TIE #
323 # #
324 ####################################################################
325  
326 =pod
327  
328 =item get_selectors( params )
329  
330 Get an array of selectors that represents an inclusive list of all selectors
331 stored.
332  
333 =cut
334  
335 sub get_selectors {
336 my ($self,$params) = @_;
337  
338 $self->_check_object();
339  
340 return($self->_ordered()->Keys());
341 }
342  
343 =pod
344  
345 =item get_properties( params )
346  
347 Get a hash that represents the various properties for this particular selector
348  
349 This method requires you to pass in a params hash that contains scalar
350 css data. For example:
351  
352 $self->get_properties({selector => '.foo'});
353  
354 =cut
355  
356 sub get_properties {
357 my ($self,$params) = @_;
358  
359 $self->_check_object();
360  
361 return($self->_ordered()->FETCH($$params{selector}));
362 }
363  
364 =pod
365  
366 =item check_selector( params )
367  
368 Determine if a selector exists within the stored rulesets
369  
370 This method requires you to pass in a params hash that contains scalar
371 css data. For example:
372  
373 $self->check_selector({selector => '.foo'});
374  
375 =cut
376  
377 sub check_selector {
378 my ($self,$params) = @_;
379  
380 $self->_check_object();
381  
382 return($self->_ordered()->EXISTS($$params{selector}));
383 }
384  
385 =pod
386  
387 =item modify_selector( params )
388  
389 Modify an existing selector
390
391 Modifying a selector maintains the existing selectivity of the rule with relation to the
392 original stylesheet. If you want to ignore that selectivity, delete the element and re-add
393 it to CSS::Simple
394  
395 This method requires you to pass in a params hash that contains scalar
396 css data. For example:
397  
398 $self->modify_selector({selector => '.foo', new_selector => '.bar' });
399  
400 =cut
401  
402 sub modify_selector {
403 my ($self,$params) = @_;
404  
405 $self->_check_object();
406  
407 #if the selector is found, replace the selector
408 if ($self->check_selector({selector => $$params{selector}})) {
409 #we probably want to be doing this explicitely
410 my ($index) = $self->_ordered()->Indices( $$params{selector} );
411 my $properties = $self->get_properties({selector => $$params{selector}});
412  
413 $self->_ordered()->Replace($index,$properties,$$params{new_selector});
414 }
415 #otherwise new element, stick it onto the end of the rulesets
416 else {
417 #add a selector, there was nothing to replace
418 $self->add_selector({selector => $$params{new_selector}, properties => {}});
419 }
420  
421 return();
422 }
423  
424 =pod
425  
426 =item add_selector( params )
427  
428 Add a selector and associated properties to the stored rulesets
429  
430 In the event that this particular ruleset already exists, invoking this method will
431 simply replace the item. This is important - if you are modifying an existing rule
432 using this method than the previously existing selectivity will continue to persist.
433 Delete the selector first if you want to ignore the previous selectivity.
434  
435 This method requires you to pass in a params hash that contains scalar
436 css data. For example:
437  
438 $self->add_selector({selector => '.foo', properties => {color => 'red' }});
439  
440 =cut
441  
442 sub add_selector {
443 my ($self,$params) = @_;
444  
445 $self->_check_object();
446  
447 #if we existed already, invoke REPLACE to preserve selectivity
448 if ($self->check_selector({selector => $$params{selector}})) {
449 #we probably want to be doing this explicitely
450 my ($index) = $self->_ordered()->Indices( $$params{selector} );
451  
452 $self->_ordered()->Replace($index,dclone($$params{properties}));
453 }
454 #new element, stick it onto the end of the rulesets
455 else {
456 #store the properties
457 $self->_ordered()->STORE($$params{selector},dclone($$params{properties}));
458 }
459  
460 return();
461 }
462  
463 =pod
464  
465 =item add_properties( params )
466  
467 Add properties to an existing selector, preserving the selectivity of the original declaration.
468  
469 In the event that this method is invoked with a selector that doesn't exist then the call
470 is just translated to an add_selector call, thus creating the rule at the end of the ruleset.
471  
472 This method requires you to pass in a params hash that contains scalar
473 css data. For example:
474  
475 $self->add_properties({selector => '.foo', properties => {color => 'red' }});
476  
477 =cut
478  
479 sub add_properties {
480 my ($self,$params) = @_;
481  
482 $self->_check_object();
483  
484 #If selector exists already, merge properties into this selector
485 if ($self->check_selector({selector => $$params{selector}})) {
486 #merge property sets together
487 my %properties = (%{$self->get_properties({selector => $$params{selector}})}, %{$$params{properties}});
488  
489 #overwrite the existing properties for this selector with the new hybrid style
490 $self->add_selector({selector => $$params{selector}, properties => \%properties});
491 }
492 #otherwise add it wholesale
493 else {
494 $self->add_selector({selector => $$params{selector}, properties => $$params{properties}});
495 }
496  
497 return();
498 }
499  
500 =pod
501  
502 =item delete_selector( params )
503  
504 Delete a selector from the ruleset
505  
506 This method requires you to pass in a params hash that contains scalar
507 css data. For example:
508  
509 $self->delete_selector({selector => '.foo' });
510  
511 =cut
512  
513 sub delete_selector {
514 my ($self,$params) = @_;
515  
516 $self->_check_object();
517  
518 #store the properties, potentially overwriting properties that were there
519 $self->_ordered()->DELETE($$params{selector});
520  
521 return();
522 }
523  
524 =pod
525  
526 =item delete_property( params )
527  
528 Delete a property from a specific selectors rules
529  
530 This method requires you to pass in a params hash that contains scalar
531 css data. For example:
532  
533 $self->delete_property({selector => '.foo', property => 'color' });
534  
535 =back
536  
537 =cut
538  
539 sub delete_property {
540 my ($self,$params) = @_;
541  
542 $self->_check_object();
543  
544 #get the properties so we can remove the requested property from the hash
545 my $properties = $self->get_properties({selector => $$params{selector}});
546  
547 delete $$properties{$$params{property}};
548  
549 $self->add_selector({selector => $$params{selector}, properties => $properties});
550  
551 return();
552 }
553
554 ####################################################################
555 # #
556 # The following are all private methods and are not for normal use #
557 # I am working to finalize the get/set methods to make them public #
558 # #
559 ####################################################################
560  
561 sub _check_object {
562 my ($self,$params) = @_;
563  
564 unless ($self && ref $self) {
565 croak "You must instantiate this class in order to properly use it";
566 }
567  
568 return();
569 }
570  
571 sub _report_warning {
572 my ($self,$params) = @_;
573  
574 $self->_check_object();
575  
576 if ($self->{warns_as_errors}) {
577 croak $$params{info};
578 }
579 else {
580 my $warnings = $self->_content_warnings();
581 $$warnings{$$params{info}} = 1;
582 }
583  
584 return();
585 }
586  
587 1;
588  
589 =pod
590  
591 =head1 Sponsor
592  
593 This code has been developed under sponsorship of MailerMailer LLC, http://www.mailermailer.com/
594  
595 =head1 AUTHOR
596  
597 Kevin Kamel <C<kamelkev@mailermailer.com>>
598  
599 =head1 ATTRIBUTION
600  
601 This module is directly based off of Adam Kennedy's <adamk@cpan.org> CSS::Tiny module.
602  
603 This particular version differs in terms of interface and the ultimate ordering of the CSS.
604  
605 =head1 LICENSE
606  
607 This module is a derived version of Adam Kennedy's CSS::Tiny Module.
608  
609 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
610  
611 The full text of the license can be found in the LICENSE file included with this module.
612  
613 =cut