c1e614a544b38c88c3aa205e77012e587aea3fa6
[gitmo/Mouse.git] / lib / Mouse / Meta / Class.pm
1 package Mouse::Meta::Class;
2 use strict;
3 use warnings;
4
5 use Scalar::Util qw/blessed weaken/;
6
7 use Mouse::Util qw/get_linear_isa not_supported/;
8
9 use Mouse::Meta::Method::Constructor;
10 use Mouse::Meta::Method::Destructor;
11 use Mouse::Meta::Module;
12
13 use base qw(Mouse::Meta::Module);
14
15 sub method_metaclass(){ 'Mouse::Meta::Method' } # required for get_method()
16
17 sub _construct_meta {
18     my($class, %args) = @_;
19
20     $args{attributes} ||= {};
21     $args{methods}    ||= {};
22     $args{roles}      ||= [];
23
24     $args{superclasses} = do {
25         no strict 'refs';
26         \@{ $args{package} . '::ISA' };
27     };
28
29     #return Mouse::Meta::Class->initialize($class)->new_object(%args)
30     #    if $class ne __PACKAGE__;
31
32     return bless \%args, ref($class) || $class;
33 }
34
35 sub create_anon_class{
36     my $self = shift;
37     return $self->create(undef, @_);
38 }
39
40 sub is_anon_class{
41     return exists $_[0]->{anon_serial_id};
42 }
43
44 sub roles { $_[0]->{roles} }
45
46 sub superclasses {
47     my $self = shift;
48
49     if (@_) {
50         Mouse::load_class($_) for @_;
51         @{ $self->{superclasses} } = @_;
52     }
53
54     return @{ $self->{superclasses} };
55 }
56
57 sub find_method_by_name{
58     my($self, $method_name) = @_;
59     defined($method_name)
60         or $self->throw_error('You must define a method name to find');
61     foreach my $class( $self->linearized_isa ){
62         my $method = $self->initialize($class)->get_method($method_name);
63         return $method if defined $method;
64     }
65     return undef;
66 }
67
68 sub get_all_methods {
69     my($self) = @_;
70     return map{ $self->find_method_by_name($self) } $self->get_all_method_names;
71 }
72
73 sub get_all_method_names {
74     my $self = shift;
75     my %uniq;
76     return grep { $uniq{$_}++ == 0 }
77             map { Mouse::Meta::Class->initialize($_)->get_method_list() }
78             $self->linearized_isa;
79 }
80
81 sub add_attribute {
82     my $self = shift;
83
84     if (@_ == 1 && blessed($_[0])) {
85         my $attr = shift @_;
86         $self->{'attributes'}{$attr->name} = $attr;
87     }
88     else {
89         my $names = shift @_;
90         $names = [$names] if !ref($names);
91         my $metaclass = 'Mouse::Meta::Attribute';
92         my %options   = (@_ == 1 ? %{$_[0]} : @_);
93
94         if ( my $metaclass_name = delete $options{metaclass} ) {
95             my $new_class = Mouse::Util::resolve_metaclass_alias(
96                 'Attribute',
97                 $metaclass_name
98             );
99             if ( $metaclass ne $new_class ) {
100                 $metaclass = $new_class;
101             }
102         }
103
104         for my $name (@$names) {
105             if ($name =~ s/^\+//) {
106                 $metaclass->clone_parent($self, $name, %options);
107             }
108             else {
109                 $metaclass->create($self, $name, %options);
110             }
111         }
112     }
113 }
114
115 sub compute_all_applicable_attributes { shift->get_all_attributes(@_) }
116 sub get_all_attributes {
117     my $self = shift;
118     my (@attr, %seen);
119
120     for my $class ($self->linearized_isa) {
121         my $meta = $self->_metaclass_cache($class)
122             or next;
123
124         for my $name (keys %{ $meta->get_attribute_map }) {
125             next if $seen{$name}++;
126             push @attr, $meta->get_attribute($name);
127         }
128     }
129
130     return @attr;
131 }
132
133 sub linearized_isa { @{ get_linear_isa($_[0]->name) } }
134
135 sub new_object {
136     my $self = shift;
137     my %args = (@_ == 1 ? %{$_[0]} : @_);
138
139     my $instance = bless {}, $self->name;
140
141     my @triggers_queue;
142
143     foreach my $attribute ($self->get_all_attributes) {
144         my $from = $attribute->init_arg;
145         my $key  = $attribute->name;
146
147         if (defined($from) && exists($args{$from})) {
148             $args{$from} = $attribute->coerce_constraint($args{$from})
149                 if $attribute->should_coerce;
150             $attribute->verify_against_type_constraint($args{$from});
151
152             $instance->{$key} = $args{$from};
153
154             weaken($instance->{$key})
155                 if ref($instance->{$key}) && $attribute->is_weak_ref;
156
157             if ($attribute->has_trigger) {
158                 push @triggers_queue, [ $attribute->trigger, $args{$from} ];
159             }
160         }
161         else {
162             if ($attribute->has_default || $attribute->has_builder) {
163                 unless ($attribute->is_lazy) {
164                     my $default = $attribute->default;
165                     my $builder = $attribute->builder;
166                     my $value = $attribute->has_builder
167                               ? $instance->$builder
168                               : ref($default) eq 'CODE'
169                                   ? $default->($instance)
170                                   : $default;
171
172                     $value = $attribute->coerce_constraint($value)
173                         if $attribute->should_coerce;
174                     $attribute->verify_against_type_constraint($value);
175
176                     $instance->{$key} = $value;
177
178                     weaken($instance->{$key})
179                         if ref($instance->{$key}) && $attribute->is_weak_ref;
180                 }
181             }
182             else {
183                 if ($attribute->is_required) {
184                     $self->throw_error("Attribute (".$attribute->name.") is required");
185                 }
186             }
187         }
188     }
189
190     foreach my $trigger_and_value(@triggers_queue){
191         my($trigger, $value) = @{$trigger_and_value};
192         $trigger->($instance, $value);
193     }
194
195     return $instance;
196 }
197
198 sub clone_object {
199     my $class    = shift;
200     my $instance = shift;
201
202     (blessed($instance) && $instance->isa($class->name))
203         || $class->throw_error("You must pass an instance of the metaclass (" . $class->name . "), not ($instance)");
204
205     $class->clone_instance($instance, @_);
206 }
207
208 sub clone_instance {
209     my ($class, $instance, %params) = @_;
210
211     (blessed($instance))
212         || $class->throw_error("You can only clone instances, ($instance) is not a blessed instance");
213
214     my $clone = bless { %$instance }, ref $instance;
215
216     foreach my $attr ($class->get_all_attributes()) {
217         if ( defined( my $init_arg = $attr->init_arg ) ) {
218             if (exists $params{$init_arg}) {
219                 $clone->{ $attr->name } = $params{$init_arg};
220             }
221         }
222     }
223
224     return $clone;
225
226 }
227
228 sub make_immutable {
229     my $self = shift;
230     my %args = (
231         inline_constructor => 1,
232         inline_destructor  => 1,
233         @_,
234     );
235
236     $self->{is_immutable}++;
237
238     if ($args{inline_constructor}) {
239         $self->add_method('new' => Mouse::Meta::Method::Constructor->generate_constructor_method_inline( $self ));
240     }
241
242     if ($args{inline_destructor}) {
243         $self->add_method('DESTROY' => Mouse::Meta::Method::Destructor->generate_destructor_method_inline( $self ));
244     }
245
246     # Moose's make_immutable returns true allowing calling code to skip setting an explicit true value
247     # at the end of a source file. 
248     return 1;
249 }
250
251 sub make_mutable { not_supported }
252
253 sub is_immutable {  $_[0]->{is_immutable} }
254 sub is_mutable   { !$_[0]->{is_immutable} }
255
256 sub _install_modifier {
257     my ( $self, $into, $type, $name, $code ) = @_;
258
259     # which is modifer class available?
260     my $modifier_class = do {
261         if (eval "require Class::Method::Modifiers::Fast; 1") {
262             'Class::Method::Modifiers::Fast';
263         } elsif (eval "require Class::Method::Modifiers; 1") {
264             'Class::Method::Modifiers';
265         } else {
266             Carp::croak("Method modifiers require the use of Class::Method::Modifiers or Class::Method::Modifiers::Fast. Please install it from CPAN and file a bug report with this application.");
267         }
268     };
269     my $modifier = $modifier_class->can('_install_modifier');
270
271     # replace this method itself :)
272     {
273         no warnings 'redefine';
274         *_install_modifier = sub {
275             my ( $self, $into, $type, $name, $code ) = @_;
276             $modifier->(
277                 $into,
278                 $type,
279                 $name,
280                 $code
281             );
282             $self->{methods}{$name}++; # register it to the method map
283             return;
284         };
285     }
286
287     # call me. for first time.
288     $self->_install_modifier( $into, $type, $name, $code );
289 }
290
291 sub add_before_method_modifier {
292     my ( $self, $name, $code ) = @_;
293     $self->_install_modifier( $self->name, 'before', $name, $code );
294 }
295
296 sub add_around_method_modifier {
297     my ( $self, $name, $code ) = @_;
298     $self->_install_modifier( $self->name, 'around', $name, $code );
299 }
300
301 sub add_after_method_modifier {
302     my ( $self, $name, $code ) = @_;
303     $self->_install_modifier( $self->name, 'after', $name, $code );
304 }
305
306 sub add_override_method_modifier {
307     my ($self, $name, $code) = @_;
308
309     my $package = $self->name;
310
311     my $body = $package->can($name)
312         or $self->throw_error("You cannot override '$name' because it has no super method");
313
314     $self->add_method($name => sub { $code->($package, $body, @_) });
315 }
316
317 sub does_role {
318     my ($self, $role_name) = @_;
319
320     (defined $role_name)
321         || $self->throw_error("You must supply a role name to look for");
322
323     for my $class ($self->linearized_isa) {
324         my $meta = Mouse::Meta::Module::class_of($class);
325         next unless $meta && $meta->can('roles');
326
327         for my $role (@{ $meta->roles }) {
328
329             return 1 if $role->does_role($role_name);
330         }
331     }
332
333     return 0;
334 }
335
336 1;
337
338 __END__
339
340 =head1 NAME
341
342 Mouse::Meta::Class - hook into the Mouse MOP
343
344 =head1 METHODS
345
346 =head2 initialize ClassName -> Mouse::Meta::Class
347
348 Finds or creates a Mouse::Meta::Class instance for the given ClassName. Only
349 one instance should exist for a given class.
350
351 =head2 new %args -> Mouse::Meta::Class
352
353 Creates a new Mouse::Meta::Class. Don't call this directly.
354
355 =head2 name -> ClassName
356
357 Returns the name of the owner class.
358
359 =head2 superclasses -> [ClassName]
360
361 Gets (or sets) the list of superclasses of the owner class.
362
363 =head2 add_attribute (Mouse::Meta::Attribute| name => spec)
364
365 Begins keeping track of the existing L<Mouse::Meta::Attribute> for the owner
366 class.
367
368 =head2 get_all_attributes -> (Mouse::Meta::Attribute)
369
370 Returns the list of all L<Mouse::Meta::Attribute> instances associated with
371 this class and its superclasses.
372
373 =head2 get_attribute_map -> { name => Mouse::Meta::Attribute }
374
375 Returns a mapping of attribute names to their corresponding
376 L<Mouse::Meta::Attribute> objects.
377
378 =head2 get_attribute_list -> { name => Mouse::Meta::Attribute }
379
380 This returns a list of attribute names which are defined in the local
381 class. If you want a list of all applicable attributes for a class,
382 use the C<get_all_attributes> method.
383
384 =head2 has_attribute Name -> Bool
385
386 Returns whether we have a L<Mouse::Meta::Attribute> with the given name.
387
388 =head2 get_attribute Name -> Mouse::Meta::Attribute | undef
389
390 Returns the L<Mouse::Meta::Attribute> with the given name.
391
392 =head2 linearized_isa -> [ClassNames]
393
394 Returns the list of classes in method dispatch order, with duplicates removed.
395
396 =head2 clone_object Instance -> Instance
397
398 Clones the given C<Instance> which must be an instance governed by this
399 metaclass.
400
401 =head2 clone_instance Instance, Parameters -> Instance
402
403 The clone_instance method has been made private.
404 The public version is deprecated.
405
406 =cut
407