| Moose::Util::TypeConstraints - Type constraint system for Moose |
Moose::Util::TypeConstraints - Type constraint system for Moose
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+$_ };
enum 'RGBColors' => qw(red green blue);
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
Num
Int
Str
ClassName
RoleName
Ref
ScalarRef
ArrayRef[`a]
HashRef[`a]
CodeRef
RegexpRef
GlobRef
FileHandle
Object
Role
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 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'. The Role
constraint checks that an object does the named role.
Type name 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 it's 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/200_examples/004_example_w_DCS.t test file.
Here is an example of using the Test::Deep manpage and it's 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/200_examples/005_example_w_TestDeep.t test file.
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 optimize_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.
Creates a Role type constraint with the name $role and the
metaclass the Moose::Meta::TypeConstraint::Role manpage.
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 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 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 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" version of your type constraint which can be used to avoid traversing a subtype constraint hierarchy.
NOTE: You should only use this if you know what you are doing, all the built in types use this, so your subtypes (assuming they are shallow) will not likely need to use this.
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 optimize_as.
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, 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.
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 exist 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 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 anonymous 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
All complex software has bugs lurking in it, and this module is no exception. If you find a bug please either email me, or add the bug to cpan-RT.
Stevan Little <stevan@iinteractive.com>
Copyright 2006-2009 by Infinity Interactive, Inc.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| Moose::Util::TypeConstraints - Type constraint system for Moose |