Commit | Line | Data |
fbb43338 |
1 | use strict; |
2 | use warnings; |
3 | |
4 | use Test::More tests=>15; |
5 | use Moose::Util::TypeConstraints; |
6 | use Moose::Meta::TypeConstraint::Parameterizable; |
7 | use Moose; |
b454ba9e |
8 | use Data::Dump qw/dump/; |
fbb43338 |
9 | |
1e60caec |
10 | ## Sketch for how this could work |
fbb43338 |
11 | ok my $Optional = Moose::Meta::TypeConstraint::Parameterizable->new( |
12 | name => 'Optional', |
13 | package_defined_in => __PACKAGE__, |
14 | parent => find_type_constraint('Item'), |
15 | constraint => sub { 1 }, |
16 | constraint_generator => sub { |
17 | my $type_parameter = shift; |
18 | my $check = $type_parameter->_compiled_type_constraint; |
19 | return sub { |
20 | my (@args) = @_; |
b454ba9e |
21 | warn dump [@args]; |
22 | warn exists $args[0]? "exists":"null"; |
23 | warn defined $args[0]? "defined":"undef"; |
24 | |
fbb43338 |
25 | if(exists($args[0])) { |
26 | ## If it exists, we need to validate it |
27 | $check->($args[0]); |
28 | } else { |
29 | ## But it's is okay if the value doesn't exists |
30 | return 1; |
31 | } |
32 | } |
33 | } |
34 | ); |
35 | |
1e60caec |
36 | Moose::Util::TypeConstraints::register_type_constraint($Optional); |
fbb43338 |
37 | Moose::Util::TypeConstraints::add_parameterizable_type($Optional); |
1e60caec |
38 | ## END SKETCH |
fbb43338 |
39 | |
40 | isa_ok $Optional, 'Moose::Meta::TypeConstraint::Parameterizable'; |
41 | |
1e60caec |
42 | ok my $int = Moose::Util::TypeConstraints::find_or_parse_type_constraint('Int') |
43 | => 'Got Int'; |
fbb43338 |
44 | |
1e60caec |
45 | ok my $arrayref = Moose::Util::TypeConstraints::find_or_parse_type_constraint('ArrayRef[Int]') |
46 | => 'Got ArrayRef[Int]'; |
fbb43338 |
47 | |
1e60caec |
48 | ok my $Optional_Int = $Optional->parameterize($int), 'Parameterized Int'; |
49 | ok my $Optional_ArrayRef = $Optional->parameterize($arrayref), 'Parameterized ArrayRef'; |
fbb43338 |
50 | |
b454ba9e |
51 | $Optional_Int->check(); |
52 | |
53 | die; |
54 | |
fbb43338 |
55 | ok $Optional_Int->check() => 'Optional is allowed to not exist'; |
b454ba9e |
56 | |
fbb43338 |
57 | ok !$Optional_Int->check(undef) => 'Optional is NOT allowed to be undef'; |
58 | ok $Optional_Int->check(199) => 'Correctly validates 199'; |
59 | ok !$Optional_Int->check("a") => 'Correctly fails "a"'; |
60 | |
61 | ok $Optional_ArrayRef->check() => 'Optional is allowed to not exist'; |
62 | ok !$Optional_ArrayRef->check(undef) => 'Optional is NOT allowed to be undef'; |
63 | ok $Optional_ArrayRef->check([1,2,3]) => 'Correctly validates [1,2,3]'; |
64 | ok !$Optional_ArrayRef->check("a") => 'Correctly fails "a"'; |
65 | ok !$Optional_ArrayRef->check(["a","b"]) => 'Correctly fails ["a","b"]'; |