776953bcce7d0c0fb5b22bc3c885788e79e10082
[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 '_inline_BUILDALL' => sub {
10     my $orig = shift;
11     my $self = shift;
12
13     my @source = $self->$orig();
14
15     my @attrs = (
16         '__INSTANCE__ => 1,',
17         map { B::perlstring($_) . ' => 1,' }
18         grep {defined}
19         map  { $_->init_arg() } $self->get_all_attributes()
20     );
21
22     return (
23         @source,
24         'my %attrs = (' . ( join ' ', @attrs ) . ');',
25         'my @bad = sort grep { !$attrs{$_} } keys %{ $params };',
26         'if (@bad) {',
27             'Moose->throw_error("Found unknown attribute(s) passed to the constructor: @bad");',
28         '}',
29     );
30 };
31
32 # If the base class role is applied first, and then a superclass is added, we
33 # lose the role.
34 after superclasses => sub {
35     my $self = shift;
36     return if not @_;
37     Moose::Util::MetaRole::apply_base_class_roles(
38         for   => $self->name,
39         roles => ['MooseX::StrictConstructor::Role::Object'],
40     );
41 };
42
43 1;
44
45 # ABSTRACT: A role to make immutable constructors strict
46
47 __END__
48
49 =pod
50
51 =head1 DESCRIPTION
52
53 This role simply wraps C<_inline_BUILDALL()> (from
54 C<Moose::Meta::Class>) so that immutable classes have a
55 strict constructor.
56
57 =cut