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