blib/lib/Web/VWF/Config.pm untested

filter: Statementstmt 0.0% 0 / 123 Branchbran 0.0% 0 / 72 Conditioncond 0.0% 0 / 30 MC/DCmcdc 0.0% 0 / 20 Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 260 CC 37 SCAR 64.6
CC
37
Cov
0%
new
992.0
AUTOLOAD
56.0
BEGIN
2.0
CRAP 636.0
1 package Web::VWF::Config;
2  
3 # VWF is licensed under GPL2.0 for personal use only
4 # njh@bandsman.co.uk
5  
6 # Usage is subject to licence terms.
7 # The licence terms of this software are as follows:
8 # Personal single user, single computer use: GPL2
9 # All other users (including Commercial, Charity, Educational, Government)
10 # must apply in writing for a licence for use from Nigel Horne at the
11 # above e-mail.
12  
13 use warnings;
14 use strict;
15  
16 use Carp;
17 use Config::Abstraction;
18 use CGI::Info;
19 use Data::Dumper;
20 use Web::VWF::Utils ();
21 use Error::Simple;
22 use File::Spec;
23 use Params::Get 0.13;
24  
25 =encoding utf-8
26  
27 =head1 NAME
28  
29 Web::VWF::Config - Site-independent configuration file for the Versatile Web Framework
30  
31 =head1 VERSION
32  
33 Version 0.004.3
34  
35 =cut
36  
37 use version; our $VERSION = version->declare('0.004.3');
38  
39 # Where the server keeps one configuration directory per site, named after the
40 # site - see Web::VWF::directory()
41 our $DEFAULT_DIRECTORY = '/usr/lib/vwf';
42  
43 =head1 SUBROUTINES/METHODS
44  
45 =head2 new
46  
47 Creates a new Web::VWF::Config instance with hierarchical configuration loading.
48  
49 Takes four optional arguments:
50 info (CGI::Info object)
51 logger
52 config_directory - used when the configuration directory can't be worked out
53 config_file - name of the configuration file - otherwise determined dynamically
54 config (ref to hash of values to override in the config file
55  
56 Values in the file are overridden by what's in the environment
57  
58 B<Parameters:>
59  
60 =over 4
61  
62 =item * C<info> - CGI::Info object (optional, created if not provided)
63  
64 =item * C<logger> - Logger object with debug() method (optional)
65  
66 =item * C<config_directory> - Additional config directory path (optional)
67  
68 =item * C<config_file> - Specific config filename (optional)
69  
70 =item * C<config> - Hash ref of override values (optional)
71  
72 =back
73  
74 B<Configuration Resolution Order:>
75 1. Base configuration files
76 2. Values from config parameter
77 3. Environment variable overrides
78  
79 B<Directory Search Order:>
80 1. $ENV{CONFIG_DIR} (if set)
81 2. Provided config_directory
82 3. ../conf relative to script
83 4. ../../conf relative to script
84 5. $DOCUMENT_ROOT/../lib/conf
85 6. $HOME/lib/conf
86  
87 B<Returns:> Blessed Web::VWF::Config object
88  
89 B<Throws:> Error::Simple on configuration errors
90  
91 =head3 API SPECIFICATION
92  
93 =head4 INPUT
94  
95 {
96 info => { type => 'object', optional => 1 },
97 logger => { type => 'object', optional => 1 }, # with a debug() method
98 directory => { type => 'string', optional => 1 },
99 config_directory => { type => 'string', optional => 1 }, # must exist
100 config_file => { type => 'string', optional => 1 },
101 config => { type => 'hashref', optional => 1 },
102 lingua => { type => 'object', optional => 1 },
103 debug => { type => 'boolean', optional => 1 },
104 }
105  
106 =head4 OUTPUT
107  
108 { type => 'object', isa => 'Web::VWF::Config' }
109  
110 =head3 FORMAL SPECIFICATION
111  
112 [STRING, HASH, LOGGER]
113  
114 ConfigState ::= ⟨⟨ config_dirs : ℙ STRING;
115 config_data : HASH;
116 logger : LOGGER ⟩⟩
117  
118 ConfigArgs ::= ⟨⟨ info : CGI_Info;
119 logger : LOGGER;
120 config_directory : STRING;
121 config_file : STRING;
122 config : HASH ⟩⟩
123  
124 Init : ConfigArgs → ConfigState
125  
126 ∀ params : ConfigArgs •
127 let dirs == if env.CONFIG_DIR ≠ ∅
128 then {env.CONFIG_DIR}
129 else default_dirs ∪ {params.config_directory} fi •
130 let valid_dirs == {d : dirs | ∃ f : FILE • readable(d, f)} •
131 valid_dirs ≠ ∅ ∧
132 config_data ∈ HASH ∧
133 config_data = merge(file_config, params.config, env_overrides)
134  
135 ValidConfigKey == {k : STRING | k ∈ dom config_data}
136  
137 GetConfigValue : ValidConfigKey → (STRING ∪ HASH ∪ ARRAY)
138  
139 =cut
140  
141 sub new
142 {
143 my $proto = shift;
144 my $params = Params::Get::get_params(undef, @_);
145  
146 if (exists $params->{logger} && defined $params->{logger}) {
147 throw Error::Simple('logger must be an object with debug method')
148 unless ref($params->{logger}) && $params->{logger}->can('debug');
149 }
150  
151 if($params->{'logger'}) {
152 $params->{'logger'}->debug(__PACKAGE__, '->new()');
153 }
154  
155 if(exists $params->{config} && defined $params->{config}) {
156 throw Error::Simple('config must be a hash reference') unless ref($params->{config}) eq 'HASH';
157 }
158  
159 my $class = ref($proto) || $proto;
160 my $info = $params->{info} || CGI::Info->new();
161  
162 my @config_dirs;
163 if($ENV{'CONFIG_DIR'}) {
164 # Validate directory exists
165 throw Error::Simple("CONFIG_DIR '$ENV{CONFIG_DIR}' does not exist or is not readable")
166 unless -d $ENV{'CONFIG_DIR'} && -r $ENV{'CONFIG_DIR'};
167 @config_dirs = ($ENV{'CONFIG_DIR'});
168 } else {
169 # Build the standard search path; caller's config_directory is prepended below
170 @config_dirs = (
171 File::Spec->catdir(
172 $info->script_dir(),
173 File::Spec->updir(),
174 File::Spec->updir(),
175 'conf'
176 ), File::Spec->catdir(
177 $info->script_dir(),
178 File::Spec->updir(),
179 'conf'
180 )
181 );
182  
183 # The server's own directory for this site, used when the site keeps no
184 # conf/ beside its cgi-bin/. The domain name comes from the Host header,
185 # so it must look like a host name before it is made part of a path
186 if(defined(my $directory = $params->{'directory'})) {
187 throw Error::Simple('directory must be a string') if ref($directory);
188 my $domain = $info->domain_name();
189 if(defined($domain) && ($domain =~ /\A[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\z/)) {
190 push @config_dirs, File::Spec->catdir($directory, $domain);
191 }
192 }
193  
194 if($ENV{'DOCUMENT_ROOT'}) {
195 push(@config_dirs, File::Spec->catdir(
196 $ENV{'DOCUMENT_ROOT'},
197 File::Spec->updir(),
198 'lib',
199 'conf'
200 ))
201 }
202 if($ENV{'HOME'}) {
203 push(@config_dirs, File::Spec->catdir(
204 $ENV{'HOME'},
205 'lib',
206 'conf'
207 ));
208 }
209  
210 # Prepend the caller-supplied directory so it takes highest precedence
211 if($params->{config_directory}) {
212 throw Error::Simple("config_directory must be a string") if ref($params->{config_directory});
213 throw Error::Simple("config_directory '$params->{config_directory}' does not exist")
214 unless -d $params->{config_directory};
215 unshift @config_dirs, $params->{config_directory};
216 }
217 }
218  
219 # Look for localised configurations
220 my $language;
221 if(my $lingua = $params->{'lingua'}) {
222 $language = $lingua->language_code_alpha2();
223 }
224 $language ||= $info->lang();
225  
226 if($language) {
227 @config_dirs = map {
228 ($_, "$_/default", "$_/$language")
229 } @config_dirs;
230 } else {
231 @config_dirs = map {
232 ($_, File::Spec->catdir($_, 'default'))
233 } @config_dirs;
234 }
235  
236 if($params->{'debug'}) {
237 # Not sure this really does anything
238 # $Config::Auto::Debug = 1;
239  
240 if($params->{logger}) {
241 while(my ($key,$value) = each %ENV) {
242 if($value) {
243 $params->{logger}->debug("$key=$value");
244 }
245 }
246 }
247 }
248  
249 my $config;
250 eval {
251 $config = Config::Abstraction->new(
252 config_dirs => \@config_dirs,
253 config_files => ['default', $info->domain_name(), $ENV{'CONFIG_FILE'}, $params->{'config_file'}],
254 logger => $params->{'logger'}
255 )->all();
256 };
257 if($@ || !defined($config)) {
258 throw Error::Simple("Configuration error: $@");
259 }
260  
261 # Validate essential configuration structure
262 throw Error::Simple('Configuration must be a hash reference') unless(ref($config) eq 'HASH');
263  
264 # The values in config are defaults which can be overridden by
265 # the values in params->{config}
266 if(defined($params->{'config'})) {
267 $config = { %{$config}, %{$params->{'config'}} };
268 }
269  
270 # Allow variables to be overridden by the environment
271 foreach my $key(keys %{$config}) {
272 if(my $value = $ENV{$key}) {
273 # Validate environment variable names
274 # throw Error::Simple("Invalid environment variable name: $key")
275 # unless $key =~ /^[A-Z_][A-Z0-9_]*$/;
276  
277 # Sanitize values
278 # $value =~ s/[^\w\s=\.\-]//g; # Remove potentially dangerous characters
279  
280 if($params->{'logger'}) {
281 $params->{'logger'}->debug(__PACKAGE__, ': ', __LINE__, " overwriting $key, ", $config->{$key}, " with $value");
282 }
283 # If the value contains an equals make it into a hash value
284 if($value =~ /(.+)=(.+)/) {
285 delete $config->{$key} if(!ref($config->{$key}));
286 $config->{$key}{$1} = $2;
287 } else {
288 $config->{$key} = $value;
289 }
290 }
291 }
292  
293 # Config::Any turns fields with spaces into arrays, put them back
294 foreach my $field('Contents', 'SiteTitle') {
295 next if(!exists $config->{$field});
296 my $value = $config->{$field};
297  
298 if(ref($value) eq 'ARRAY') {
299 $config->{$field} = join(' ', @{$value});
300 }
301 }
302  
303 # unless($config->{'config_path'}) {
304 # $config->{'config_path'} = File::Spec->catdir($config_dir, $info->domain_name());
305 # }
306 if($params->{'debug'} && $params->{'logger'}) {
307 $params->{'logger'}->debug(__PACKAGE__, '(', __LINE__, '): ', Data::Dumper->new([Web::VWF::Utils::redact_config($config)])->Dump());
308 }
309  
310 return bless $config, $class;
311 }
312  
313 sub AUTOLOAD
314 {
315 our $AUTOLOAD;
316 my $self = shift;
317  
318 # Called as a class method there is no hash to look in
319 return undef unless(ref($self));
320 return unless defined($AUTOLOAD);
321  
322 # Extract the key name from the AUTOLOAD variable
323 (my $key = $AUTOLOAD) =~ s/.*:://;
324  
325 return unless defined($key);
326  
327 # Don't handle special methods
328 return if $key eq 'DESTROY';
329  
330 # Validate method name - only allow safe config keys
331 Carp::croak(__PACKAGE__, ": Invalid key name: $key") unless $key =~ /^[a-zA-Z_][a-zA-Z0-9_]*$/;
332  
333 # Return the value of the corresponding hash key
334 # Only return existing keys to avoid auto-vivification
335 return exists $self->{$key} ? $self->{$key} : undef;
336 }
337  
338 1;
339  
340 =head1 AUTHOR
341  
342 Nigel Horne, C<< <njh at nigelhorne.com> >>
343  
344 =head1 LICENCE AND COPYRIGHT
345  
346 Copyright 2010-2026 Nigel Horne.
347  
348 Usage is subject to the GPL2 licence terms.
349 If you use it,
350 please let me know.
351  
352 =cut