Moose::Util::TypeConstraints - Type constraint system for Moose
version 2.2201
use Moose::Util::TypeConstraints;
subtype 'Natural',
as 'Int',
where { $_ > 0 };
subtype 'NaturalLessThanTen',
as 'Natural',
where { $_ < 10 },
message { "This number ($_) is not less than ten!" };
coerce 'Num',
from 'Str',
via { 0+$_ };
class_type 'DateTimeClass', { class => 'DateTime' };
role_type 'Barks', { role => 'Some::Library::Role::Barks' };
enum 'RGBColors', [qw(red green blue)];
union 'StringOrArray', [qw( String ArrayRef )];
no Moose::Util::TypeConstraints;
This module provides Moose with the ability to create custom type
constraints to be used in attribute definition.
This is NOT a type system for Perl 5. These are type constraints,
and they are not used by Moose unless you tell it to. No type
inference is performed, expressions are not typed, etc. etc. etc.
A type constraint is at heart a small ``check if a value is valid''
function. A constraint can be associated with an attribute. This
simplifies parameter validation, and makes your code clearer to read,
because you can refer to constraints by name.
It is always a good idea to quote your type names.
This prevents Perl from trying to execute the call as an indirect
object call. This can be an issue when you have a subtype with the
same name as a valid class.
For instance:
subtype DateTime => as Object => where { $_->isa('DateTime') };
will just work, while this:
use DateTime;
subtype DateTime => as Object => where { $_->isa('DateTime') };
will fail silently and cause many headaches. The simple way to solve
this, as well as future proof your subtypes from classes which have
yet to have been created, is to quote the type name:
use DateTime;
subtype 'DateTime', as 'Object', where { $_->isa('DateTime') };
This module also provides a simple hierarchy for Perl 5 types, here is
that hierarchy represented visually.
Any
Item
Bool
Maybe[`a]
Undef
Defined
Value
Str
Num
Int
ClassName
RoleName
Ref
ScalarRef[`a]
ArrayRef[`a]
HashRef[`a]
CodeRef
RegexpRef
GlobRef
FileHandle
Object
NOTE: Any type followed by a type parameter [`a] can be
parameterized, this means you can say:
ArrayRef[Int] # an array of integers
HashRef[CodeRef] # a hash of str to CODE ref mappings
ScalarRef[Int] # a reference to an integer
Maybe[Str] # value may be a string, may be undefined
If Moose finds a name in brackets that it does not recognize as an
existing type, it assumes that this is a class name, for example
ArrayRef[DateTime] .
NOTE: Unless you parameterize a type, then it is invalid to include
the square brackets. I.e. ArrayRef[] will be treated as a new type
name, not as a parameterization of ArrayRef .
NOTE: The Undef type constraint for the most part works
correctly now, but edge cases may still exist, please use it
sparingly.
NOTE: The ClassName type constraint does a complex package
existence check. This means that your class must be loaded for this
type constraint to pass.
NOTE: The RoleName constraint checks a string is a package
name which is a role, like 'MyApp::Role::Comparable' .
Type names declared via this module can only contain alphanumeric
characters, colons (:), and periods (.).
Since the types created by this module are global, it is suggested
that you namespace your types just as you would namespace your
modules. So instead of creating a Color type for your
My::Graphics module, you would call the type
My::Graphics::Types::Color instead.
This module can play nicely with other constraint modules with some
slight tweaking. The where clause in types is expected to be a
CODE reference which checks its first argument and returns a
boolean. Since most constraint modules work in a similar way, it
should be simple to adapt them to work with Moose.
For instance, this is how you could use it with
the Declare::Constraints::Simple manpage to declare a completely new type.
type 'HashOfArrayOfObjects',
where {
IsHashRef(
-keys => HasLength,
-values => IsArrayRef(IsObject)
)->(@_);
};
For more examples see the t/examples/example_w_DCS.t test
file.
Here is an example of using the Test::Deep manpage and its non-test
related eq_deeply function.
type 'ArrayOfHashOfBarsAndRandomNumbers',
where {
eq_deeply($_,
array_each(subhashof({
bar => isa('Bar'),
random_number => ignore()
})))
};
For a complete example see the
t/examples/example_w_TestDeep.t test file.
Type constraints can also specify custom error messages, for when they fail to
validate. This is provided as just another coderef, which receives the invalid
value in $_ , as in:
subtype 'PositiveInt',
as 'Int',
where { $_ > 0 },
message { "$_ is not a positive integer!" };
If no message is specified, a default message will be used, which indicates
which type constraint was being used and what value failed. If
the Devel::PartialDump manpage (version 0.14 or higher) is installed, it will be used to
display the invalid value, otherwise it will just be printed as is.
The following functions are used to create type constraints. They
will also register the type constraints your create in a global
registry that is used to look types up by name.
See the SYNOPSIS for an example of how to use these.
This creates a named subtype.
If you provide a parent that Moose does not recognize, it will
automatically create a new class type constraint for this name.
When creating a named type, the subtype function should either be
called with the sugar helpers (where , message , etc), or with a
name and a hashref of parameters:
subtype( 'Foo', { where => ..., message => ... } );
The valid hashref keys are as (the parent), where , message ,
and inline_as .
This creates an unnamed subtype and will return the type
constraint meta-object, which will be an instance of
the Moose::Meta::TypeConstraint manpage.
When creating an anonymous type, the subtype function should either
be called with the sugar helpers (where , message , etc), or with
just a hashref of parameters:
subtype( { where => ..., message => ... } );
Creates a new subtype of Object with the name $class and the
metaclass the Moose::Meta::TypeConstraint::Class manpage.
# Create a type called 'Box' which tests for objects which ->isa('Box')
class_type 'Box';
By default, the name of the type and the name of the class are the same, but
you can specify both separately.
# Create a type called 'Box' which tests for objects which ->isa('ObjectLibrary::Box');
class_type 'Box', { class => 'ObjectLibrary::Box' };
Creates a Role type constraint with the name $role and the
metaclass the Moose::Meta::TypeConstraint::Role manpage.
# Create a type called 'Walks' which tests for objects which ->does('Walks')
role_type 'Walks';
By default, the name of the type and the name of the role are the same, but
you can specify both separately.
# Create a type called 'Walks' which tests for objects which ->does('MooseX::Role::Walks');
role_type 'Walks', { role => 'MooseX::Role::Walks' };
Creates a type constraint for either undef or something of the
given type.
This will create a subtype of Object and test to make sure the value
can() do the methods in \@methods .
This is intended as an easy way to accept non-Moose objects that
provide a certain interface. If you're using Moose classes, we
recommend that you use a requires -only Role instead.
If passed an ARRAY reference as the only parameter instead of the
$name , \@methods pair, this will create an unnamed duck type.
This can be used in an attribute definition like so:
has 'cache' => (
is => 'ro',
isa => duck_type( [qw( get_set )] ),
);
This will create a basic subtype for a given set of strings.
The resulting constraint will be a subtype of Str and
will match any of the items in \@values . It is case sensitive.
See the SYNOPSIS for a simple example.
NOTE: This is not a true proper enum type, it is simply
a convenient constraint builder.
If passed an ARRAY reference as the only parameter instead of the
$name , \@values pair, this will create an unnamed enum. This
can then be used in an attribute definition like so:
has 'sort_order' => (
is => 'ro',
isa => enum([qw[ ascending descending ]]),
);
This will create a basic subtype where any of the provided constraints
may match in order to satisfy this constraint.
If passed an ARRAY reference as the only parameter instead of the
$name , \@constraints pair, this will create an unnamed union.
This can then be used in an attribute definition like so:
has 'items' => (
is => 'ro',
isa => union([qw[ Str ArrayRef ]]),
);
This is similar to the existing string union:
isa => 'Str|ArrayRef'
except that it supports anonymous elements as child constraints:
has 'color' => (
isa => 'ro',
isa => union([ 'Int', enum([qw[ red green blue ]]) ]),
);
This is just sugar for the type constraint construction syntax.
It takes a single argument, which is the name of a parent type.
This is just sugar for the type constraint construction syntax.
It takes a subroutine reference as an argument. When the type
constraint is tested, the reference is run with the value to be tested
in $_ . This reference should return true or false to indicate
whether or not the constraint check passed.
This is just sugar for the type constraint construction syntax.
It takes a subroutine reference as an argument. When the type
constraint fails, then the code block is run with the value provided
in $_ . This reference should return a string, which will be used in
the text of the exception thrown.
This can be used to define a ``hand optimized'' inlinable version of your type
constraint.
You provide a subroutine which will be called as a method on a
the Moose::Meta::TypeConstraint manpage object. It will receive a single parameter, the
name of the variable to check, typically something like "$_" or "$_[0]" .
The subroutine should return a code string suitable for inlining. You can
assume that the check will be wrapped in parentheses when it is inlined.
The inlined code should include any checks that your type's parent types
do. If your parent type constraint defines its own inlining, you can simply use
that to avoid repeating code. For example, here is the inlining code for the
Value type, which is a subtype of Defined :
sub {
$_[0]->parent()->_inline_check($_[1])
. ' && !ref(' . $_[1] . ')'
}
This creates a base type, which has no parent.
The type function should either be called with the sugar helpers
(where , message , etc), or with a name and a hashref of
parameters:
type( 'Foo', { where => ..., message => ... } );
The valid hashref keys are where , message , and inlined_as .
This is a utility function for doing simple type based dispatching similar to
match/case in OCaml and case/of in Haskell. It is not as featureful as those
languages, nor does not it support any kind of automatic destructuring
bind. Here is a simple Perl pretty printer dispatching over the core Moose
types.
sub ppprint {
my $x = shift;
match_on_type $x => (
HashRef => sub {
my $hash = shift;
'{ '
. (
join ", " => map { $_ . ' => ' . ppprint( $hash->{$_} ) }
sort keys %$hash
) . ' }';
},
ArrayRef => sub {
my $array = shift;
'[ ' . ( join ", " => map { ppprint($_) } @$array ) . ' ]';
},
CodeRef => sub {'sub { ... }'},
RegexpRef => sub { 'qr/' . $_ . '/' },
GlobRef => sub { '*' . B::svref_2object($_)->NAME },
Object => sub { $_->can('to_string') ? $_->to_string : $_ },
ScalarRef => sub { '\\' . ppprint( ${$_} ) },
Num => sub {$_},
Str => sub { '"' . $_ . '"' },
Undef => sub {'undef'},
=> sub { die "I don't know what $_ is" }
);
}
Or a simple JSON serializer:
sub to_json {
my $x = shift;
match_on_type $x => (
HashRef => sub {
my $hash = shift;
'{ '
. (
join ", " =>
map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) }
sort keys %$hash
) . ' }';
},
ArrayRef => sub {
my $array = shift;
'[ ' . ( join ", " => map { to_json($_) } @$array ) . ' ]';
},
Num => sub {$_},
Str => sub { '"' . $_ . '"' },
Undef => sub {'null'},
=> sub { die "$_ is not acceptable json type" }
);
}
The matcher is done by mapping a $type to an \&action . The $type can
be either a string type or a the Moose::Meta::TypeConstraint manpage object, and
\&action is a subroutine reference. This function will dispatch on the
first match for $value . It is possible to have a catch-all by providing an
additional subroutine reference as the final argument to match_on_type .
You can define coercions for type constraints, which allow you to
automatically transform values to something valid for the type
constraint. If you ask your accessor to coerce by adding the option coerce => 1 , then Moose will run
the type-coercion code first, followed by the type constraint
check. This feature should be used carefully as it is very powerful
and could easily take off a limb if you are not careful.
See the SYNOPSIS for an example of how to use these.
This defines a coercion from one type to another. The Name argument
is the type you are coercing to.
To define multiple coercions, supply more sets of from/via pairs:
coerce 'Name',
from 'OtherName', via { ... },
from 'ThirdName', via { ... };
This is just sugar for the type coercion construction syntax.
It takes a single type name (or type object), which is the type being
coerced from.
This is just sugar for the type coercion construction syntax.
It takes a subroutine reference. This reference will be called with
the value to be coerced in $_ . It is expected to return a new value
of the proper type for the coercion.
These are additional functions for creating and finding type
constraints. Most of these functions are not available for
importing. The ones that are importable as specified.
This function can be used to locate the the Moose::Meta::TypeConstraint manpage
object for a named type.
This function is importable.
This function will register a the Moose::Meta::TypeConstraint manpage with the
global type registry.
This function is importable.
This method takes a type constraint name and returns the normalized
form. This removes any whitespace in the string.
This can take a union type specification like 'Int|ArrayRef[Int]' ,
or a list of names. It returns a new
the Moose::Meta::TypeConstraint::Union manpage object.
Given a $type_name in the form of 'BaseType[ContainerType]' ,
this will create a new the Moose::Meta::TypeConstraint::Parameterized manpage
object. The BaseType must already exist as a parameterizable
type.
Given a class name this function will create a new
the Moose::Meta::TypeConstraint::Class manpage object for that class name.
The $options is a hash reference that will be passed to the
the Moose::Meta::TypeConstraint::Class manpage constructor (as a hash).
Given a role name this function will create a new
the Moose::Meta::TypeConstraint::Role manpage object for that role name.
The $options is a hash reference that will be passed to the
the Moose::Meta::TypeConstraint::Role manpage constructor (as a hash).
Given a enum name this function will create a new
the Moose::Meta::TypeConstraint::Enum manpage object for that enum name.
Given a duck type name this function will create a new
the Moose::Meta::TypeConstraint::DuckType manpage object for that enum name.
Given a type name, this first attempts to find a matching constraint
in the global registry.
If the type name is a union or parameterized type, it will create a
new object of the appropriate, but if given a ``regular'' type that does
not yet exist, it simply returns false.
When given a union or parameterized type, the member or base type must
already exist.
If it creates a new union or parameterized type, it will add it to the
global registry.
These functions will first call find_or_parse_type_constraint . If
that function does not return a type, a new type object will
be created.
The isa variant will use create_class_type_constraint and the
does variant will use create_role_type_constraint .
Returns the the Moose::Meta::TypeConstraint::Registry manpage object which
keeps track of all type constraints.
This will return a list of type constraint names in the global
registry. You can then fetch the actual type object using
find_type_constraint($type_name) .
This will return a list of builtin type constraints, meaning those
which are defined in this module. See the Default Type Constraints
section for a complete list.
This will export all the current type constraints as functions into
the caller's namespace (Int() , Str() , etc). Right now, this is
mostly used for testing, but it might prove useful to others.
This returns all the parameterizable types that have been registered,
as a list of type objects.
Adds $type to the list of parameterizable types
See Moose/BUGS for details on reporting bugs.
This software is copyright (c) 2006 by Infinity Interactive, Inc.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
|