blib/lib/CSS/Watcher/Parser.pm untested

filter: Statementstmt 0.0% 0 / 49 Branchbran 0.0% 0 / 18 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 78 SCAR 47.0
CC
10
Cov
0%
_parse_css
110.0
new
2.0
parse_css
2.0
CRAP 110.0
1 package CSS::Watcher::Parser;
2  
3 use strict;
4 use warnings;
5  
6 use Carp;
7 use Log::Log4perl qw(:easy);
8 use CSS::Selector::Parser qw/parse_selector/;
9  
10 my $nested; # regexp for "{ }"
11 $nested = qr/
12 \{
13 (
14 [^{}]
15 |
16 (??{ $nested })
17 )*
18 \}
19 /x;
20  
21 sub new {
22 my $class = shift;
23 return bless ({}, $class);
24 }
25  
26 sub parse_css {
27 my $self = shift;
28 my $source = shift;
29  
30 my %classes;
31 my %ids;
32  
33 $self->_parse_css($source, \%classes, \%ids);
34
35 return (\%classes, \%ids);
36 }
37  
38 sub _parse_css {
39 my $self = shift;
40 my ($source, $classes, $ids) = @_;
41  
42 $source =~s|/\*.*?\*/||gs; # remove comments
43  
44 while ($source =~ m/(.*?)($nested)/gs) {
45 my ($selector, $selector_body) = ($1, $2);
46  
47 if ($selector =~/\s*\@media/s) {
48 if ($selector_body =~m /\{(.+)\}/s) {
49 $self->_parse_css($1, $classes, $ids);
50 }
51 next;
52 } elsif ($selector =~/\s*\@/s) {
53 # ignore @keyframes, etc @..
54 next;
55 }
56 eval {
57 foreach (parse_selector($selector)) {
58 next unless (ref $_ eq 'ARRAY');
59 foreach my $rule (@{$_}) {
60 if (exists $rule->{class}) {
61 # Bug, selector for .foo.bar return class foo.bar
62 # so split this selector by "."
63 foreach my $classname (split /\./, $rule->{class}) {
64 $classes->{
65 exists ($rule->{element}) ? $rule->{element} : "global"
66 }{ $classname }++;
67 }
68 }
69 if (exists $rule->{id}) {
70 $ids->{
71 exists ($rule->{element}) ? $rule->{element} : "global"
72 }{ $rule->{id} }++;
73 }
74 }
75 }
76 };
77 if ($@) {
78 # log selector parse failure
79 ERROR "Can't parse selector: \"$selector\"";
80 }
81 }
82 }
83  
84  
85 1;
86  
87 __END__
88  
89 =head1 NAME
90  
91 CSS::Watcher::Parser - Extract classes, ids from css
92  
93 =head1 SYNOPSIS
94  
95 use CSS::Watcher::Parser;
96 my $parser = CSS::Watcher::Parser->new()
97 my ($hclasses, $hids) = parser->parse_css ('.foo, #myid {color: red}');
98  
99 =head1 DESCRIPTION
100  
101 Simple parser of css files
102  
103 =head1 AUTHOR
104  
105 Olexandr Sydorchuk (olexandr.syd@gmail.com)
106  
107 =head1 COPYRIGHT AND LICENSE
108  
109 Copyright (C) 2014 by Olexandr Sydorchuk
110  
111 This program is free software; you can redistribute it and/or modify
112 it under the same terms as Perl itself, either Perl version 5.8.2 or,
113 at your option, any later version of Perl 5 you may have available.
114  
115 =cut