Move attribute triggers from Moose, breaking no compatibility
[gitmo/Class-MOP.git] / lib / Class / MOP / Method / Constructor.pm
1
2 package Class::MOP::Method::Constructor;
3
4 use strict;
5 use warnings;
6
7 use Carp         'confess';
8 use Scalar::Util 'blessed', 'weaken', 'looks_like_number';
9
10 our $VERSION   = '0.91';
11 $VERSION = eval $VERSION;
12 our $AUTHORITY = 'cpan:STEVAN';
13
14 use base 'Class::MOP::Method::Inlined';
15
16 sub new {
17     my $class   = shift;
18     my %options = @_;
19
20     (blessed $options{metaclass} && $options{metaclass}->isa('Class::MOP::Class'))
21         || confess "You must pass a metaclass instance if you want to inline"
22             if $options{is_inline};
23
24     ($options{package_name} && $options{name})
25         || confess "You must supply the package_name and name parameters $Class::MOP::Method::UPGRADE_ERROR_TEXT";
26
27     my $self = $class->_new(\%options);
28
29     # we don't want this creating
30     # a cycle in the code, if not
31     # needed
32     weaken($self->{'associated_metaclass'});
33
34     $self->_initialize_body;
35
36     return $self;
37 }
38
39 sub _new {
40     my $class = shift;
41
42     return Class::MOP::Class->initialize($class)->new_object(@_)
43         if $class ne __PACKAGE__;
44
45     my $params = @_ == 1 ? $_[0] : {@_};
46
47     return bless {
48         # inherited from Class::MOP::Method
49         body                 => $params->{body},
50         # associated_metaclass => $params->{associated_metaclass}, # overriden
51         package_name         => $params->{package_name},
52         name                 => $params->{name},
53         original_method      => $params->{original_method},
54
55         # inherited from Class::MOP::Generated
56         is_inline            => $params->{is_inline} || 0,
57         definition_context   => $params->{definition_context},
58
59         # inherited from Class::MOP::Inlined
60         _expected_method_class => $params->{_expected_method_class},
61
62         # defined in this subclass
63         options              => $params->{options} || {},
64         associated_metaclass => $params->{metaclass},
65     }, $class;
66 }
67
68 ## accessors
69
70 sub options              { (shift)->{'options'}              }
71 sub associated_metaclass { (shift)->{'associated_metaclass'} }
72
73 ## cached values ...
74
75 sub meta_instance {
76     Carp::cluck('The meta_instance method has been made private.'
77         . " The public version is deprecated and will be removed in a future release.\n");
78     shift->_meta_instance;
79 }
80
81 sub _meta_instance {
82     my $self = shift;
83     $self->{'meta_instance'} ||= $self->associated_metaclass->get_meta_instance;
84 }
85
86 sub attributes {
87     Carp::cluck('The attributes method has been made private.'
88         . " The public version is deprecated and will be removed in a future release.\n");
89
90     return shift->_attributes;
91 }
92
93 sub _attributes {
94     my $self = shift;
95     $self->{'attributes'} ||= [ $self->associated_metaclass->get_all_attributes ]
96 }
97
98 ## method
99
100 sub initialize_body {
101     Carp::cluck('The initialize_body method has been made private.'
102         . " The public version is deprecated and will be removed in a future release.\n");
103     shift->_initialize_body;
104 }
105
106 sub _initialize_body {
107     my $self        = shift;
108     my $method_name = '_generate_constructor_method';
109
110     $method_name .= '_inline' if $self->is_inline;
111
112     $self->{'body'} = $self->$method_name;
113 }
114
115 sub generate_constructor_method {
116     Carp::cluck('The generate_constructor_method method has been made private.'
117         . " The public version is deprecated and will be removed in a future release.\n");
118     shift->_generate_constructor_method;
119 }
120
121 sub _generate_constructor_method {
122     return sub { Class::MOP::Class->initialize(shift)->new_object(@_) }
123 }
124
125 sub _inline_set_slot_value{
126     my($self,$attr, $instance, $attr_var, $value) = @_;
127
128     if($attr->has_trigger){
129         return sprintf q{ my $value = %s; %s->call_trigger(%s, $value); },
130             $self->_meta_instance->inline_set_slot_value($instance, $attr->name, $value),
131             $attr_var, $instance, $value;
132     }
133     else{
134         return $self->_meta_instance->inline_set_slot_value($instance, $attr->name, $value);
135     }
136 }
137
138 sub generate_constructor_method_inline {
139     Carp::cluck('The generate_constructor_method_inline method has been made private.'
140         . " The public version is deprecated and will be removed in a future release.\n");
141     shift->_generate_constructor_method_inline;
142 }
143
144 sub _generate_constructor_method_inline {
145     my $self = shift;
146
147     my $close_over = {};
148
149     my $source = 'sub {';
150     $source .= "\n" . 'my $class = shift;';
151
152     $source .= "\n" . 'return Class::MOP::Class->initialize($class)->new_object(@_)';
153     $source .= "\n" . '    if $class ne \'' . $self->associated_metaclass->name . '\';';
154
155     $source .= "\n" . 'my $params = @_ == 1 ? $_[0] : {@_};';
156
157     $source .= "\n" . 'my $instance = ' . $self->_meta_instance->inline_create_instance('$class');
158     $source .= ";\n" . (join ";\n" => map {
159         $self->_generate_slot_initializer($_, $close_over)
160     } @{ $self->_attributes });
161     $source .= ";\n" . 'return $instance';
162     $source .= ";\n" . '}';
163     warn $source if $self->options->{debug};
164
165     my ( $code, $e ) = $self->_eval_closure(
166         $close_over,
167         $source
168     );
169     confess "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$e" if $e;
170
171     return $code;
172 }
173
174 sub _generate_slot_initializer {
175     my $self  = shift;
176     my $attr  = shift;
177     my $close = shift;
178
179
180     my $attr_var = do{
181         my $attrs = ($close->{'@attrs'} ||= []);
182         push @{$attrs}, $attr;
183         sprintf q{$attrs[%d]}, scalar(@{$attrs}) - 1;
184     };
185
186     my $default;
187     if ($attr->has_default) {
188         # NOTE:
189         # default values can either be CODE refs
190         # in which case we need to call them. Or
191         # they can be scalars (strings/numbers)
192         # in which case we can just deal with them
193         # in the code we eval.
194         if ($attr->is_default_a_coderef) {
195             my $idx = @{$close->{'@defaults'}||=[]};
196             push(@{$close->{'@defaults'}}, $attr->default);
197             $default = '$defaults[' . $idx . ']->($instance)';
198         }
199         else {
200             $default = $attr->default;
201             # make sure to quote strings ...
202             unless (looks_like_number($default)) {
203                 $default = "'$default'";
204             }
205         }
206     } elsif( $attr->has_builder ) {
207         $default = '$instance->'.$attr->builder;
208     }
209
210     if ( defined(my $init_arg = $attr->init_arg) ) {
211       return (
212           'if(exists $params->{\'' . $init_arg . '\'}){' . "\n" .
213                 $self->_inline_set_slot_value(
214                     $attr,
215                     '$instance',
216                     $attr_var,
217                     '$params->{\'' . $init_arg . '\'}' ) . "\n" .
218            '} ' . (!defined $default ? '' : 'else {' . "\n" .
219                 $self->_inline_set_slot_value(
220                     $attr,
221                     '$instance',
222                     $attr_var,
223                      $default ) . "\n" .
224            '}')
225         );
226     } elsif ( defined $default ) {
227         return (
228             $self->_inline_set_slot_value(
229                 $attr,
230                 '$instance',
231                 $attr_var,
232                  $default ) . "\n"
233         );
234     } else { return '' }
235 }
236
237 1;
238
239 __END__
240
241 =pod
242
243 =head1 NAME
244
245 Class::MOP::Method::Constructor - Method Meta Object for constructors
246
247 =head1 SYNOPSIS
248
249   use Class::MOP::Method::Constructor;
250
251   my $constructor = Class::MOP::Method::Constructor->new(
252       metaclass => $metaclass,
253       options   => {
254           debug => 1, # this is all for now
255       },
256   );
257
258   # calling the constructor ...
259   $constructor->body->execute($metaclass->name, %params);
260
261 =head1 DESCRIPTION
262
263 This is a subclass of C<Class::MOP::Method> which generates
264 constructor methods.
265
266 =head1 METHODS
267
268 =over 4
269
270 =item B<< Class::MOP::Method::Constructor->new(%options) >>
271
272 This creates a new constructor object. It accepts a hash reference of
273 options.
274
275 =over 8
276
277 =item * metaclass
278
279 This should be a L<Class::MOP::Class> object. It is required.
280
281 =item * name
282
283 The method name (without a package name). This is required.
284
285 =item * package_name
286
287 The package name for the method. This is required.
288
289 =item * is_inline
290
291 This indicates whether or not the constructor should be inlined. This
292 defaults to false.
293
294 =back
295
296 =item B<< $metamethod->is_inline >>
297
298 Returns a boolean indicating whether or not the constructor is
299 inlined.
300
301 =item B<< $metamethod->associated_metaclass >>
302
303 This returns the L<Class::MOP::Class> object for the method.
304
305 =back
306
307 =head1 AUTHORS
308
309 Stevan Little E<lt>stevan@iinteractive.comE<gt>
310
311 =head1 COPYRIGHT AND LICENSE
312
313 Copyright 2006-2009 by Infinity Interactive, Inc.
314
315 L<http://www.iinteractive.com>
316
317 This library is free software; you can redistribute it and/or modify
318 it under the same terms as Perl itself.
319
320 =cut
321