MooseX::TypeArray - Create composite types where all subtypes must be satisfied
version 0.2.0
{
package #
Foo;
use Moose::Util::TypeConstraint;
use MooseX::TypeArray;
subtype 'Natural',
as 'Int',
where { $_ > 0 };
message { "This number ($_) is not bigger then 0" };
subtype 'BiggerThanTen',
as 'Int',
where { $_ > 10 },
message { "This number ($_) is not bigger than ten!" };
typearray NaturalAndBiggerThanTen => [ 'Natural', 'BiggerThanTen' ];
# or this , which is the same thing.
typearray NaturalAndBiggerThanTen => {
combining => [qw( Natural BiggerThanTen )],
};
...
has field => (
isa => 'NaturalAndBiggerThanTen',
...
);
...
}
use Try::Tiny;
use Data::Dumper qw( Dumper );
try {
Foo->new( field => 0 );
} catch {
print Dumper( $_ );
#
# bless({ errors => {
# Natural => "This number (0) is not bigger then 0",
# BiggerThanTen => "This number (0) is not bigger than ten!"
# }}, 'MooseX::TypeArray::Error' );
#
print $_;
# Validation failed for TypeArray NaturalAndBiggerThanTen with value "0" :
# 1. Validation failed for Natural:
# This number (0) is not bigger than 0
# 2. Validation failed for BiggerThanTen:
# This number (0) is not bigger than ten!
#
}
This type constraint is much like the "Union" type constraint, except the union type constraint validates when any of its members are valid. This type constraint requires ALL of its members to be valid.
This type constraint also returns an Object with a breakdown of the composite failed constraints on error, which you should be able to use if you work with this type constraint directly.
Alas, Moose itself currently doesn't support propagation of objects as validation methods, so you will only get the stringified version of this object until that is solved.
Alternatively, you can use MooseX::Attribute::ValidateWithException until Moose natively supports exceptions.
This function has 2 forms, anonymous and named.
typearray 'foo', [ 'SubTypeA', 'SubTypeB' ];
# the same as
typearray { name => 'foo', combining => [ 'SubTypeA', 'SubTypeB' ] };
typearray 'foo', [ 'SubTypeA', 'SubTypeB' ], { blah => "blah" };
# the same as
typearray { name => 'foo', combining => [ 'SubTypeA', 'SubTypeB' ], blah => "blah" };
typearray 'foo', { blah => "blah" };
# the same as
typearray { name => 'foo', blah => "blah" };
typearray [ 'SubTypeA', 'SubTypeB' ];
# the same as
typearray { combining => [ 'SubTypeA', 'SubTypeB' ] };
typearray [ 'SubTypeA', 'SubTypeB' ], { blah => "blah};
# the same as
typearray { combining => [ 'SubTypeA', 'SubTypeB' ] , blah => "blah" };
typearray {
name => $name # the name of the type ( ie: 'MyType' or 'NaturalBigInt' )
combining => $arrayref # the subtypes which must be satisfied for this constraint
};
No other keys are recognised at this time.
Kent Fredric kentnl@cpan.org
This software is copyright (c) 2013 by Kent Fredric kentnl@cpan.org.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.