blib/lib/Evented/Configuration.pm untested

filter: Statementstmt 0.0% 0 / 145 Branchbran 0.0% 0 / 50 Conditioncond 0.0% 0 / 32 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 266 CC 26 SCAR 43.6
CC
26
Cov
0%
parse_config
240.0
_value_to_perl
12.0
new
6.0
CRAP 78.5
1 # Copyright (c) 2017, Mitchell Cooper
2 #
3 # Evented::Configuration:
4 #
5 # Events:
6 #
7 # each time a configuration value changes, change:blocktype/blockname:key is fired. For unnamed
8 # blocks, the block type is omitted. For example, a block named 'chocolate' of type
9 # 'cookies' would fire the event 'change:cookies/chocolate:favorite' when its 'favorite' key
10 # is changed. An unnamed block of type 'fudge' would fire the event 'change:fudge:peanutbutter'
11 # when its 'peanutbutter' key is changed.
12 #
13 # If a value never existed, new values fire change events as well. If you want your
14 # listeners to respond to certain values even when the configuration is first loaded,
15 # simply add the listeners before calling parse_config(). If you wish for the opposite
16 # behavior, do the opposite: apply the handlers after calling parse_config().
17 #
18 # All events are fired with:
19 # $old - first argument, the former value of this configuration key.
20 # $new - second argument, the new value of this configuration key.
21 #
22 # The easiest way to attach configuration change events is with the on_change() method.
23 # It is also the safest way because event names could possibly change in the future.
24 # For example:
25 #
26 # $conf->on_change(['someBlockType', 'someBlockName'], 'key', sub {
27 # my ($event, $old, $new) = @_;
28 # ...
29 # });
30 #
31 # You can also add additional hash arguments for ->register_callback() to the end.
32 #
33  
34 package Evented::Configuration;
35  
36 use warnings;
37 use strict;
38 use utf8;
39 use 5.010;
40 use parent 'Evented::Object';
41 use Scalar::Util qw(blessed);
42 use File::Basename qw(dirname);
43  
44 our $VERSION = '4.01';
45  
46 my ($true, $false) = (1, 0);
47 sub on () { state $on = bless \$true, 'Evented::Configuration::Boolean' }
48 sub off () { state $off = bless \$false, 'Evented::Configuration::Boolean' }
49  
50 # create a new configuration instance.
51 sub new {
52 my ($class, %opts) = (shift, @_);
53  
54 # if we have no defined conffile, we must give up now.
55 return if !defined $opts{conffile};
56  
57 # if 'hashref' is provided, use it.
58 $opts{conf} = $opts{hashref} || $opts{conf} || {};
59  
60 # return the new configuration object.
61 return bless \%opts, $class;
62  
63 }
64  
65 # parse the configuration file.
66 sub parse_config {
67 my ($conf) = @_;
68 my $file = $conf->{conffile};
69  
70 # open for reading
71 my $fh;
72 if (not open $fh, '<', $file) {
73 my $msg = "$file: Failed to open for reading: $!";
74 return (undef, $msg);
75 }
76  
77 my ($block, $name, @new_conf);
78 my $err = sub {
79 my ($i, $msg) = @_;
80 $msg = "$file:$i: $msg; parsing aborted";
81 close $fh;
82 return wantarray ? (undef, $msg) : undef;
83 };
84  
85 while (<$fh>) {
86 my ($key, $val, $val_changed_maybe);
87  
88 # remove comments and excess whitespace.
89 chomp;
90 s/^\s*//;
91 s/\s*(#.*)$//;
92 next unless length;
93  
94 # a block with a name.
95 if (m/^\[(.+?):(.+)\]$/) {
96 $block = trim($1);
97 $name = trim($2);
98
99 # include
100 if ($block eq 'include') {
101 my $sfile = dirname($file)."/$name";
102 my $sconf = __PACKAGE__->new(conffile => $sfile);
103
104 # error?
105 my ($ok, $err) = $sconf->parse_config;
106 return $err->($., "include error: $err") if !$ok;
107
108 # inject
109 for my $sblock (keys %{ $sconf->{conf} }) {
110 for my $sname (keys %{ $sconf->{conf}{$sblock} }) {
111 for my $skey (keys %{ $sconf->{conf}{$sblock}{$sname} }) {
112 my $old = $conf->{conf}{$sblock}{$sname}{$skey};
113 my $val = $sconf->{conf}{$sblock}{$sname}{$skey};
114 push @new_conf, $sblock, $sname, $skey, $old, $val;
115 }}}
116 }
117 }
118  
119 # a nameless block.
120 elsif (m/^\[(.+)\]$/) {
121 $block = 'section';
122 $name = trim($1);
123 }
124  
125 # a boolean key.
126 elsif (m/^([\w:]+)$/) {
127 $key = trim($1);
128 $val = on;
129 $val_changed_maybe++;
130  
131 # no block is set
132 return $err->($., "Stray key '$key'")
133 if !length $block;
134 }
135  
136 # a key and value.
137 elsif (m/^([\w:]+)\s*[:=]+(.+)$/) {
138 $key = trim($1);
139 my $val_str = trim($2);
140 $val_changed_maybe++;
141  
142 # no block is set
143 return $err->($., "Stray pair '$key = $val_str'")
144 if !length $block;
145  
146 $val = eval $val_str;
147  
148 # error occured in eval
149 return $err->($., "Invalid value '$val_str': $@")
150 if $@;
151 }
152  
153 # I don't know how to handle this.
154 else {
155 return $err->($., "Syntax error: '$_'");
156 }
157  
158 # something may have changed.
159 next unless $val_changed_maybe;
160  
161 # fetch the old value and set the new value.
162 my $old = $conf->{conf}{$block}{$name}{$key};
163  
164 # push the events.
165 push @new_conf, $block, $name, $key, $old, $val;
166 }
167  
168 # we parsed the entire file successfully, so commit the changes.
169 my @new_events;
170 while (my @set = splice @new_conf, 0, 5) {
171 push @new_events, $conf->_get_events(@set);
172 $conf->{conf}{ $set[0] }{ $set[1] }{ $set[2] } = $set[4];
173 }
174  
175 # now fire change events.
176 $conf->fire_events_together(@new_events) if @new_events;
177  
178 close $fh;
179 return 1;
180 }
181  
182 # returns true if the block is found.
183 # supports unnamed blocks by get(block, key)
184 # supports named blocks by get([block type, block name], key)
185 sub has_block {
186 my ($conf, $block) = @_;
187 my ($block_type, $block_name) = _block_parts($block);
188 return 1 if $conf->{conf}{$block_type}{$block_name};
189 }
190  
191 # returns a list of all the names of a block type.
192 # for example, names_of_block('listen') might return ('0.0.0.0', '127.0.0.1')
193 sub names_of_block {
194 my ($conf, $block_type) = @_;
195 return keys %{ $conf->{conf}{$block_type} };
196 }
197  
198 # returns a list of all the keys in a block.
199 # for example, keys_of_block('modules') would return an array of every module.
200 # accepts block type or [block type, block name] as well.
201 sub keys_of_block {
202 my ($conf, $block) = @_;
203 my ($block_type, $block_name) = _block_parts($block);
204  
205 # not a hashref. return empty list.
206 my $hashref = $conf->{conf}{$block_type}{$block_name};
207 if (!$hashref || !ref $hashref || ref $hashref ne 'HASH') {
208 return;
209 }
210  
211 return keys %$hashref;
212 }
213  
214 # returns a list of all the values in a block.
215 # accepts block type or [block type, block name] as well.
216 sub values_of_block {
217 my ($conf, $block) = @_;
218 my ($block_type, $block_name) = _block_parts($block);
219  
220 # not a hashref. return empty list.
221 my $hashref = $conf->{conf}{$block_type}{$block_name};
222 if (!$hashref || !ref $hashref || ref $hashref ne 'HASH') {
223 return;
224 }
225  
226 return map _value_to_perl($_), values %$hashref;
227 }
228  
229 # returns the key:value hash of a block.
230 # accepts block type or [block type, block name] as well.
231 sub hash_of_block {
232 my ($conf, $block) = @_;
233 my ($block_type, $block_name) = _block_parts($block);
234  
235 # not a hashref. return empty list.
236 my $hashref = $conf->{conf}{$block_type}{$block_name};
237 if (!$hashref || !ref $hashref || ref $hashref ne 'HASH') {
238 return;
239 }
240  
241 return map { $_ => _value_to_perl($hashref->{$_}) } keys %$hashref;
242 }
243  
244 # get a configuration value.
245 # supports unnamed blocks by get(block, key)
246 # supports named blocks by get([block type, block name], key)
247 sub get { _get(shift, 0, @_) }
248 sub _get {
249 my ($conf, $bool_objs, $block, $key) = @_;
250 my ($block_type, $block_name) = _block_parts($block);
251 my $res = $conf->{conf}{$block_type}{$block_name}{$key};
252 return $bool_objs ? $res : _value_to_perl($res);
253 }
254  
255 # remove leading and trailing whitespace.
256 sub trim {
257 my $string = shift;
258 $string =~ s/\s+$//;
259 $string =~ s/^\s+//;
260 return $string;
261 }
262  
263 # convert stored value to Perl representation.
264 sub _value_to_perl {
265 my ($val) = @_;
266 if (blessed $val && $val->isa('Evented::Configuration::Boolean')) {
267 return $$val ? 1 : undef;
268 }
269 return $val;
270 }
271  
272 # attach a configuration change listener.
273 # see notes at top of file for usage.
274 sub on_change {
275 my ($conf, $block, $key, $code, %opts) = @_;
276 my ($block_type, $block_name) = _block_parts($block);
277  
278 # determine the name of the event.
279 $block = $block_type eq 'section' ? $block_name : $block_type.q(/).$block_name;
280 my $event_name = "change:$block:$key";
281  
282 # register the event.
283 return $conf->register_event($event_name => $code, %opts);
284 }
285  
286 # get events for a change.
287 sub _get_events {
288 my ($conf, $block, $name, $key, $old, $val) = @_;
289 $old = _value_to_perl($old);
290 $val = _value_to_perl($val);
291  
292 # determine the name of the event.
293 my $eblock = $block eq 'section' ? $name : $block.q(/).$name;
294  
295 # return the events.
296 return (
297  
298 # change => sub { my ($blockref, $key, $old, $new) }
299 # change:namelessblock => sub { my ($key, $old, $new) }
300 # change:named/theName => sub { my ($key, $old, $new) }
301 # change:section:__ANY__ => sub { my ($the_type, $key, $old, $new) }
302 # change:named:__ANY__ => sub { my ($the_name, $key, $old, $new) }
303 # change:namelessblock:someKey => sub { my ($old, $new) }
304 # change:named/theName:someKey => sub { my ($old, $new) }
305  
306 [ change => [ $block, $name ], $key, $old, $val ],
307 [ "change:$eblock" => $key, $old, $val ],
308 [ "change:$block:__ANY__" => $name, $key, $old, $val ],
309 [ "change:$eblock:$key" => $old, $val ]
310  
311 );
312 }
313  
314 # handle 'unamed block' or [ 'block type', 'named block' ]
315 # returns a list (block type, block name)
316 sub _block_parts {
317 my $block = shift;
318 if (ref $block && ref $block eq 'ARRAY' && @$block >= 2) {
319 return @$block;
320 }
321 return ('section', $block);
322 }
323  
324 1;
325  
326 =head1 NAME
327  
328 B<Evented::Configuration> - an event-driven objective configuration class and parser for
329 Perl software built upon L<Evented::Object>.
330  
331 =head1 SYNOPSIS
332  
333 =head2 Example usage
334  
335 # create a new configuration instance.
336 my $conf = Evented::Configuration->new(conffile => 'etc/some.conf');
337  
338 # attach a callback to respond to changes of the user:age key.
339 $conf->on_change('user', 'name', sub {
340 my ($event, $old, $new) = @_;
341 say 'The user\'s age changed from ', $old || '(not born)', "to $new";
342 });
343  
344 # parse the configuration file.
345 $conf->parse_config();
346  
347 =head2 Example configuration file
348  
349 # some.conf file
350  
351 # Comments
352  
353 # Hello, I am a comment.
354 # I am also a comment.
355  
356 # Unnamed blocks
357  
358 [ someBlock ]
359  
360 someKey = "some string"
361 otherKey = 12
362 another = ['hello', 'there']
363 evenMore = ['a'..'z']
364  
365 # Named blocks
366  
367 [ cookies: sugar ]
368  
369 favorites = ['sugar cookie', 'snickerdoodle']
370  
371 [ cookies: chocolate ]
372  
373 favorites = ['chocolate macadamia nut', 'chocolate chip']
374  
375 =head1 DESCRIPTION
376  
377 As the name suggests, event firing is what makes Evented::Configuration unique in
378 comparison to other configuration classes.
379  
380 =head2 Blocks
381  
382 Evented::Configuration's configuration is block-styled, with all keys and values
383 associated with a block. Blocks can be "named," meaning there are several blocks of one
384 type with different names, or they can be "unnamed," meaning there is only one block of
385 that type.
386  
387 =head2 Objective
388  
389 Evented::Configuration's objective interface allows you to store nothing more than the
390 configuration object. Then, make the object accessible where you need it.
391  
392 =head2 Event-driven
393  
394 Evented::Configuration is based upon the Evented::Object framework, firing events each time
395 a configuration changes. This allows software to respond immediately to changes of user
396 settings, etc.
397  
398 =head2 Convenience
399  
400 Most configuration parsers spit out nothing more than a hash reference of keys and values.
401 Evented::Configuration instead supplies several convenient methods for fetching
402 configuration data.
403  
404 =head1 METHODS
405  
406 Evented::Configuration provides several convenient methods for fetching configuration
407 values.
408  
409 =head2 Evented::Configuration->new(%options)
410  
411 Creates a new instance of Evented::Configuration.
412  
413 my $conf = Evented::Configuration->new(conffile => 'etc/some.conf');
414  
415 B<Parameters>
416  
417 =over 4
418  
419 =item *
420  
421 B<options>: a hash of constructor options.
422  
423 =back
424  
425 B<%options - constructor options>
426  
427 =over 4
428  
429 =item *
430  
431 * B<conffile>: file location of a configuration file.
432  
433 =item *
434  
435 * B<hashref>: I<optional>, a hash ref to store configuration values in.
436  
437 =back
438  
439 =head2 $conf->parse_config()
440  
441 Parses the configuration file. Used also to rehash configuration.
442  
443 $conf->parse_config();
444  
445 =head2 $conf->get($block, $key)
446  
447 Fetches a single configuration value.
448  
449 my $value = $conf->get('unnamedBlock', 'someKey');
450 my $other = $conf->get(['blockType', 'namedBlock'], 'someKey');
451  
452 B<Parameters>
453  
454 =over 4
455  
456 =item *
457  
458 B<block>: for unnamed blocks, should be the string block type. for named blocks, should be
459 an array reference in the form of C<[block type, block name]>.
460  
461 =item *
462  
463 B<key>: the key of the configuration value being fetched.
464  
465 =back
466  
467 =head2 $conf->names_of_block($block_type)
468  
469 Returns an array of the names of all blocks of the specified type.
470  
471 foreach my $block_name ($conf->names_of_block('cookies')) {
472 print "name of this cookie block: $block_name\n";
473 }
474  
475 B<Parameters>
476  
477 =over 4
478  
479 =item *
480  
481 B<block_type>: the type of the named block.
482  
483 =back
484  
485 =head2 $conf->keys_of_block($block)
486  
487 Returns an array of all the keys in the specified block.
488  
489 foreach my $key ($conf->keys_of_block('someUnnamedBlock')) {
490 print "someUnnamedBlock unnamed block has key: $key\n";
491 }
492  
493 foreach my $key ($conf->keys_of_block('someNamedBlock', 'someName')) {
494 print "someNamedBlock:someName named block has key: $key\n";
495 }
496  
497 B<Parameters>
498  
499 =over 4
500  
501 =item *
502  
503 B<block>: for unnamed blocks, should be the string block type. for named blocks, should be
504 an array reference in the form of C<[block type, block name]>.
505  
506 =back
507  
508 =head2 $conf->on_change($block, $key, $code, %opts)
509  
510 Attaches an event listener for the configuration change event. This event will be fired
511 even if the value never existed. If you want a listener to be called the first time the
512 configuration is parsed, simply add the listener before calling C<-E<gt>parse_config()>.
513 Otherwise, add listeners later.
514  
515 # an example with an unnamed block
516 $conf->on_change('myUnnamedBlock', 'myKey', sub {
517 my ($event, $old, $new) = @_;
518 ...
519 });
520  
521 # an example with a name block.
522 $conf->on_change(['myNamedBlockType', 'myBlockName'], 'someKey', sub {
523 my ($event, $old, $new) = @_;
524 ...
525 });
526  
527 # an example with an unnamed block and ->register_event() options.
528 $conf->on_change('myUnnamedBlock', 'myKey', sub {
529 my ($event, $old, $new) = @_;
530 ...
531 }, priority => 100, name => 'myCallback');
532  
533 B<Parameters>
534  
535 =over 4
536  
537 =item *
538  
539 B<block>: for unnamed blocks, should be the string block type. for named blocks, should be
540 an array reference in the form of C<[block type, block name]>.
541  
542 =item *
543  
544 B<key>: the key of the configuration value being listened for.
545  
546 =item *
547  
548 B<code>: a code reference to be called when the value is changed.
549  
550 =item *
551  
552 B<opts>: I<optional>, a hash of any other options to be passed to Evented::Object's
553 C<-E<gt>register_event()>.
554  
555 =back
556  
557 =head1 EVENTS
558  
559 Evented::Configuration fires events when configuration values are changed.
560  
561 In any case, events are fired with arguments C<(old value, new value)>.
562  
563 Say you have an unnamed block of type C<myBlock>. If you changed the key C<myKey> in
564 C<myBlock>, Evented::Configuration would fire the event
565 C<change:myBlock:myKey>.
566  
567 Now assume you have a named block of type C<myBlock> with name C<myName>. If you changed
568 the key C<myKey> in C<myBlock:myName>, Evented::Configuration would fire event
569 C<change:myBlock/myName:myKey>.
570  
571 However, it is recommended that you use the C<-E<gt>on_change()> method rather than
572 directly attaching event callbacks. This will insure compatibility for later versions that
573 could possibly change the way events are fired.
574  
575 =head1 SEE ALSO
576  
577 =over 4
578  
579 =item *
580  
581 L<Evented::Object> - the event class that powers Evented::Configuration.
582  
583 =back
584  
585 =head1 AUTHOR
586  
587 L<Mitchell Cooper|https://github.com/cooper> <cooper@cpan.org>
588  
589 Copyright E<copy> 2014. Released under BSD license.
590  
591 =over 4
592  
593 =item *
594  
595 B<IRC channel>: L<irc.notroll.net #k|irc://irc.notroll.net/k>
596  
597 =item *
598  
599 B<Email>: cooper@cpan.org
600  
601 =item *
602  
603 B<CPAN>: L<COOPER|http://search.cpan.org/~cooper/>
604  
605 =item *
606  
607 B<GitHub>: L<cooper|https://github.com/cooper>
608  
609 =back
610  
611 Comments, complaints, and recommendations are accepted. IRC is my preferred communication
612 medium. Bugs may be reported on
613 L<RT|https://rt.cpan.org/Public/Dist/Display.html?Name=Evented-Configuration>.