this shouldn't be using a base class role at all
[gitmo/MooseX-StrictConstructor.git] / lib / MooseX / StrictConstructor / Trait / Class.pm
CommitLineData
1a4f7732 1package MooseX::StrictConstructor::Trait::Class;
c001451a 2
d99e6f32 3use Moose::Role;
4
5use namespace::autoclean;
c001451a 6
79b37c7d 7use B ();
c001451a 8
709eccb9 9around 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 (map { $_ => 1 }
18 grep { defined }
19 map { $_->init_arg }
20 $self->get_all_attributes)
21 );
22
23 my @bad = sort grep { !$attrs{$_} } keys %$params;
24
25 if (@bad) {
26 $self->throw_error(
27 "Found unknown attribute(s) init_arg passed to the constructor: @bad");
28 }
29
30 return $instance;
31};
32
01265e2a 33around '_inline_BUILDALL' => sub {
64c958ef 34 my $orig = shift;
c001451a 35 my $self = shift;
36
01265e2a 37 my @source = $self->$orig();
c001451a 38
5a0d4921 39 my @attrs = (
df9653e6 40 '__INSTANCE__ => 1,',
79b37c7d 41 map { B::perlstring($_) . ' => 1,' }
5a0d4921 42 grep {defined}
01265e2a 43 map { $_->init_arg() } $self->get_all_attributes()
5a0d4921 44 );
c001451a 45
01265e2a 46 return (
47 @source,
93a34553 48 'my %attrs = (' . ( join ' ', @attrs ) . ');',
01265e2a 49 'my @bad = sort grep { !$attrs{$_} } keys %{ $params };',
50 'if (@bad) {',
714128ef 51 'Moose->throw_error("Found unknown attribute(s) passed to the constructor: @bad");',
01265e2a 52 '}',
53 );
0dc0aea2 54} if $Moose::VERSION >= 1.9900;
c001451a 55
c001451a 561;
58370717 57
0639c294 58# ABSTRACT: A role to make immutable constructors strict
59
58370717 60__END__
61
62=pod
63
58370717 64=head1 DESCRIPTION
65
01265e2a 66This role simply wraps C<_inline_BUILDALL()> (from
67C<Moose::Meta::Class>) so that immutable classes have a
fbfaa61f 68strict constructor.
58370717 69
58370717 70=cut