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