File Coverage

blib/lib/MooseX/Types.pm
Criterion Covered Total %
statement 92 93 98.9
branch 19 22 86.3
condition n/a
subroutine 46 46 100.0
pod 6 6 100.0
total 163 167 97.6


line stmt bran cond sub pod time code
1             package MooseX::Types; # git description: v0.49-2-gc8f752e
2 18     142   860430 use Moose;
  18         5999450  
  18         134  
3             # ABSTRACT: Organise your Moose types in libraries
4             # KEYWORDS: moose types classes objects constraints declare libraries
5              
6             our $VERSION = '0.50';
7              
8 18     105   124994 use Moose::Util::TypeConstraints qw( find_type_constraint );
  18         34  
  18         190  
9 18     25   18013 use MooseX::Types::TypeDecorator;
  18         60  
  18         646  
10 18     18   9686 use MooseX::Types::Base ();
  18         57  
  18         755  
11 18     18   9098 use MooseX::Types::Util qw( filter_tags );
  18         38  
  18         1095  
12 18     18   7691 use MooseX::Types::UndefinedType;
  18         39  
  18         549  
13 18     18   8038 use MooseX::Types::CheckedUtilExports ();
  18         55  
  18         638  
14 18     18   152 use Carp::Clan qw( ^MooseX::Types );
  18         29  
  18         136  
15 18     18   2876 use Sub::Name;
  18         30  
  18         1037  
16 18     18   91 use Scalar::Util qw( reftype );
  18         27  
  18         1040  
17 18     18   10152 use Sub::Exporter::ForMethods 0.100052 'method_installer'; # for 'rebless'
  18         15489  
  18         103  
18              
19 18     18   5827 use namespace::autoclean;
  18         28  
  18         141  
20              
21 18     18   1352 use 5.008;
  18         48  
