8d8590f1b20d667af8151b9a1f9a07281e4a6636
[gitmo/MooseX-StrictConstructor.git] / lib / MooseX / StrictConstructor / Trait / Method / Constructor.pm
1 package MooseX::StrictConstructor::Trait::Method::Constructor;
2
3 use Moose::Role;
4
5 use namespace::autoclean;
6
7 use B ();
8
9 around _generate_BUILDALL => sub {
10     my $orig = shift;
11     my $self = shift;
12
13     my $source = $self->$orig();
14     $source .= ";\n" if $source;
15
16     my @attrs = '__INSTANCE__ => 1,';
17     push @attrs, map { B::perlstring($_) . ' => 1,' }
18         grep { defined }
19         map  { $_->init_arg() } @{ $self->_attributes() };
20
21
22     $source .= <<"EOF";
23 my \%attrs = (@attrs);
24
25 my \@bad = sort grep { ! \$attrs{\$_} }  keys \%{ \$params };
26
27 if (\@bad) {
28     Moose->throw_error("Found unknown attribute(s) passed to the constructor: \@bad");
29 }
30 EOF
31
32     return $source;
33 } if $Moose::VERSION < 1.9900;
34
35 around _eval_environment => sub {
36     my $orig = shift;
37     my $self = shift;
38
39     my $env = $self->$orig();
40
41     my %attrs = map { $_ => 1 }
42         grep { defined }
43         map  { $_->init_arg() }
44         $self->associated_metaclass()->get_all_attributes();
45
46     $attrs{__INSTANCE__} = 1;
47
48     $env->{'%allowed_attrs'} = \%attrs;
49
50     return $env;
51 } if $Moose::VERSION >= 1.9900;
52
53 1;
54
55 # ABSTRACT: A role to make immutable constructors strict
56
57 __END__
58
59 =pod
60
61 =head1 DESCRIPTION
62
63 This role simply wraps C<_generate_BUILDALL()> (from
64 C<Moose::Meta::Method::Constructor>) so that immutable classes have a
65 strict constructor.
66
67 =cut
68