1Config::Model::Value(3)User Contributed Perl DocumentatioCnonfig::Model::Value(3)
2
3
4
6 Config::Model::Value - Strongly typed configuration value
7
9 version 2.136
10
12 use Config::Model;
13
14 # define configuration tree object
15 my $model = Config::Model->new;
16 $model ->create_config_class (
17 name => "MyClass",
18
19 element => [
20
21 [qw/foo bar/] => {
22 type => 'leaf',
23 value_type => 'string',
24 description => 'foobar',
25 }
26 ,
27 country => {
28 type => 'leaf',
29 value_type => 'enum',
30 choice => [qw/France US/],
31 description => 'big countries',
32 }
33 ,
34 ],
35 ) ;
36
37 my $inst = $model->instance(root_class_name => 'MyClass' );
38
39 my $root = $inst->config_root ;
40
41 # put data
42 $root->load( steps => 'foo=FOO country=US' );
43
44 print $root->report ;
45 # foo = FOO
46 # DESCRIPTION: foobar
47 #
48 # country = US
49 # DESCRIPTION: big countries
50
52 This class provides a way to specify configuration value with the
53 following properties:
54
55 · Strongly typed scalar: the value can either be an enumerated type,
56 a boolean, a number, an integer or a string
57
58 · default parameter: a value can have a default value specified
59 during the construction. This default value is written in the
60 target configuration file. ("default" parameter)
61
62 · upstream default parameter: specifies a default value that is used
63 by the application when no information is provided in the
64 configuration file. This upstream_default value is not written in
65 the configuration files. Only the "fetch_standard" method returns
66 the builtin value. This parameter was previously referred as
67 "built_in" value. This may be used for audit purpose.
68 ("upstream_default" parameter)
69
70 · mandatory value: reading a mandatory value raises an exception if
71 the value is not specified and has no default value.
72
73 · dynamic change of property: A slave value can be registered to
74 another master value so that the properties of the slave value can
75 change according to the value of the master value. For instance,
76 paper size value can be 'letter' for country 'US' and 'A4' for
77 country 'France'.
78
79 · A reference to the Id of a hash of list element. In other word, the
80 value is an enumerated type where the possible values (choice) is
81 defined by the existing keys of a has element somewhere in the
82 tree. See "Value Reference".
83
85 There are several kind of default values. They depend on where these
86 values are defined (or found).
87
88 From the lowest default level to the "highest":
89
90 · "upstream_default": The value is known in the application, but is
91 not written in the configuration file.
92
93 · "layered": The value is known by the application through another
94 mean (e.g. an included configuration file), but is not written in
95 the configuration file.
96
97 · "default": The value is known by the model, but not by the
98 application. This value must be written in the configuration file.
99
100 · "computed": The value is computed from other configuration
101 elements. This value must be written in the configuration file.
102
103 · "preset": The value is not known by the model or by the
104 application. But it can be found by an automatic program and stored
105 while the configuration Config::Model::Instance is in preset mode
106
107 Then there is the value entered by the user. This overrides all kind of
108 "default" value.
109
110 The fetch_standard function returns the "highest" level of default
111 value, but does not return a custom value, i.e. a value entered by the
112 user.
113
115 Value object should not be created directly.
116
118 A leaf element must be declared with the following parameters:
119
120 value_type
121 Either "boolean", "enum", "integer", "number", "uniline", "string",
122 "file", "dir". Mandatory. See "Value types".
123
124 default
125 Specify the default value (optional)
126
127 upstream_default
128 Specify a built in default value (optional). I.e a value known by
129 the application which does not need to be written in the
130 configuration file.
131
132 write_as
133 Array ref. Reserved for boolean value. Specify how to write a
134 boolean value. Default is "[0,1]" which may not be the most
135 readable. "write_as" can be specified as "['false','true']" or
136 "['no','yes']".
137
138 compute
139 Computes a value according to a formula and other values. By
140 default a computed value cannot be set. See
141 Config::Model::ValueComputer for computed value declaration.
142
143 migrate_from
144 This is a special parameter to cater for smooth configuration
145 upgrade. This parameter can be used to copy the value of a
146 deprecated parameter to its replacement. See "Upgrade" for details.
147
148 convert => [uc | lc ]
149 When stored, the value is converted to uppercase (uc) or lowercase
150 (lc).
151
152 min Specify the minimum value (optional, only for integer, number)
153
154 max Specify the maximum value (optional, only for integer, number)
155
156 mandatory
157 Set to 1 if the configuration value must be set by the
158 configuration user (default: 0)
159
160 choice
161 Array ref of the possible value of an enum. Example :
162
163 choice => [ qw/foo bar/]
164
165 match
166 Perl regular expression. The value is matched with the regex to
167 assert its validity. Example "match => '^foo'" means that the
168 parameter value must begin with "foo". Valid only for "string" or
169 "uniline" values.
170
171 warn_if_match
172 Hash ref. Keys are made of Perl regular expression. The value can
173 specify a warning message (leave empty or undefined for a default
174 warning message) and instructions to fix the value. A warning is
175 issued when the value matches the passed regular expression. Valid
176 only for "string" or "uniline" values. The fix instructions is
177 evaluated when apply_fixes is called. $_ contains the value to fix.
178 $_ is stored as the new value once the instructions are done.
179 $self contains the value object. Use with care.
180
181 In the example below, any value matching 'foo' is converted in
182 uppercase:
183
184 warn_if_match => {
185 'foo' => {
186 fix => 'uc;',
187 msg => 'value $_ contains foo'
188 },
189 'BAR' => {
190 fix =>'lc;',
191 msg => 'value $_ contains BAR'
192 }
193 },
194
195 The tests are done in alphabetical order. In the example above,
196 "BAR" test is done before "foo" test.
197
198 $_ is substituted with the bad value when the message is generated.
199 $std_value is substituted with the standard value (i.e the preset,
200 computed or default value).
201
202 warn_unless_match
203 Hash ref like above. A warning is issued when the value does not
204 match the passed regular expression. Valid only for "string" or
205 "uniline" values.
206
207 warn
208 String. Issue a warning to user with the specified string any time
209 a value is set or read.
210
211 warn_if
212 A bit like "warn_if_match". The hash key is not a regexp but a
213 label to help users. The hash ref contains some Perl code that is
214 evaluated to perform the test. A warning is issued if the given
215 code returns true.
216
217 $_ contains the value to check. $self contains the
218 "Config::Model::Value" object (use with care).
219
220 The example below warns if value contains a number:
221
222 warn_if => {
223 warn_test => {
224 code => 'defined $_ && /\d/;',
225 msg => 'value $_ should not have numbers',
226 fix => 's/\d//g;'
227 }
228 },
229
230 Hash key is used in warning message when "msg" is not set:
231
232 warn_if => {
233 'should begin with foo' => {
234 code => 'defined && /^foo/'
235 }
236 }
237
238 Any operation or check on file must be done with "file" sub
239 (otherwise tests will break). This sub returns a Path::Tiny object
240 that can be used to perform checks. For instance:
241
242 warn_if => {
243 warn_test => {
244 code => 'not file($_)->exists',
245 msg => 'file $_ should exist'
246 }
247
248 warn_unless
249 Like "warn_if", but issue a warning when the given "code" returns
250 false.
251
252 The example below warns unless the value points to an existing
253 directory:
254
255 warn_unless => {
256 'missing dir' => {
257 code => '-d',
258 fix => "system(mkdir $_);" }
259 }
260
261 assert
262 Like "warn_if". Except that returned value triggers an error when
263 the given code returns false:
264
265 assert => {
266 test_nb => {
267 code => 'defined $_ && /\d/;',
268 msg => 'should not have numbers',
269 fix => 's/\d//g;'
270 }
271 },
272
273 hash key can also be used to generate error message when "msg"
274 parameter is not set.
275
276 grammar
277 Setup a Parse::RecDescent grammar to perform validation.
278
279 If the grammar does not start with a "check" rule (i.e does not
280 start with "check: "), the first line of the grammar is modified to
281 add "check" rule and this rules is set up so the entire value must
282 match the passed grammar.
283
284 I.e. the grammar:
285
286 token (oper token)(s?)
287 oper: 'and' | 'or'
288 token: 'Apache' | 'CC-BY' | 'Perl'
289
290 is changed to
291
292 check: token (oper token)(s?) /^\Z/ {$return = 1;}
293 oper: 'and' | 'or'
294 token: 'Apache' | 'CC-BY' | 'Perl'
295
296 The rule is called with Value object and a string reference. So, in
297 the actions you may need to define, you can call the value object
298 as $arg[0], store error message in "${$arg[1]}}" and store warnings
299 in "${$arg[2]}}".
300
301 replace
302 Hash ref. Used for enum to substitute one value with another. This
303 parameter must be used to enable user to upgrade a configuration
304 with obsolete values. For instance, if the value "foo" is obsolete
305 and replaced by "foo_better", you must declare:
306
307 replace => { foo => 'foo_better' }
308
309 The hash key can also be a regular expression for wider range
310 replacement. The regexp must match the whole value:
311
312 replace => ( 'foo.*' => 'better_foo' }
313
314 In this case, a value is replaced by "better_foo" when the
315 "/^foo.*$/" regexp matches.
316
317 replace_follow
318 Path specifying a hash of value element in the configuration tree.
319 The hash if used in a way similar to the "replace" parameter. In
320 this case, the replacement is not coded in the model but specified
321 by the configuration.
322
323 refer_to
324 Specify a path to an id element used as a reference. See Value
325 Reference for details.
326
327 computed_refer_to
328 Specify a path to an id element used as a computed reference. See
329 "Value Reference" for details.
330
331 warp
332 See section below: "Warp: dynamic value configuration".
333
334 help
335 You may provide detailed description on possible values with a hash
336 ref. Example:
337
338 help => { oui => "French for 'yes'", non => "French for 'no'"}
339
340 The key of help is used as a regular expression to find the help
341 text applicable to a value. These regexp are tried from the longest
342 to the shortest and are matched from the beginning of the string.
343 The key ""."" or "".*"" are fallback used last.
344
345 For instance:
346
347 help => {
348 'foobar' => 'help for values matching /^foobar/',
349 'foo' => 'help for values matching /^foo/ but not /^foobar/ (used above)',
350 '.' => 'help for all other values'
351 }
352
353 Value types
354 This modules can check several value types:
355
356 "boolean"
357 Accepts values 1 or 0, "yes" or "no", "true" or "false", and empty
358 string. The value read back is always 1 or 0.
359
360 "enum"
361 Enum choices must be specified by the "choice" parameter.
362
363 "integer"
364 Enable positive or negative integer
365
366 "number"
367 The value can be a decimal number
368
369 "uniline"
370 A one line string. I.e without "\n" in it.
371
372 "string"
373 Actually, no check is performed with this type.
374
375 "reference"
376 Like an "enum" where the possible values (aka choice) is defined by
377 another location if the configuration tree. See "Value Reference".
378
379 "file"
380 A file name or path. A warning is issued if the file does not
381 exists (or is a directory)
382
383 "dir"
384 A directory name or path. A warning is issued if the directory does
385 not exists (or is a plain file)
386
388 The Warp functionality enable a "Value" object to change its properties
389 (i.e. default value or its type) dynamically according to the value of
390 another "Value" object locate elsewhere in the configuration tree. (See
391 Config::Model::Warper for an explanation on warp mechanism).
392
393 For instance if you declare 2 "Value" element this way:
394
395 $model ->create_config_class (
396 name => "TV_config_class",
397 element => [
398 country => {
399 type => 'leaf',
400 value_type => 'enum',
401 choice => [qw/US Europe Japan/]
402 } ,
403 tv_standard => { # this example is getting old...
404 type => 'leaf',
405 value_type => 'enum',
406 choice => [ qw/PAL NTSC SECAM/ ]
407 warp => {
408 follow => {
409 # this points to the warp master
410 c => '- country'
411 },
412 rules => {
413 '$c eq "US"' => {
414 default => 'NTSC'
415 },
416 '$c eq "France"' => {
417 default => 'SECAM'
418 },
419 '$c eq "Japan"' => {
420 default => 'NTSC'
421 },
422 '$c eq "Europe"' => {
423 default => 'PAL'
424 },
425 }
426 }
427 } ,
428 ]
429 );
430
431 Setting "country" element to "US" means that "tv_standard" has a
432 default value set to "NTSC" by the warp mechanism.
433
434 Likewise, the warp mechanism enables you to dynamically change the
435 possible values of an enum element:
436
437 state => {
438 type => 'leaf',
439 value_type => 'enum', # example is admittedly silly
440 warp => {
441 follow => {
442 c => '- country'
443 },
444 rules => {
445 '$c eq "US"' => {
446 choice => ['Kansas', 'Texas' ]
447 },
448 '$c eq "Europe"' => {
449 choice => ['France', 'Spain' ]
450 },
451 '$c eq "Japan"' => {
452 choice => ['Honshu', 'Hokkaido' ]
453 }
454 }
455 }
456 }
457
458 Cascaded warping
459 Warping value can be cascaded: "A" can be warped by "B" which can be
460 warped by "C". But this feature should be avoided since it can lead to
461 a model very hard to debug. Bear in mind that:
462
463 · Warp loops are not detected and end up in "deep recursion
464 subroutine" failures.
465
466 · avoid "diamond" shaped warp dependencies: the results depends on
467 the order of the warp algorithm which can be unpredictable in this
468 case
469
470 · The keys declared in the warp rules ("US", "Europe" and "Japan" in
471 the example above) cannot be checked at start time against the warp
472 master "Value". So a wrong warp rule key is silently ignored during
473 start up and fails at run time.
474
476 To set up an enumerated value where the possible choice depends on the
477 key of a Config::Model::AnyId object, you must:
478
479 · Set "value_type" to "reference".
480
481 · Specify the "refer_to" or "computed_refer_to" parameter. See
482 refer_to parameter.
483
484 In this case, a "IdElementReference" object is created to handle the
485 relation between this value object and the referred Id. See
486 Config::Model::IdElementReference for details.
487
489 The following methods returns the current value of the parameter of the
490 value object (as declared in the model unless they were warped):
491
492 min
493 max
494 mandatory
495 choice
496 convert
497 value_type
498 default
499 upstream_default
500 index_value
501 element_name
502
503 name
504 Returns the object name.
505
506 get_type
507 Returns "leaf".
508
509 can_store
510 Returns true if the value object can be assigned to. Return 0 for a
511 read-only value (i.e. a computed value with no override allowed).
512
513 get_choice
514 Query legal values (only for enum types). Return an array (possibly
515 empty).
516
517 get_help
518 With a parameter, returns the help string applicable to the passed
519 value or undef.
520
521 Without parameter returns a hash ref that contains all the help
522 strings.
523
524 error_msg
525 Returns the error messages of this object (if any)
526
527 warning_msg
528 Returns warning concerning this value. Returns a list in list context
529 and a string in scalar context.
530
531 check_value
532 Parameters: "( value )"
533
534 Check the consistency of the value.
535
536 "check_value" also accepts named parameters:
537
538 value
539 quiet
540 When non null, check does not try to get extra information from the
541 tree. This is required in some cases to avoid loops in check,
542 get_info, get_warp_info, re-check ...
543
544 In scalar context, return 0 or 1.
545
546 In array context, return an empty array when no error was found. In
547 case of errors, returns an array of error strings that should be shown
548 to the user.
549
550 has_fixes
551 Returns the number of fixes that can be applied to the current value.
552
553 apply_fixes
554 Applies the fixes to suppress the current warnings.
555
556 check
557 Parameters: "( [ value => foo ] )"
558
559 Like "check_value".
560
561 Also displays warnings on STDOUT unless "silent" parameter is set to 1.
562 In this case,user is expected to retrieve them with "warning_msg".
563
564 Without "value" argument, this method checks the value currently
565 stored.
566
568 store
569 Parameters: "( $value )" or "value => ..., check => yes|no|skip ),
570 silent => 0|1"
571
572 Store value in leaf element. "check" parameter can be used to skip
573 validation check (default ies 'yes'). "silent" cane be used to
574 suppress warnings.
575
576 Optional "callback" is now deprecated.
577
578 clear
579 Clear the stored value. Further read returns the default value (or
580 computed or migrated value).
581
582 load_data
583 Parameters: "( $value )"
584
585 Load scalar data. Data is forwarded to "store".
586
587 Called with "load_data" or "load_data" or with the same parameters are
588 "store" method.
589
590 fetch_custom
591 Returns the stored value if this value is different from a standard
592 setting or built in setting. In other words, returns undef if the
593 stored value is identical to the default value or the computed value or
594 the built in value.
595
596 fetch_standard
597 Returns the standard value as defined by the configuration model. The
598 standard value can be either a preset value, a layered value, a
599 computed value, a default value or a built-in default value.
600
601 has_data
602 Return true if the value contains information different from default or
603 upstream default value.
604
605 fetch
606 Check and fetch value from leaf element. The method can have one
607 parameter (the fetch mode) or several pairs:
608
609 mode
610 Whether to fetch default, custom, etc value. See below for details
611
612 check
613 Whether to check if the value is valid or not before returning it.
614 Default is 'yes'. Possible value are
615
616 yes Perform check and raise an exception for bad values
617
618 skip
619 Perform check and return undef for bad values. A warning is
620 issued when a bad value is skipped. Set "check" to "no" to
621 avoid warnings.
622
623 no Do not check and return values even if bad
624
625 silent
626 When set to 1, warning are not displayed on STDOUT. User is
627 expected to read warnings with warning_msg method.
628
629 According to the "mode" parameter, this method returns either:
630
631 empty mode parameter (default)
632 Value entered by user or default value if the value is different
633 from upstream_default or layered value. Typically this value is
634 written in a configuration file.
635
636 backend
637 Alias for default mode.
638
639 custom
640 The value entered by the user (if different from built in, preset,
641 computed or default value)
642
643 user
644 The value most useful to user: the value that is used by the
645 application.
646
647 preset
648 The value entered in preset mode
649
650 standard
651 The preset or computed or default or built in value.
652
653 default
654 The default value (defined by the configuration model)
655
656 layered
657 The value found in included files (treated in layered mode: values
658 specified there are handled as upstream default values). E.g. like
659 in multistrap config.
660
661 upstream_default
662 The upstream_default value. (defined by the configuration model)
663
664 non_upstream_default
665 The custom or preset or computed or default value. Returns undef if
666 either of this value is identical to the upstream_default value.
667 This feature is useful to reduce data to write in configuration
668 file.
669
670 allow_undef
671 With this mode, "fetch()" returns undef for mandatory values.
672 Normally, trying to fetch an undefined mandatory value leads to an
673 exception.
674
675 user_value
676 Returns the value entered by the user. Does not use the default or
677 computed value. Returns undef unless a value was actually stored.
678
679 fetch_preset
680 Returns the value entered in preset mode. Does not use the default or
681 computed value. Returns undef unless a value was actually stored in
682 preset mode.
683
684 clear_preset
685 Delete the preset value. (Even out of preset mode). Returns true if
686 other data are still stored in the value (layered or user data).
687 Returns false otherwise.
688
689 fetch_layered
690 Returns the value entered in layered mode. Does not use the default or
691 computed value. Returns undef unless a value was actually stored in
692 layered mode.
693
694 clear_layered
695 Delete the layered value. (Even out of layered mode). Returns true if
696 other data are still stored in the value (layered or user data).
697 Returns false otherwise.
698
699 get( path => ..., mode => ... , check => ... )
700 Get a value from a directory like path.
701
702 set( path , value )
703 Set a value from a directory like path.
704
706 Number with min and max values
707 bounded_number => {
708 type => 'leaf',
709 value_type => 'number',
710 min => 1,
711 max => 4,
712 },
713
714 Mandatory value
715 mandatory_string => {
716 type => 'leaf',
717 value_type => 'string',
718 mandatory => 1,
719 },
720
721 mandatory_boolean => {
722 type => 'leaf',
723 value_type => 'boolean',
724 mandatory => 1,
725 },
726
727 Enum with help associated with each value
728 Note that the help specification is optional.
729
730 enum_with_help => {
731 type => 'leaf',
732 value_type => 'enum',
733 choice => [qw/a b c/],
734 help => {
735 a => 'a help'
736 }
737 },
738
739 Migrate old obsolete enum value
740 Legacy values "a1", "c1" and "foo/.*" are replaced with "a", "c" and
741 "foo/".
742
743 with_replace => {
744 type => 'leaf',
745 value_type => 'enum',
746 choice => [qw/a b c/],
747 replace => {
748 a1 => 'a',
749 c1 => 'c',
750 'foo/.*' => 'foo',
751 },
752 },
753
754 Enforce value to match a regexp
755 An exception is triggered when the value does not match the "match"
756 regular expression.
757
758 match => {
759 type => 'leaf',
760 value_type => 'string',
761 match => '^foo\d{2}$',
762 },
763
764 Enforce value to match a Parse::RecDescent grammar
765 match_with_parse_recdescent => {
766 type => 'leaf',
767 value_type => 'string',
768 grammar => q{
769 token (oper token)(s?)
770 oper: 'and' | 'or'
771 token: 'Apache' | 'CC-BY' | 'Perl'
772 },
773 },
774
775 Issue a warning if a value matches a regexp
776 Issue a warning if the string contains upper case letters. Propose a
777 fix that translate all capital letters to lower case.
778
779 warn_if_capital => {
780 type => 'leaf',
781 value_type => 'string',
782 warn_if_match => {
783 '/A-Z/' => {
784 fix => '$_ = lc;'
785 }
786 },
787 },
788
789 A specific warning can be specified:
790
791 warn_if_capital => {
792 type => 'leaf',
793 value_type => 'string',
794 warn_if_match => {
795 '/A-Z/' => {
796 fix => '$_ = lc;',
797 mesg => 'NO UPPER CASE PLEASE'
798 }
799 },
800 },
801
802 Issue a warning if a value does NOT match a regexp
803 warn_unless => {
804 type => 'leaf',
805 value_type => 'string',
806 warn_unless_match => {
807 foo => {
808 msg => '',
809 fix => '$_ = "foo".$_;'
810 }
811 },
812 },
813
814 Always issue a warning
815 always_warn => {
816 type => 'leaf',
817 value_type => 'string',
818 warn => 'Always warn whenever used',
819 },
820
821 Computed values
822 See "Examples" in Config::Model::ValueComputer.
823
825 Upgrade is a special case when the configuration of an application has
826 changed. Some parameters can be removed and replaced by another one. To
827 avoid trouble on the application user side, Config::Model offers a
828 possibility to handle the migration of configuration data through a
829 special declaration in the configuration model.
830
831 This declaration must:
832
833 · Declare the deprecated parameter with a "status" set to
834 "deprecated"
835
836 · Declare the new parameter with the instructions to load the
837 semantic content from the deprecated parameter. These instructions
838 are declared in the "migrate_from" parameters (which is similar to
839 the "compute" parameter)
840
841 Here an example where a URL parameter is changed to a set of 2
842 parameters (host and path):
843
844 'old_url' => {
845 type => 'leaf',
846 value_type => 'uniline',
847 status => 'deprecated',
848 },
849 'host' => {
850 type => 'leaf',
851 value_type => 'uniline',
852
853 # the formula must end with '$1' so the result of the capture is used
854 # as the host value
855 migrate_from => {
856 formula => '$old =~ m!http://([\w\.]+)!; $1 ;',
857 variables => {
858 old => '- old_url'
859 },
860 use_eval => 1,
861 },
862 },
863 'path' => {
864 type => 'leaf',
865 value_type => 'uniline',
866 migrate_from => {
867 formula => '$old =~ m!http://[\w\.]+(/.*)!; $1 ;',
868 variables => {
869 old => '- old_url'
870 },
871 use_eval => 1,
872 },
873 },
874
876 When an error is encountered, this module may throw the following
877 exceptions:
878
879 Config::Model::Exception::Model Config::Model::Exception::Formula
880 Config::Model::Exception::WrongValue
881 Config::Model::Exception::WarpError
882
883 See Config::Model::Exception for more details.
884
886 Dominique Dumont, (ddumont at cpan dot org)
887
889 Config::Model, Config::Model::Node, Config::Model::AnyId,
890 Config::Model::Warper, Config::Model::Exception
891 Config::Model::ValueComputer,
892
894 Dominique Dumont
895
897 This software is Copyright (c) 2005-2019 by Dominique Dumont.
898
899 This is free software, licensed under:
900
901 The GNU Lesser General Public License, Version 2.1, February 1999
902
903
904
905perl v5.30.0 2019-08-04 Config::Model::Value(3)