Declare::Constraints::Simple::Library::OO - OO Constraints


Declare-Constraints-Simple documentation Contained in the Declare-Constraints-Simple distribution.

Index


Code Index:

NAME

Top

Declare::Constraints::Simple::Library::OO - OO Constraints

SYNOPSIS

Top

  # accept objects or classes
  my $object_or_class = Or( IsObject, IsClass );

  # valid on objects with all methods
  my $proper_object = And( IsObject, 
                           HasMethods( qw(foo bar) ));

  # validate against date objects
  my $is_date_object = IsA('DateTime');

DESCRIPTION

Top

This library contains the constraints for validating parameters in an object oriented manner.

CONSTRAINTS

Top

HasMethods(@methods)

Returns true if the value is an object or class that can all the specified @methods.

The stack or path part of HasMethods looks like HasMethods[$method] where $method is the first found missing method.

IsA(@classes)

Is true if the passed object or class is a subclass of one of the classes mentioned in @classes.

IsClass()

Valid if value is a loaded class.

IsObject()

True if the value is blessed.

SEE ALSO

Top

Declare::Constraints::Simple, Declare::Constraints::Simple::Library

AUTHOR

Top

Robert 'phaylon' Sedlacek <phaylon@dunkelheit.at>

LICENSE AND COPYRIGHT

Top


Declare-Constraints-Simple documentation Contained in the Declare-Constraints-Simple distribution.
package Declare::Constraints::Simple::Library::OO;
use warnings;
use strict;

use Declare::Constraints::Simple-Library;

use Class::Inspector;
use Scalar::Util ();

constraint 'HasMethods',
    sub {
        my (@methods) = @_;
        return sub { 
            return _false('Undefined Value') unless defined $_[0];
            return _false('Not a Class or Object') 
                unless Scalar::Util::blessed($_[0])
                    or Class::Inspector->loaded($_[0]);

            for (@methods) { 
                unless ($_[0]->can($_)) {
                    _info($_);
                    return _false("Method $_ not implemented");
                }
            }

            return _true;
        };
    };

constraint 'IsA',
    sub {
        my (@classes) = @_;
        return sub {
            return _false('Undefined Value') unless defined $_[0];
            for (@classes) { 
                return _true if eval { $_[0]->isa($_) };
            }
            return _false('No matching Class');
        };
    };

constraint 'IsClass',
    sub {
        return sub {
            return _false('Undefined Value') unless defined $_[0];
            return _result(Class::Inspector->loaded($_[0]), 
                'Not a loaded Class');
        };
    };

constraint 'IsObject',
    sub {
        return sub {
            return _false('Undefined Value') unless defined $_[0];
            return _result(Scalar::Util::blessed($_[0]), 
                'Not an Object');
        };
    };

1;