++ed by:
KJETILK PSMITH XENO FIBO DCPETROV

161 PAUSE users
135 non-PAUSE users.

Dave Rolsky
and 1 contributors

NAME

Moose::Util::TypeConstraints - Type constraint system for Moose

SYNOPSIS

  use Moose::Util::TypeConstraints;

  type 'Num' => where { Scalar::Util::looks_like_number($_) };

  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);

DESCRIPTION

This module provides Moose with the ability to create custom type constraints to be used in attribute definition.

Important Caveat

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, expression are not typed, etc. etc. etc.

This is simply a means of creating small constraint functions which can be used to simplify your own type-checking code, with the added side benefit of making your intentions clearer through self-documentation.

Slightly Less Important Caveat

It is always a good idea to quote your type and subtype names.

This is to prevent perl from trying to execute the call as an indirect object call. This issue only seems to come up when you have a subtype the same name as a valid class, but when the issue does arise it tends to be quite annoying to debug.

So for instance, this:

  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 yet, is to simply do this:

  use DateTime;
  subtype 'DateTime' => as 'Object' => where { $_->isa('DateTime') };

Default Type Constraints

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 literally interpreted as a type name.

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. I know this is not ideal for all, but it is a saner restriction than most others.

NOTE: The RoleName constraint checks a string is package name which is a role, like 'MyApp::Role::Comparable'. The Role constraint checks that an object does the named role.

Type Constraint Naming

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.Color instead.

Use with Other Constraint Modules

This module should play fairly nicely with other constraint modules with only 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 Declare::Constraints::Simple to declare a completely new type.

  type 'HashOfArrayOfObjects',
      {
      where => IsHashRef(
          -keys   => HasLength,
          -values => IsArrayRef(IsObject)
      )
  };

For more examples see the t/200_examples/204_example_w_DCS.t test file.

Here is an example of using Test::Deep 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/205_example_w_TestDeep.t test file.

FUNCTIONS

Type Constraint Constructors

The following functions are used to create type constraints. They will then register the type constraints in a global store where Moose can get to them if it needs to.

See the SYNOPSIS for an example of how to use these.

type 'Name' = where { } ... >

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.

subtype 'Name' = as 'Parent' => where { } ...>

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.

subtype as 'Parent' = where { } ...>

This creates an unnamed subtype and will return the type constraint meta-object, which will be an instance of Moose::Meta::TypeConstraint.

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 => ... } );
class_type ($class, ?$options)

Creates a new subtype of Object with the name $class and the metaclass Moose::Meta::TypeConstraint::Class.

role_type ($role, ?$options)

Creates a Role type constraint with the name $role and the metaclass Moose::Meta::TypeConstraint::Role.

maybe_type ($type)

Creates a type constraint for either undef or something of the given type.

enum ($name, @values)

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.

enum (\@values)

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 ]]),
  );
as

This is just sugar for the type constraint construction syntax.

where

This is just sugar for the type constraint construction syntax.

Takes a block/code ref as an argument. When the type constraint is tested, the supplied code is run with the value to be tested in $_. This block should return true or false to indicate whether or not the constraint check passed.

message

This is just sugar for the type constraint construction syntax.

Takes a block/code ref as an argument. When the type constraint fails, then the code block is run (with the value provided in $_). This code ref should return a string, which will be used in the text of the exception thrown.

optimize_as

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.

Type Coercion Constructors

Type constraints can also contain type coercions as well. 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.

coerce
from

This is just sugar for the type coercion construction syntax.

via

This is just sugar for the type coercion construction syntax.

Type Constraint Construction & Locating

normalize_type_constraint_name ($type_constraint_name)

Given a string that is expected to match a type constraint, will normalize the string so that extra whitespace and newlines are removed.

create_type_constraint_union ($pipe_separated_types | @type_constraint_names)

Given string with $pipe_separated_types or a list of @type_constraint_names, this will return a Moose::Meta::TypeConstraint::Union instance.

create_parameterized_type_constraint ($type_name)

Given a $type_name in the form of:

  BaseType[ContainerType]

this will extract the base type and container type and build an instance of Moose::Meta::TypeConstraint::Parameterized for it.

create_class_type_constraint ($class, ?$options)

Given a class name it will create a new Moose::Meta::TypeConstraint::Class object for that class name.

create_role_type_constraint ($role, ?$options)

Given a role name it will create a new Moose::Meta::TypeConstraint::Role object for that role name.

create_enum_type_constraint ($name, $values)
find_or_parse_type_constraint ($type_name)

This will attempt to find or create a type constraint given the a $type_name. If it cannot find it in the registry, it will see if it should be a union or container type an create one if appropriate

find_or_create_type_constraint ($type_name, ?$options_for_anon_type)

This function will first call find_or_parse_type_constraint with the type name.

If no type is found or created, but $options_for_anon_type are provided, it will create the corresponding type.

This was used by the does and isa parameters to Moose::Meta::Attribute and are now superseded by find_or_create_isa_type_constraint and find_or_create_does_type_constraint.

find_or_create_isa_type_constraint ($type_name)
find_or_create_does_type_constraint ($type_name)

Attempts to parse the type name using find_or_parse_type_constraint and if no appropriate constraint is found will create a new anonymous one.

The isa variant will use create_class_type_constraint and the does variant will use create_role_type_constraint.

find_type_constraint ($type_name)

This function can be used to locate a specific type constraint meta-object, of the class Moose::Meta::TypeConstraint or a derivative. What you do with it from there is up to you :)

register_type_constraint ($type_object)

This function will register a named type constraint with the type registry.

get_type_constraint_registry

Fetch the Moose::Meta::TypeConstraint::Registry object which keeps track of all type constraints.

list_all_type_constraints

This will return a list of type constraint names, you can then fetch them using find_type_constraint ($type_name) if you want to.

list_all_builtin_type_constraints

This will return a list of builtin type constraints, meaning, those which are defined in this module. See the section labeled "Default Type Constraints" for a complete list.

export_type_constraints_as_functions

This will export all the current type constraints as functions into the caller's namespace. Right now, this is mostly used for testing, but it might prove useful to others.

get_all_parameterizable_types

This returns all the parameterizable types that have been registered.

add_parameterizable_type ($type)

Adds $type to the list of parameterizable types

Namespace Management

unimport

This will remove all the type constraint keywords from the calling class namespace.

BUGS

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.

AUTHOR

Stevan Little <stevan@iinteractive.com>

COPYRIGHT AND LICENSE

Copyright 2006-2009 by Infinity Interactive, Inc.

http://www.iinteractive.com

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.