RWDE/RObject.pm untested

filter: Statementstmt 0.0% 0 / 211 Branchbran 0.0% 0 / 54 Conditioncond 0.0% 0 / 41 MC/DCmcdc 0.0% 0 / 19 Subroutinesub 0.0% 0 / 32 Podpod 0.0% 0 / 23 totaltotal 0.0% 0 / 380 CC 28 SCAR 26.5
CC
28
Cov
0%
FIELDNAME
56.0
check_params
30.0
validate_email
20.0
CRAP 14.1
1 package RWDE::RObject;
2  
3 use strict;
4 use warnings;
5  
6 use Data::Validate::Domain qw(is_domain);
7 use Mail::RFC822::Address qw(valid);
8  
9 use RWDE::Exceptions;
10  
11 use base qw(RWDE::Logging);
12  
13 use vars qw($AUTOLOAD);
14 use vars qw($VERSION);
15 $VERSION = sprintf "%d", q$Revision: 528 $ =~ /(\d+)/;
16  
17 our (%_validators);
18  
19 =pod
20  
21 =head1 RWDE::RObject
22  
23 Base class for various records
24 All derived classes must be hashes and correspond to a standard derived class format
25  
26 =cut
27  
28 BEGIN {
29  
30 #all of the default data validators that we use
31 %_validators = (
32  
33 # Field => [Type, Callback, Descr]
34 IP => [ 'IP', 'validate_ip', 'validate an ip address' ],
35 email => [ 'email', 'validate_email', 'validate an email address' ],
36 boolean => [ 'boolean', 'validate_boolean', 'validate a boolean string' ],
37 );
38 }
39  
40 =head2 new()
41  
42 =cut
43  
44 sub new() {
45 my ($proto, $params) = @_;
46  
47 my $class = ref($proto) || $proto;
48  
49 my $self = { _data => {}, };
50  
51 bless($self, $class);
52  
53 no strict 'refs';
54 $self->{_modifiable_fields} = \%{ $class . "::modifiable_fields" };
55 $self->{_modifiable_fieldnames} = \@{ $class . "::modifiable_fieldnames" };
56 $self->{_static_fields} = \%{ $class . "::static_fields" };
57 $self->{_static_fieldnames} = \@{ $class . "::static_fieldnames" };
58 $self->{_fieldnames} = \@{ $class . "::fieldnames" };
59 $self->{_fields} = \%{ $class . "::fields" };
60 $self->{_id} = ${ $class . "::id" };
61  
62 $self->initialize($params);
63  
64 return $self;
65 }
66  
67 =head2 is_instance()
68  
69 Determine if this reference instance of a class
70  
71 =cut
72  
73 sub is_instance {
74 my ($self, $params) = @_;
75  
76 return ref($self) ? 1 : 0;
77 }
78  
79 =head2 check_object()
80  
81 Verify that this reference is an object.
82  
83 DevelException is thrown if this is not an object instantiation.
84  
85 =cut
86  
87 sub check_object {
88 my ($self, $params) = @_;
89  
90 my $info = $$params{info} || "$self is not an instance.";
91  
92 if (not $self->is_instance()) {
93 my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(1);
94 throw RWDE::DevelException({ info => $info . "Called from $subroutine at $package, line: $line" });
95 }
96  
97 return ();
98 }
99  
100 =head2 field_desc($fn)
101  
102 Get the field description stored within the object for the param $fn.
103  
104 =cut
105  
106 sub field_desc {
107 my $self = shift;
108 my $fn = shift;
109  
110 return (exists $self->{_fields}->{$fn} ? $self->{_fields}->{$fn}[1] : $fn);
111 }
112  
113 =head2 field_type($fn)
114  
115 Get the field type stored within the object for the param $fn.
116  
117 =cut
118  
119 sub field_type {
120 my $self = shift;
121 my $fn = shift;
122  
123 return $self->{_fields}->{$fn}[0];
124 }
125  
126 =head2 FIELDNAME
127  
128 All field names of the record are accessible via the field name. If a
129 second parameter is provided, that value is stored as the data,
130 otherwise the existing value if any is returned. Throws an 'undef'
131 exception on error. It is intended to be called by an F<AUTOLOAD()>
132 method from the subclass.
133  
134 Example:
135  
136 $rec->owner_email('new\@add.ress');
137 $rec->user_addr2(undef);
138 print $rec->user_fname();
139  
140 Would be converted by F<AUTOLOAD()> in the subclass to calls like
141  
142 $rec->FIELDNAME('owner_email','new@add.ress');
143  
144 and so forth.
145  
146 =cut
147  
148 sub FIELDNAME {
149 my $self = shift;
150 my $fn = shift;
151 my $supplied_value = $_[0];
152  
153 $self->check_object({ info => "No method by name: $fn could be located. FIELDNAME tried to find the attribute by $fn - but the call was on $self, not an instance." });
154  
155 $fn =~ s/.*://; # strip fully-qualified portion
156  
157 unless (exists $self->{_fields}->{$fn}) {
158 my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(1);
159 throw RWDE::DevelException({ info => "Unknown field name '$fn' in class $self, for $package on line: $line." });
160 }
161  
162 my $type = $self->field_type($fn); #note the type
163  
164 if (not defined $type) {
165 throw RWDE::DevelException({ info => "Type for $self -> $fn not defined" });
166 }
167  
168 if ( defined $supplied_value
169 && defined $self->{_data}->{$fn}
170 && $type eq 'timestamp'
171 && $supplied_value eq 'date') {
172 return substr($self->{_data}->{$fn}, 0, 10);
173 }
174  
175 #if you are trying to set data, have a name and the data...
176 if (defined($supplied_value)) {
177  
178 #check to see if the field is modifiable
179 if (!(exists $self->{_modifiable_fields}->{$fn})) {
180 throw RWDE::DevelException({ info => "Field name '$fn' in class $self is not allowed to be modified." });
181 }
182  
183 #check to make sure the data is valid to be entered
184 if (exists $_validators{$type}) {
185 my $callback = $_validators{$type}[1];
186 $self->$callback($supplied_value);
187 }
188  
189 #set the data
190 $self->{_data}->{$fn} = $supplied_value;
191 }
192  
193 return $self->{_data}->{$fn};
194 }
195  
196 =head2 validate_email()
197  
198 Check the syntactical format of an email address to reduce risk of
199 bogus addresses.
200  
201 RWDE::DevelException thrown if invalid format detected, otherwise
202 just returns
203  
204 Ensures that the address is in somewhat reasonable domain style, does
205 not contain blanks, commas, brackets, colons, semicolons, or end in a
206 period.
207  
208 =cut
209  
210 sub validate_email {
211 my ($self, $addr) = @_;
212  
213 if (length($addr) > 100) {
214 throw RWDE::DataBadException({ info => 'Email address is too long. We only allow 100 characters.' });
215 }
216  
217 my ($email, $domain) = split /@/, $addr, 2;
218  
219 throw RWDE::DataBadException(
220 {
221 info =>
222 'Unfortunately, we are having problems recording your entries and setting up your account. Please check that the email address you entered is in the standard format of "me@example.com" and that it doesn\'t contain any spaces, commas, parentheses, brackets, colons, double quotes, or semicolons and try again.'
223 }
224 ) unless is_domain($domain);
225  
226 throw RWDE::DataBadException(
227 {
228 info =>
229 'Unfortunately, we are having problems recording your entries and setting up your account. Please check that the email address you entered is in the standard format of "me@example.com" and that it doesn\'t contain any spaces, commas, parentheses, brackets, colons, double quotes, or semicolons and try again.'
230 }
231 ) unless valid($addr);
232  
233 return ();
234 }
235  
236 =head2 validate_ip()
237  
238 Check the syntactical format of an ip address to reduce risk of
239 storing a bogus or faked ip.
240  
241 RWDE::DevelException thrown if invalid format detected, otherwise
242 just returns
243  
244 Ensures that the address is the standard aaa.bbb.ccc.ddd ip address format
245  
246 =cut
247  
248 sub validate_ip {
249 my ($self, $ip) = @_;
250  
251 my @values = split /\./, $ip;
252  
253 my $validity = 0;
254 foreach my $value (@values) {
255 if (($value > 0) && ($value < 256)) {
256 $validity++;
257 }
258 }
259  
260 if ($validity != 4) {
261 throw RWDE::DevelException({ info => 'Invalid format for IP address (aaa.bbb.ccc.ddd)' });
262 }
263  
264 return;
265 }
266  
267 =head2 validate_boolean()
268  
269 Check to make sure that any of the accepted variations on a boolean is present.
270  
271 RWDE::DevelException thrown if invalid boolean detected, otherwise
272 just returns
273  
274 =cut
275  
276 sub validate_boolean {
277 my ($self, $boolean) = @_;
278  
279 if ( ($boolean ne 'true')
280 && ($boolean ne 't')
281 && ($boolean ne '1')
282 && ($boolean ne 'false')
283 && ($boolean ne 'f')
284 && ($boolean ne '0')
285 && ($boolean ne 'NULL')) {
286 throw RWDE::DevelException({ info => 'Invalid boolean expression: ' . $boolean });
287 }
288  
289 return;
290 }
291  
292 =head2 DESTROY()
293  
294 Do nothing. Here just to shut up TT when AUTOLOAD is present
295  
296 =cut
297  
298 sub DESTROY {
299  
300 }
301  
302 =head2 display()
303  
304 =cut
305  
306 sub display {
307 my ($self, $params) = @_;
308  
309 my $data = $self->get_data;
310  
311 foreach my $key (sort keys(%{$data})) {
312 print "$key\t";
313 print defined $data->{$key} ? ":" . $data->{$key} . ":" : 'Not defined (NULL)';
314 print "\n";
315 }
316  
317 return ();
318 }
319  
320 =head2 AUTOLOAD()
321  
322 All field names of the record are accessible via the field name. If a
323 parameter is provided, that value is stored as the data, otherwise the
324 existing value if any is returned. Throws an 'undef' exception on
325 error.
326  
327 Example:
328  
329 $rec->password('blahblah');
330 print $rec->password();
331 @return (Enter explanation for return value here)
332  
333 =cut
334  
335 sub AUTOLOAD {
336 my ($self, @args) = @_;
337  
338 if (not ref $self) {
339 my ($package, $filename, $line) = caller();
340 throw RWDE::DevelException(
341 { info => "Record::AUTOLOAD invoked with the fieldname: $AUTOLOAD; probably static access to an undefined field/method from $filename Line: $line " . join(':', @args) . "\n" });
342 }
343  
344 return $self->FIELDNAME($AUTOLOAD, @args);
345 }
346  
347 =head2 copy_record()
348  
349 Copy a source record over top of this object.
350  
351 In doing so we need to verify that this is an object instance, that this object is different
352 than the source record.
353  
354 If both of those are true then we simply copy the data present within $source into this object instance.
355  
356 =cut
357  
358 sub copy_record {
359 my ($self, $source) = @_;
360  
361 $self->check_object();
362  
363 if ((ref $self) ne (ref $source)) {
364 throw RWDE::DevelException({ info => "Cannot copy $source to $self, they have to be of the same type" });
365 }
366  
367 #copy over all the fields
368 foreach my $fieldname (@{ $self->{_fieldnames} }) {
369  
370 #populate all the fields
371 $self->{_data}->{$fieldname} = $source->$fieldname;
372 }
373  
374 return;
375 }
376  
377 =head2 fill()
378  
379 Fill an object with data specified in the params hash. If the params hash does not have
380 every piece of data, an exception is thrown.
381  
382 =cut
383  
384 sub fill {
385 my ($self, $params) = @_;
386  
387 $self->check_object();
388  
389 #check to make sure we have all the necessary fields
390 foreach my $fieldname (@{ $self->{_fieldnames} }) {
391 throw RWDE::DevelException({ info => "Value for the required field $fieldname not found in params hash." })
392 unless exists($$params{$fieldname});
393  
394 #populate the field
395 $self->{_data}->{$fieldname} = $self->denormalize($fieldname, $$params{$fieldname});
396 }
397  
398 return;
399 }
400  
401 =head2 fill_required()
402  
403 This function takes the required array of elements, populates the current object and notifies if there are any missing elements
404  
405 =cut
406  
407 sub fill_required {
408 my ($self, $params) = @_;
409  
410 my @required = @{ $$params{required} };
411  
412 foreach my $f (@required) {
413 if (not defined($$params{$f})) {
414 $self->add_missing({ key => $f });
415 }
416 else {
417 $self->$f($$params{$f});
418 }
419 }
420  
421 # verify data looks ok...
422 $self->is_missing();
423  
424 return ();
425 }
426  
427 =head2 fill_optional()
428  
429 This function takes the required array of elements, populates the current object and notifies if there are any missing elements
430  
431 =cut
432  
433 sub fill_optional {
434 my ($self, $params) = @_;
435  
436 my @optional = @{ $$params{optional} };
437  
438 foreach my $f (@optional) {
439 if (defined($$params{$f})) {
440 $self->$f($$params{$f});
441 }
442 }
443  
444 return ();
445 }
446  
447 =head2 get_id()
448  
449 Get the id value present in this classes id_name
450  
451 =cut
452  
453 sub get_id {
454 my ($self, $params) = @_;
455  
456 my $id_name = $self->get_id_name();
457  
458 return $self->$id_name;
459 }
460  
461 =head2 get_id_name()
462  
463 Get the id_name stored within the class
464  
465 =cut
466  
467 sub get_id_name {
468 my ($self, $params) = @_;
469  
470 return $self->get_static({ value => '_id' });
471 }
472  
473 =head2 fetch_by_id()
474  
475 =cut
476  
477 sub fetch_by_id {
478 my ($self, $params) = @_;
479  
480 #this element is used to lookup static variables for the given type
481 my $term = $self->new();
482  
483 throw RWDE::DevelException({ info => 'Called with no initialization parameter (has to be ' . $term->get_id_name() . ')' })
484 unless (defined $$params{ $term->get_id_name() });
485  
486 return $term->_fetch_by_id({ $term->get_id_name() => $$params{ $term->get_id_name() } });
487 }
488  
489 =head2 _fetch_by_id()
490  
491 =cut
492  
493 sub _fetch_by_id {
494 my ($self, $params) = @_;
495  
496 return $self->__fetch_by_id($params);
497 }
498  
499 =head2 get_static()
500  
501 =cut
502  
503 sub get_static {
504 my ($self, $params) = @_;
505  
506 my $value;
507  
508 my $key = $$params{value};
509  
510 if (ref $self) {
511 $value = $self->{$key};
512 }
513 else {
514 my $term = $self->new();
515 $value = $term->{$key};
516 }
517  
518 return $value;
519 }
520  
521 =head2 check_params()
522  
523 Verify that all fields specified in the required array are present within the params
524  
525 Note that other fields may be present within the params, but that the required elements
526 must be present at a minimum.
527  
528 RWDE::DevelException is thrown if the required fields are not present within the params,
529 along with a string that includes the names of all missing fields. This information
530 maybe be useful to pass back to the user in an alternate form.
531  
532 =cut
533  
534 sub check_params {
535 my ($self, $params) = @_;
536
537 if (!(defined $params)) {
538 throw RWDE::DevelException({ info => "Record::check_params: params hash not supplied" });
539 }
540  
541 my @required = @{ $$params{required} };
542 my $supplied = $$params{supplied};
543
544 my ($package, $filename, $line) = caller(1);
545
546 #ensure that we received a params hash, and not a scalar or array
547 if (ref $supplied ne 'HASH') {
548 throw RWDE::DevelException({ info => "Record::check_params: ($package) from $filename Line: $line attempted to pass invalid params hash"});
549 }
550  
551 my @missing;
552
553 foreach my $f (@required) {
554 if ( not defined($$supplied{$f})
555 or ($$supplied{$f} =~ m/^\s*$/)
556 or ($$supplied{$f} eq '--')) {
557 push @missing, $f;
558 }
559 }
560  
561 # verify data looks ok...
562 if (@missing) {
563 throw RWDE::DevelException({ info => "Record::check_params: ($package) from $filename Line: $line is missing parameters: " . join(', ', @missing) });
564 }
565  
566 return ();
567 }
568  
569 1;