Test COMPONENT functionality
[catagits/CatalystX-DynamicComponent.git] / lib / CatalystX / ModelToControllerReflector.pm
CommitLineData
59fc9d16 1package CatalystX::ModelToControllerReflector;
2use Moose::Role;
abcde601 3use Moose::Util qw/does_role/;
279c014c 4use List::MoreUtils qw/uniq/;
046d763d 5use namespace::autoclean;
59fc9d16 6
53a42ae0 7with 'CatalystX::DynamicComponent' => {
8 name => '_setup_dynamic_controller',
9};
59fc9d16 10
cbc455a6 11requires 'setup_components';
59fc9d16 12
cbc455a6 13after 'setup_components' => sub { shift->_setup_dynamic_controllers(@_); };
59fc9d16 14
15sub _setup_dynamic_controllers {
16 my ($app) = @_;
17 my @model_names = grep { /::Model::/ } keys %{ $app->components };
00b934f1 18
59fc9d16 19 foreach my $model_name (@model_names) {
6a2f1e96 20 $app->_reflect_model_to_controller( $model_name, $app->components->{$model_name} );
59fc9d16 21 }
22}
23
6a2f1e96 24sub _reflect_model_to_controller {
25 my ( $app, $model_name, $model ) = @_;
26
77e54b00 27 my $class = blessed($app) || $app;
28
6a2f1e96 29 my $controller_name = $model_name;
30 $controller_name =~ s/::Model::/::Controller::/;
31
77e54b00 32 my $suffix = $model_name;
33 $suffix =~ s/^.*::Model:://;
34
549d6abc 35 my %controller_methods;
36 my $model_methods = $model->meta->get_method_map;
549d6abc 37 foreach my $method_name (keys %$model_methods) {
abcde601 38 next unless does_role($model_methods->{$method_name}, 'CatalystX::ControllerGeneratingModel::DispatchableMethod');
77e54b00 39 # Note need to pass model name, as the method actually comes from
40 # the underlying model class, not the Catalyst shim class we autogenerated.
549d6abc 41 $controller_methods{$method_name} = $app->generate_reflected_controller_action_method($suffix, $model_methods->{$method_name})
77e54b00 42 }
549d6abc 43
0b07685c 44 my $config_name = $controller_name;
45 $config_name =~ s/^[^:]+:://;
279c014c 46 my $config = $app->config->{$config_name};
47 my @roles = @{ $config->{roles}||[] };
48 @roles = uniq @roles, 'CatalystX::ModelToControllerReflector::ControllerRole';
49 $config->{roles} = \@roles;
50 $app->_setup_dynamic_controller( $controller_name, $config, \%controller_methods );
2f61148c 51}
52
77e54b00 53sub generate_reflected_controller_action_method {
54 my ( $app, $model, $method ) = @_;
55 my $method_name = $method->name; # Is it worth passing the actual method object here?
56 sub {
57 my ($self, $c, @args) = @_;
58 $c->res->header('X-From-Model', $model);
59 $c->res->header('X-From-Model-Data', $c->model($model)->$method_name(@args));
60 $c->res->body('OK');
61 };
59fc9d16 62}
63
641;
65