22             my $UndefMsg = q{Action for type '%s' not yet defined in library '%s'};
23              
24             #pod =pod
25             #pod
26             #pod =head1 SYNOPSIS
27             #pod
28             #pod =head2 Library Definition
29             #pod
30             #pod package MyLibrary;
31             #pod
32             #pod # predeclare our own types
33             #pod use MooseX::Types -declare => [
34             #pod qw(
35             #pod PositiveInt
36             #pod NegativeInt
37             #pod ArrayRefOfPositiveInt
38             #pod ArrayRefOfAtLeastThreeNegativeInts
39             #pod LotsOfInnerConstraints
40             #pod StrOrArrayRef
41             #pod MyDateTime
42             #pod )
43             #pod ];
44             #pod
45             #pod # import builtin types
46             #pod use MooseX::Types::Moose qw/Int HashRef/;
47             #pod
48             #pod # type definition.
49             #pod subtype PositiveInt,
50             #pod as Int,
51             #pod where { $_ > 0 },
52             #pod message { "Int is not larger than 0" };
53             #pod
54             #pod subtype NegativeInt,
55             #pod as Int,
56             #pod where { $_ < 0 },
57             #pod message { "Int is not smaller than 0" };
58             #pod
59             #pod # type coercion
60             #pod coerce PositiveInt,
61             #pod from Int,
62             #pod via { 1 };
63             #pod
64             #pod # with parameterized constraints.
65             #pod
66             #pod subtype ArrayRefOfPositiveInt,
67             #pod as ArrayRef[PositiveInt];
68             #pod
69             #pod subtype ArrayRefOfAtLeastThreeNegativeInts,
70             #pod as ArrayRef[NegativeInt],
71             #pod where { scalar(@$_) > 2 };
72             #pod
73             #pod subtype LotsOfInnerConstraints,
74             #pod as ArrayRef[ArrayRef[HashRef[Int]]];
75             #pod
76             #pod # with TypeConstraint Unions
77             #pod
78             #pod subtype StrOrArrayRef,
79             #pod as Str|ArrayRef;
80             #pod
81             #pod # class types
82             #pod
83             #pod class_type 'DateTime';
84             #pod
85             #pod # or better
86             #pod
87             #pod class_type MyDateTime, { class => 'DateTime' };
88             #pod
89             #pod coerce MyDateTime,
90             #pod from HashRef,
91             #pod via { DateTime->new(%$_) };
92             #pod
93             #pod 1;
94             #pod
95             #pod =head2 Usage
96             #pod
97             #pod package Foo;
98             #pod use Moose;
99             #pod use MyLibrary qw( PositiveInt NegativeInt );
100             #pod
101             #pod # use the exported constants as type names
102             #pod has 'bar',
103             #pod isa => PositiveInt,
104             #pod is => 'rw';
105             #pod has 'baz',
106             #pod isa => NegativeInt,
107             #pod is => 'rw';
108             #pod
109             #pod sub quux {
110             #pod my ($self, $value);
111             #pod
112             #pod # test the value
113             #pod print "positive\n" if is_PositiveInt($value);
114             #pod print "negative\n" if is_NegativeInt($value);
115             #pod
116             #pod # coerce the value, NegativeInt doesn't have a coercion
117             #pod # helper, since it didn't define any coercions.
118             #pod $value = to_PositiveInt($value) or die "Cannot coerce";
119             #pod }
120             #pod
121             #pod 1;
122             #pod
123             #pod =head1 DESCRIPTION
124             #pod
125             #pod The type system provided by Moose effectively makes all of its builtin type
126             #pod global, as are any types you declare with Moose. This means that every module
127             #pod that declares a type named C<PositiveInt> is sharing the same type object. This
128             #pod can be a problem when different parts of the code base want to use the same
129             #pod name for different things.
130             #pod
131             #pod This package lets you declare types using short names, but behind the scenes
132             #pod it namespaces all your type declarations, effectively prevent name clashes
133             #pod between packages.
134             #pod
135             #pod This is done by creating a type library module like C<MyApp::Types> and then
136             #pod importing types from that module into other modules.
137             #pod
138             #pod As a side effect, the declaration mechanism allows you to write type names as
139             #pod barewords (really function calls), which catches typos in names at compile
140             #pod time rather than run time.
141             #pod
142             #pod This module also provides some helper functions for using Moose types outside
143             #pod of attribute declarations.
144             #pod
145             #pod If you mix string-based names with types created by this module, it will warn,
146             #pod with a few exceptions. If you are declaring a C<class_type()> or
147             #pod C<role_type()> within your type library, or if you use a fully qualified name
148             #pod like C<"MyApp::Foo">.
149             #pod
150             #pod =head1 LIBRARY DEFINITION
151             #pod
152             #pod A MooseX::Types is just a normal Perl module. Unlike Moose
153             #pod itself, it does not install C<use strict> and C<use warnings> in your
154             #pod class by default, so this is up to you.
155             #pod
156             #pod The only thing a library is required to do is
157             #pod
158             #pod use MooseX::Types -declare => \@types;
159             #pod
160             #pod with C<@types> being a list of types you wish to define in this library.
161             #pod This line will install a proper base class in your package as well as the
162             #pod full set of L<handlers|/"TYPE HANDLER FUNCTIONS"> for your declared
163             #pod types. It will then hand control over to L<Moose::Util::TypeConstraints>'
164             #pod C<import> method to export the functions you will need to declare your
165             #pod types.
166             #pod
167             #pod If you want to use Moose' built-in types (e.g. for subtyping) you will
168             #pod want to
169             #pod
170             #pod use MooseX::Types::Moose @types;
171             #pod
172             #pod to import the helpers from the shipped L<MooseX::Types::Moose>
173             #pod library which can export all types that come with Moose.
174             #pod
175             #pod You will have to define coercions for your types or your library won't
176             #pod export a L</to_$type> coercion helper for it.
177             #pod
178             #pod Note that you currently cannot define types containing C<::>, since
179             #pod exporting would be a problem.
180             #pod
181             #pod You also don't need to use C<warnings> and C<strict>, since the
182             #pod definition of a library automatically exports those.
183             #pod
184             #pod =head1 LIBRARY USAGE
185             #pod
186             #pod You can import the L<"type helpers"|/"TYPE HANDLER FUNCTIONS"> of a
187             #pod library by C<use>ing it with a list of types to import as arguments. If
188             #pod you want all of them, use the C<:all> tag. For example:
189             #pod
190             #pod use MyLibrary ':all';
191             #pod use MyOtherLibrary qw( TypeA TypeB );
192             #pod
193             #pod MooseX::Types comes with a library of Moose' built-in types called
194             #pod L<MooseX::Types::Moose>.
195             #pod
196             #pod The exporting mechanism is, since version 0.5, implemented via a wrapper
197             #pod around L<Sub::Exporter>. This means you can do something like this:
198             #pod
199             #pod use MyLibrary TypeA => { -as => 'MyTypeA' },
200             #pod TypeB => { -as => 'MyTypeB' };
201             #pod
202             #pod =head1 TYPE HANDLER FUNCTIONS
203             #pod
204             #pod =head2 $type
205             #pod
206             #pod A constant with the name of your type. It contains the type's fully
207             #pod qualified name. Takes no value, as all constants.
208             #pod
209             #pod =head2 is_$type
210             #pod
211             #pod This handler takes a value and tests if it is a valid value for this
212             #pod C<$type>. It will return true or false.
213             #pod
214             #pod =head2 to_$type
215             #pod
216             #pod A handler that will take a value and coerce it into the C<$type>. It will
217             #pod return a false value if the type could not be coerced.
218             #pod
219             #pod B<Important Note>: This handler will only be exported for types that can
220             #pod do type coercion. This has the advantage that a coercion to a type that
221             #pod has not defined any coercions will lead to a compile-time error.
222             #pod
223             #pod =head1 WRAPPING A LIBRARY
224             #pod
225             #pod You can define your own wrapper subclasses to manipulate the behaviour
226             #pod of a set of library exports. Here is an example:
227             #pod
228             #pod package MyWrapper;
229             #pod use strict;
230             #pod use MRO::Compat;
231             #pod use base 'MooseX::Types::Wrapper';
232             #pod
233             #pod sub coercion_export_generator {
234             #pod my $class = shift;
235             #pod my $code = $class->next::method(@_);
236             #pod return sub {
237             #pod my $value = $code->(@_);
238             #pod warn "Coercion returned undef!"
239             #pod unless defined $value;
240             #pod return $value;
241             #pod };
242             #pod }
243             #pod
244             #pod 1;
245             #pod
246             #pod This class wraps the coercion generator (e.g., C<to_Int()>) and warns
247             #pod if a coercion returned an undefined value. You can wrap any library
248             #pod with this:
249             #pod
250             #pod package Foo;
251             #pod use strict;
252             #pod use MyWrapper MyLibrary => [qw( Foo Bar )],
253             #pod Moose => [qw( Str Int )];
254             #pod
255             #pod ...
256             #pod 1;
257             #pod
258             #pod The C<Moose> library name is a special shortcut for L<MooseX::Types::Moose>.
259             #pod
260             #pod =head2 Generator methods you can overload
261             #pod
262             #pod =over 4
263             #pod
264             #pod =item type_export_generator( $short, $full )
265             #pod
266             #pod Creates a closure returning the type's L<Moose::Meta::TypeConstraint> object.
267             #pod
268             #pod =item check_export_generator( $short, $full, $undef_message )
269             #pod
270             #pod This creates the closure used to test if a value is valid for this type.
271             #pod
272             #pod =item coercion_export_generator( $short, $full, $undef_message )
273             #pod
274             #pod This is the closure that's doing coercions.
275             #pod
276             #pod =back
277             #pod
278             #pod =head2 Provided Parameters
279             #pod
280             #pod =over 4
281             #pod
282             #pod =item $short
283             #pod
284             #pod The short, exported name of the type.
285             #pod
286             #pod =item $full
287             #pod
288             #pod The fully qualified name of this type as L<Moose> knows it.
289             #pod
290             #pod =item $undef_message
291             #pod
292             #pod A message that will be thrown when type functionality is used but the
293             #pod type does not yet exist.
294             #pod
295             #pod =back
296             #pod
297             #pod =head1 RECURSIVE SUBTYPES
298             #pod
299             #pod As of version 0.08, L<Moose::Types> has experimental support for Recursive
300             #pod subtypes. This will allow:
301             #pod
302             #pod subtype Tree() => as HashRef[Str|Tree];
303             #pod
304             #pod Which validates things like:
305             #pod
306             #pod {key=>'value'};
307             #pod {key=>{subkey1=>'value', subkey2=>'value'}}
308             #pod
309             #pod And so on. This feature is new and there may be lurking bugs so don't be afraid
310             #pod to hunt me down with patches and test cases if you have trouble.
311             #pod
312             #pod =head1 NOTES REGARDING TYPE UNIONS
313             #pod
314             #pod L<MooseX::Types> uses L<MooseX::Types::TypeDecorator> to do some overloading
315             #pod which generally allows you to easily create union types:
316             #pod
317             #pod subtype StrOrArrayRef,
318             #pod as Str|ArrayRef;
319             #pod
320             #pod As with parameterized constraints, this overloading extends to modules using the
321             #pod types you define in a type library.
322             #pod
323             #pod use Moose;
324             #pod use MooseX::Types::Moose qw(HashRef Int);
325             #pod
326             #pod has 'attr' => ( isa => HashRef | Int );
327             #pod
328             #pod And everything should just work as you'd think.
329             #pod
330             #pod =head1 METHODS
331             #pod
332             #pod =head2 import
333             #pod
334             #pod Installs the L<MooseX::Types::Base> class into the caller and exports types
335             #pod according to the specification described in L</"LIBRARY DEFINITION">. This
336             #pod will continue to L<Moose::Util::TypeConstraints>' C<import> method to export
337             #pod helper functions you will need to declare your types.
338             #pod
339             #pod =cut
340              
341             sub import {
342 41     41   10080 my ($class, %args) = @_;
343 41         117 my $caller = caller;
344              
345             # everyone should want this
346 41         341 strict->import;
347 41         651 warnings->import;
348              
349             # inject base class into new library
350 18     18   101 { no strict 'refs';
  18         30  
  18         14758  
  41         57  
351 41         66 unshift @{ $caller . '::ISA' }, 'MooseX::Types::Base';
  41         749  
352             }
353              
354             # generate predeclared type helpers
355 41 100       78 if (my @orig_declare = @{ $args{ -declare } || [] }) {
  41 100       445  
356 22         136 my ($tags, $declare) = filter_tags @orig_declare;
357 22         46 my @to_export;
358              
359 22         151 for my $type (@$declare) {
360              
361 63 100       179 croak "Cannot create a type containing '::' ($type) at the moment"
362             if $type =~ /::/;
363              
364             # add type to library and remember to export
365 62         290 $caller->add_type($type);
366 62         105 push @to_export, $type;
367             }
368              
369             $caller->import({
370 21         173 -full => 1,
371             -into => $caller,
372             installer => method_installer({ rebless => 1 }),
373             }, @to_export);
374             }
375              
376             # run type constraints import
377 40         9777 Moose::Util::TypeConstraints->import({ into => $caller });
378              
379             # override some with versions that check for syntax errors
380 40         59638 MooseX::Types::CheckedUtilExports->import({ into => $caller });
381              
382 40         57936 1;
383             }
384              
385             #pod =head2 type_export_generator
386             #pod
387             #pod Generate a type export, e.g. C<Int()>. This will return either a
388             #pod L<Moose::Meta::TypeConstraint> object, or alternatively a
389             #pod L<MooseX::Types::UndefinedType> object if the type was not yet defined.
390             #pod
391             #pod =cut
392              
393             sub type_export_generator {
394 172     172 1 351 my ($class, $type, $name) = @_;
395              
396             ## Return an anonymous subroutine that will generate the proxied type
397             ## constraint for you.
398              
399             return subname "__TYPE__::$name" => sub {
400 274     30   129272 my $type_constraint = $class->create_base_type_constraint($name);
        202      
        21      
        21      
        21      
        21      
        21      
        21      
        110      
        308      
        191      
        211      
        139      
        205      
        181      
        21      
        21      
        21      
        246      
        145      
        120      
        354      
        86      
401              
402 274 100       42532 if(defined(my $params = shift @_)) {
403             ## We currently only allow a TC to accept a single, ArrayRef
404             ## parameter, as in HashRef[Int], where [Int] is what's inside the
405             ## ArrayRef passed.
406 24 100       135 if(reftype $params eq 'ARRAY') {
    50          
407 23         81 $type_constraint = $class->create_arged_type_constraint($name, @$params);
408             } elsif(!defined $type_constraint) {
409 1         20 croak "Syntax error in type definition (did you forget a comma"
410             . " after $type?)";
411             } else {
412 0         0 croak "Argument must be an ArrayRef to create a parameterized "
413             . "type, Eg.: ${type}[Int]. Got: ".ref($params)."."
414             }
415             }
416              
417 273 100       887 $type_constraint = defined($type_constraint) ? $type_constraint
418             : MooseX::Types::UndefinedType->new($name);
419              
420 273         761 my $type_decorator = $class->create_type_decorator($type_constraint);
421              
422             ## If there are additional args, that means it's probably stuff that
423             ## needs to be returned to the subtype. Not an ideal solution here but
424             ## doesn't seem to cause trouble.
425              
426 273 100       608 if(@_) {
427 5         34 return ($type_decorator, @_);
428             } else {
429 268         1725 return $type_decorator;
430             }
431 172         2260 };
432             }
433              
434             #pod =head2 create_arged_type_constraint ($name, @args)
435             #pod
436             #pod Given a String $name with @args find the matching type constraint and parameterize
437             #pod it with @args.
438             #pod
439             #pod =cut
440              
441             sub create_arged_type_constraint {
442 23     103 1 68 my ($class, $name, @args) = @_;
443 23         113 my $type_constraint = Moose::Util::TypeConstraints::find_or_create_type_constraint("$name");
444 23         2610 my $parameterized = $type_constraint->parameterize(@args);
445             # It's obnoxious to have to parameterize before looking for the TC, but the
446             # alternative is to hard-code the assumption that the name is
447             # "$name[$args[0]]", which would be worse.
448             # This breaks MXMS, unfortunately, which relies on things like Tuple[...]
449             # creating new type objects each time.
450             # if (my $existing =
451             # Moose::Util::TypeConstraints::find_type_constraint($parameterized->name)) {
452             # return $existing;
453             # }
454             # Moose::Util::TypeConstraints::register_type_constraint($parameterized);
455 23         16342 return $parameterized;
456             }
457              
458             #pod =head2 create_base_type_constraint ($name)
459             #pod
460             #pod Given a String $name, find the matching type constraint.
461             #pod
462             #pod =cut
463              
464             sub create_base_type_constraint {
465 274     354 1 499 my ($class, $name) = @_;
466 274         802 return find_type_constraint($name);
467             }
468              
469             #pod =head2 create_type_decorator ($type_constraint)
470             #pod
471             #pod Given a $type_constraint, return a lightweight L<MooseX::Types::TypeDecorator>
472             #pod instance.
473             #pod
474             #pod =cut
475              
476             sub create_type_decorator {
477 273     273 1 405 my ($class, $type_constraint) = @_;
478 273         1126 return MooseX::Types::TypeDecorator->new($type_constraint);
479             }
480              
481             #pod =head2 coercion_export_generator
482             #pod
483             #pod This generates a coercion handler function, e.g. C<to_Int($value)>.
484             #pod
485             #pod =cut
486              
487             sub coercion_export_generator {
488 75     75 1 285 my ($class, $type, $full, $undef_msg) = @_;
489             return sub {
490 12     12   4954 my ($value) = @_;
491              
492             # we need a type object
493 12 50       43 my $tobj = find_type_constraint($full) or croak $undef_msg;
494 12         1499 my $return = $tobj->coerce($value);
495              
496             # non-successful coercion returns false
497 12 100       2455 return unless $tobj->check($return);
498              
499 7         604 return $return;
500             }
501 75         357 }
502              
503             #pod =head2 check_export_generator
504             #pod
505             #pod Generates a constraint check closure, e.g. C<is_Int($value)>.
506             #pod
507             #pod =cut
508              
509             sub check_export_generator {
510 172     172 1 324 my ($class, $type, $full, $undef_msg) = @_;
511             return sub {
512 13     13   7425 my ($value) = @_;
513              
514             # we need a type object
515 13 50       47 my $tobj = find_type_constraint($full) or croak $undef_msg;
516              
517 13         1373 return $tobj->check($value);
518             }
519 172         871 }
520              
521             __END__
522              
523             =pod
524              
525             =encoding UTF-8
526              
527             =head1 NAME
528              
529             MooseX::Types - Organise your Moose types in libraries
530              
531             =head1 VERSION
532              
533             version 0.50
534              
535             =head1 SYNOPSIS
536              
537             =head2 Library Definition
538              
539             package MyLibrary;
540              
541             # predeclare our own types
542             use MooseX::Types -declare => [
543             qw(
544             PositiveInt
545             NegativeInt
546             ArrayRefOfPositiveInt
547             ArrayRefOfAtLeastThreeNegativeInts
548             LotsOfInnerConstraints
549             StrOrArrayRef
550             MyDateTime
551             )
552             ];
553              
554             # import builtin types
555             use MooseX::Types::Moose qw/Int HashRef/;
556              
557             # type definition.
558             subtype PositiveInt,
559             as Int,
560             where { $_ > 0 },
561             message { "Int is not larger than 0" };
562              
563             subtype NegativeInt,
564             as Int,
565             where { $_ < 0 },
566             message { "Int is not smaller than 0" };
567              
568             # type coercion
569             coerce PositiveInt,
570             from Int,
571             via { 1 };
572              
573             # with parameterized constraints.
574              
575             subtype ArrayRefOfPositiveInt,
576             as ArrayRef[PositiveInt];
577              
578             subtype ArrayRefOfAtLeastThreeNegativeInts,
579             as ArrayRef[NegativeInt],
580             where { scalar(@$_) > 2 };
581              
582             subtype LotsOfInnerConstraints,
583             as ArrayRef[ArrayRef[HashRef[Int]]];
584              
585             # with TypeConstraint Unions
586              
587             subtype StrOrArrayRef,
588             as Str|ArrayRef;
589              
590             # class types
591              
592             class_type 'DateTime';
593              
594             # or better
595              
596             class_type MyDateTime, { class => 'DateTime' };
597              
598             coerce MyDateTime,
599             from HashRef,
600             via { DateTime->new(%$_) };
601              
602             1;
603              
604             =head2 Usage
605              
606             package Foo;
607             use Moose;
608             use MyLibrary qw( PositiveInt NegativeInt );
609              
610             # use the exported constants as type names
611             has 'bar',
612             isa => PositiveInt,
613             is => 'rw';
614             has 'baz',
615             isa => NegativeInt,
616             is => 'rw';
617              
618             sub quux {
619             my ($self, $value);
620              
621             # test the value
622             print "positive\n" if is_PositiveInt($value);
623             print "negative\n" if is_NegativeInt($value);
624              
625             # coerce the value, NegativeInt doesn't have a coercion
626             # helper, since it didn't define any coercions.
627             $value = to_PositiveInt($value) or die "Cannot coerce";
628             }
629              
630             1;
631              
632             =head1 DESCRIPTION
633              
634             The type system provided by Moose effectively makes all of its builtin type
635             global, as are any types you declare with Moose. This means that every module
636             that declares a type named C<PositiveInt> is sharing the same type object. This
637             can be a problem when different parts of the code base want to use the same
638             name for different things.
639              
640             This package lets you declare types using short names, but behind the scenes
641             it namespaces all your type declarations, effectively prevent name clashes
642             between packages.
643              
644             This is done by creating a type library module like C<MyApp::Types> and then
645             importing types from that module into other modules.
646              
647             As a side effect, the declaration mechanism allows you to write type names as
648             barewords (really function calls), which catches typos in names at compile
649             time rather than run time.
650              
651             This module also provides some helper functions for using Moose types outside
652             of attribute declarations.
653              
654             If you mix string-based names with types created by this module, it will warn,
655             with a few exceptions. If you are declaring a C<class_type()> or
656             C<role_type()> within your type library, or if you use a fully qualified name
657             like C<"MyApp::Foo">.
658              
659             =head1 LIBRARY DEFINITION
660              
661             A MooseX::Types is just a normal Perl module. Unlike Moose
662             itself, it does not install C<use strict> and C<use warnings> in your
663             class by default, so this is up to you.
664              
665             The only thing a library is required to do is
666              
667             use MooseX::Types -declare => \@types;
668              
669             with C<@types> being a list of types you wish to define in this library.
670             This line will install a proper base class in your package as well as the
671             full set of L<handlers|/"TYPE HANDLER FUNCTIONS"> for your declared
672             types. It will then hand control over to L<Moose::Util::TypeConstraints>'
673             C<import> method to export the functions you will need to declare your
674             types.
675              
676             If you want to use Moose' built-in types (e.g. for subtyping) you will
677             want to
678              
679             use MooseX::Types::Moose @types;
680              
681             to import the helpers from the shipped L<MooseX::Types::Moose>
682             library which can export all types that come with Moose.
683              
684             You will have to define coercions for your types or your library won't
685             export a L</to_$type> coercion helper for it.
686              
687             Note that you currently cannot define types containing C<::>, since
688             exporting would be a problem.
689              
690             You also don't need to use C<warnings> and C<strict>, since the
691             definition of a library automatically exports those.
692              
693             =head1 LIBRARY USAGE
694              
695             You can import the L<"type helpers"|/"TYPE HANDLER FUNCTIONS"> of a
696             library by C<use>ing it with a list of types to import as arguments. If
697             you want all of them, use the C<:all> tag. For example:
698              
699             use MyLibrary ':all';
700             use MyOtherLibrary qw( TypeA TypeB );
701              
702             MooseX::Types comes with a library of Moose' built-in types called
703             L<MooseX::Types::Moose>.
704              
705             The exporting mechanism is, since version 0.5, implemented via a wrapper
706             around L<Sub::Exporter>. This means you can do something like this:
707              
708             use MyLibrary TypeA => { -as => 'MyTypeA' },
709             TypeB => { -as => 'MyTypeB' };
710              
711             =head1 TYPE HANDLER FUNCTIONS
712              
713             =head2 $type
714              
715             A constant with the name of your type. It contains the type's fully
716             qualified name. Takes no value, as all constants.
717              
718             =head2 is_$type
719              
720             This handler takes a value and tests if it is a valid value for this
721             C<$type>. It will return true or false.
722              
723             =head2 to_$type
724              
725             A handler that will take a value and coerce it into the C<$type>. It will
726             return a false value if the type could not be coerced.
727              
728             B<Important Note>: This handler will only be exported for types that can
729             do type coercion. This has the advantage that a coercion to a type that
730             has not defined any coercions will lead to a compile-time error.
731              
732             =head1 WRAPPING A LIBRARY
733              
734             You can define your own wrapper subclasses to manipulate the behaviour
735             of a set of library exports. Here is an example:
736              
737             package MyWrapper;
738             use strict;
739             use MRO::Compat;
740             use base 'MooseX::Types::Wrapper';
741              
742             sub coercion_export_generator {
743             my $class = shift;
744             my $code = $class->next::method(@_);
745             return sub {
746             my $value = $code->(@_);
747             warn "Coercion returned undef!"
748             unless defined $value;
749             return $value;
750             };
751             }
752              
753             1;
754              
755             This class wraps the coercion generator (e.g., C<to_Int()>) and warns
756             if a coercion returned an undefined value. You can wrap any library
757             with this:
758              
759             package Foo;
760             use strict;
761             use MyWrapper MyLibrary => [qw( Foo Bar )],
762             Moose => [qw( Str Int )];
763              
764             ...
765             1;
766              
767             The C<Moose> library name is a special shortcut for L<MooseX::Types::Moose>.
768              
769             =head2 Generator methods you can overload
770              
771             =over 4
772              
773             =item type_export_generator( $short, $full )
774              
775             Creates a closure returning the type's L<Moose::Meta::TypeConstraint> object.
776              
777             =item check_export_generator( $short, $full, $undef_message )
778              
779             This creates the closure used to test if a value is valid for this type.
780              
781             =item coercion_export_generator( $short, $full, $undef_message )
782              
783             This is the closure that's doing coercions.
784              
785             =back
786              
787             =head2 Provided Parameters
788              
789             =over 4
790              
791             =item $short
792              
793             The short, exported name of the type.
794              
795             =item $full
796              
797             The fully qualified name of this type as L<Moose> knows it.
798              
799             =item $undef_message
800              
801             A message that will be thrown when type functionality is used but the
802             type does not yet exist.
803              
804             =back
805              
806             =head1 RECURSIVE SUBTYPES
807              
808             As of version 0.08, L<Moose::Types> has experimental support for Recursive
809             subtypes. This will allow:
810              
811             subtype Tree() => as HashRef[Str|Tree];
812              
813             Which validates things like:
814              
815             {key=>'value'};
816             {key=>{subkey1=>'value', subkey2=>'value'}}
817              
818             And so on. This feature is new and there may be lurking bugs so don't be afraid
819             to hunt me down with patches and test cases if you have trouble.
820              
821             =head1 NOTES REGARDING TYPE UNIONS
822              
823             L<MooseX::Types> uses L<MooseX::Types::TypeDecorator> to do some overloading
824             which generally allows you to easily create union types:
825              
826             subtype StrOrArrayRef,
827             as Str|ArrayRef;
828              
829             As with parameterized constraints, this overloading extends to modules using the
830             types you define in a type library.
831              
832             use Moose;
833             use MooseX::Types::Moose qw(HashRef Int);
834              
835             has 'attr' => ( isa => HashRef | Int );
836              
837             And everything should just work as you'd think.
838              
839             =head1 METHODS
840              
841             =head2 import
842              
843             Installs the L<MooseX::Types::Base> class into the caller and exports types
844             according to the specification described in L</"LIBRARY DEFINITION">. This
845             will continue to L<Moose::Util::TypeConstraints>' C<import> method to export
846             helper functions you will need to declare your types.
847              
848             =head2 type_export_generator
849              
850             Generate a type export, e.g. C<Int()>. This will return either a
851             L<Moose::Meta::TypeConstraint> object, or alternatively a
852             L<MooseX::Types::UndefinedType> object if the type was not yet defined.
853              
854             =head2 create_arged_type_constraint ($name, @args)
855              
856             Given a String $name with @args find the matching type constraint and parameterize
857             it with @args.
858              
859             =head2 create_base_type_constraint ($name)
860              
861             Given a String $name, find the matching type constraint.
862              
863             =head2 create_type_decorator ($type_constraint)
864              
865             Given a $type_constraint, return a lightweight L<MooseX::Types::TypeDecorator>
866             instance.
867              
868             =head2 coercion_export_generator
869              
870             This generates a coercion handler function, e.g. C<to_Int($value)>.
871              
872             =head2 check_export_generator
873              
874             Generates a constraint check closure, e.g. C<is_Int($value)>.
875              
876             =head1 CAVEATS
877              
878             The following are lists of gotchas and their workarounds for developers coming
879             from the standard string based type constraint names
880              
881             =head2 Uniqueness
882              
883             A library makes the types quasi-unique by prefixing their names with (by
884             default) the library package name. If you're only using the type handler
885             functions provided by MooseX::Types, you shouldn't ever have to use
886             a type's actual full name.
887              
888             =head2 Argument separation ('=>' versus ',')
889              
890             The L<perlop> manpage has this to say about the '=>' operator: "The => operator is
891             a synonym for the comma, but forces any word (consisting entirely of word
892             characters) to its left to be interpreted as a string (as of 5.001). This
893             includes words that might otherwise be considered a constant or function call."
894              
895             Due to this stringification, the following will NOT work as you might think:
896              
897             subtype StrOrArrayRef => as Str | ArrayRef;
898              
899             The C<StrOrArrayRef> type will have its stringification activated -- this causes the
900             subtype to not be created. Since the bareword type constraints are not strings
901             you really should not try to treat them that way. You will have to use the ','
902             operator instead. The authors of this package realize that all the L<Moose>
903             documentation and examples nearly uniformly use the '=>' version of the comma
904             operator and this could be an issue if you are converting code.
905              
906             Patches welcome for discussion.
907              
908             =head2 Compatibility with Sub::Exporter
909              
910             If you want to use L<Sub::Exporter> with a Type Library, you need to make sure
911             you export all the type constraints declared AS WELL AS any additional export
912             targets. For example if you do:
913              
914             package TypeAndSubExporter;
915              
916             use MooseX::Types::Moose qw(Str);
917             use MooseX::Types -declare => [qw(MyStr)];
918             use Sub::Exporter -setup => { exports => [qw(something)] };
919              
920             subtype MyStr, as Str;
921              
922             sub something {
923             return 1;
924             }
925              
926             # then in another module ...
927              
928             package Foo;
929             use TypeAndSubExporter qw(MyStr);
930              
931             You'll get a C<< "MyStr" is not exported by the TypeAndSubExporter module >> error.
932             It can be worked around by:
933              
934             - use Sub::Exporter -setup => { exports => [ qw(something) ] };
935             + use Sub::Exporter -setup => { exports => [ qw(something MyStr) ] };
936              
937             This is a workaround and I am exploring how to make these modules work better
938             together. I realize this workaround will lead a lot of duplication in your
939             export declarations and will be onerous for large type libraries. Patches and
940             detailed test cases welcome. See the tests directory for a start on this.
941              
942             =head1 COMBINING TYPE LIBRARIES
943              
944             You may want to combine a set of types for your application with other type
945             libraries, like L<MooseX::Types::Moose> or L<MooseX::Types::Common::String>.
946              
947             The L<MooseX::Types::Combine> module provides a simple API for combining a set
948             of type libraries together.
949              
950             =head1 SEE ALSO
951              
952             L<Moose>, L<Moose::Util::TypeConstraints>, L<MooseX::Types::Moose>,
953             L<Sub::Exporter>
954              
955             =head1 ACKNOWLEDGEMENTS
956              
957             Many thanks to the C<#moose> cabal on C<irc.perl.org>.
958              
959             =head1 SUPPORT
960              
961             Bugs may be submitted through L<the RT bug tracker|https://rt.cpan.org/Public/Dist/Display.html?Name=MooseX-Types>
962             (or L<bug-MooseX-Types@rt.cpan.org|mailto:bug-MooseX-Types@rt.cpan.org>).
963              
964             There is also a mailing list available for users of this distribution, at
965             L<http://lists.perl.org/list/moose.html>.
966              
967             There is also an irc channel available for users of this distribution, at
968             L<C<#moose> on C<irc.perl.org>|irc://irc.perl.org/#moose>.
969              
970             =head1 AUTHOR
971              
972             Robert "phaylon" Sedlacek <rs@474.at>
973              
974             =head1 CONTRIBUTORS
975              
976             =for stopwords Karen Etheridge Dave Rolsky John Napiorkowski Robert 'phaylon' Sedlacek Rafael Kitover Florian Ragwitz Matt S Trout Tomas Doran (t0m) Jesse Luehrs Mark Fowler Hans Dieter Pearcey Graham Knop Paul Fenwick Kent Fredric Justin Hunter
977              
978             =over 4
979              
980             =item *
981              
982             Karen Etheridge <ether@cpan.org>
983              
984             =item *
985              
986             Dave Rolsky <autarch@urth.org>
987              
988             =item *
989              
990             John Napiorkowski <jjnapiork@cpan.org>
991              
992             =item *
993              
994             Robert 'phaylon' Sedlacek <phaylon@cpan.org>
995              
996             =item *
997              
998             Rafael Kitover <rkitover@cpan.org>
999              
1000             =item *
1001              
1002             Florian Ragwitz <rafl@debian.org>
1003              
1004             =item *
1005              
1006             Matt S Trout <mst@shadowcat.co.uk>
1007              
1008             =item *
1009              
1010             Tomas Doran (t0m) <bobtfish@bobtfish.net>
1011              
1012             =item *
1013              
1014             Jesse Luehrs <doy@tozt.net>
1015              
1016             =item *
1017              
1018             Mark Fowler <mark@twoshortplanks.com>
1019              
1020             =item *
1021              
1022             Hans Dieter Pearcey <hdp@weftsoar.net>
1023              
1024             =item *
1025              
1026             Graham Knop <haarg@haarg.org>
1027              
1028             =item *
1029              
1030             Paul Fenwick <pjf@perltraining.com.au>
1031              
1032             =item *
1033              
1034             Kent Fredric <kentfredric@gmail.com>
1035              
1036             =item *
1037              
1038             Justin Hunter <justin.d.hunter@gmail.com>
1039              
1040             =back
1041              
1042             =head1 COPYRIGHT AND LICENCE
1043              
1044             This software is copyright (c) 2007 by Robert "phaylon" Sedlacek.
1045              
1046             This is free software; you can redistribute it and/or modify it under
1047             the same terms as the Perl 5 programming language system itself.
1048              
1049             =cut