Version 0.31
[gitmo/MooseX-Getopt.git] / lib / MooseX / Getopt / OptionTypeMap.pm
CommitLineData
8034a232 1package MooseX::Getopt::OptionTypeMap;
669588e2 2# ABSTRACT: Storage for the option to type mappings
8034a232 3
365e5784 4use Moose 'confess', 'blessed';
8034a232 5use Moose::Util::TypeConstraints 'find_type_constraint';
6
8034a232 7my %option_type_map = (
8 'Bool' => '!',
9 'Str' => '=s',
10 'Int' => '=i',
d64acebb 11 'Num' => '=f',
8034a232 12 'ArrayRef' => '=s@',
669588e2 13 'HashRef' => '=s%',
8034a232 14);
15
f63e6310 16sub has_option_type {
365e5784 17 my (undef, $type_or_name) = @_;
f63e6310 18
365e5784 19 return 1 if exists $option_type_map{blessed($type_or_name) ? $type_or_name->name : $type_or_name};
20
21 my $current = blessed($type_or_name) ? $type_or_name : find_type_constraint($type_or_name);
669588e2 22
2482085f 23 (defined $current)
365e5784 24 || confess "Could not find the type constraint for '$type_or_name'";
669588e2 25
f63e6310 26 while (my $parent = $current->parent) {
27 return 1 if exists $option_type_map{$parent->name};
28 $current = $parent;
29 }
30
31 return 0;
32}
33
34sub get_option_type {
365e5784 35 my (undef, $type_or_name) = @_;
36
37 my $name = blessed($type_or_name) ? $type_or_name->name : $type_or_name;
f63e6310 38
365e5784 39 return $option_type_map{$name} if exists $option_type_map{$name};
40
41 my $current = ref $type_or_name ? $type_or_name : find_type_constraint($type_or_name);
669588e2 42
2482085f 43 (defined $current)
669588e2 44 || confess "Could not find the type constraint for '$type_or_name'";
365e5784 45
46 while ( $current = $current->parent ) {
47 return $option_type_map{$current->name}
48 if exists $option_type_map{$current->name};
f63e6310 49 }
50
51 return;
52}
53
8034a232 54sub add_option_type_to_map {
55 my (undef, $type_name, $option_string) = @_;
56 (defined $type_name && defined $option_string)
57 || confess "You must supply both a type name and an option string";
365e5784 58
59 if ( blessed($type_name) ) {
60 $type_name = $type_name->name;
61 } else {
62 (find_type_constraint($type_name))
63 || confess "The type constraint '$type_name' does not exist";
64 }
65
8034a232 66 $option_type_map{$type_name} = $option_string;
67}
68
669588e2 69no Moose::Util::TypeConstraints;
70no Moose;
8034a232 71
669588e2 721;
8034a232 73
74=head1 DESCRIPTION
75
76See the I<Custom Type Constraints> section in the L<MooseX::Getopt> docs
77for more info about how to use this module.
78
669588e2 79=method B<has_option_type ($type_or_name)>
8034a232 80
669588e2 81=method B<get_option_type ($type_or_name)>
8034a232 82
669588e2 83=method B<add_option_type_to_map ($type_name, $option_spec)>
8034a232 84
f63e6310 85=cut