Some more changes needed by the controller reflector, no tests for them yet
[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',
4e8f668c 9 roles => ['CatalystX::ModelToControllerReflector::ControllerRole'],
53a42ae0 10};
59fc9d16 11
cbc455a6 12requires 'setup_components';
59fc9d16 13
cbc455a6 14after 'setup_components' => sub { shift->_setup_dynamic_controllers(@_); };
59fc9d16 15
16sub _setup_dynamic_controllers {
17 my ($app) = @_;
18 my @model_names = grep { /::Model::/ } keys %{ $app->components };
00b934f1 19
59fc9d16 20 foreach my $model_name (@model_names) {
6a2f1e96 21 $app->_reflect_model_to_controller( $model_name, $app->components->{$model_name} );
59fc9d16 22 }
23}
24
6a2f1e96 25sub _reflect_model_to_controller {
26 my ( $app, $model_name, $model ) = @_;
27
77e54b00 28 my $class = blessed($app) || $app;
29
6a2f1e96 30 my $controller_name = $model_name;
31 $controller_name =~ s/::Model::/::Controller::/;
32
77e54b00 33 my $suffix = $model_name;
34 $suffix =~ s/^.*::Model:://;
35
549d6abc 36 my %controller_methods;
37 my $model_methods = $model->meta->get_method_map;
549d6abc 38 foreach my $method_name (keys %$model_methods) {
abcde601 39 next unless does_role($model_methods->{$method_name}, 'CatalystX::ControllerGeneratingModel::DispatchableMethod');
77e54b00 40 # Note need to pass model name, as the method actually comes from
41 # the underlying model class, not the Catalyst shim class we autogenerated.
549d6abc 42 $controller_methods{$method_name} = $app->generate_reflected_controller_action_method($suffix, $model_methods->{$method_name})
77e54b00 43 }
549d6abc 44
0b07685c 45 my $config_name = $controller_name;
46 $config_name =~ s/^[^:]+:://;
4e8f668c 47
48 # Shallow copy so we don't stuff method refs in config
49 my $config = { %{$app->config->{$config_name}} };
50
c52d8688 51 $config->{methods} = \%controller_methods;
52 $app->_setup_dynamic_controller( $controller_name, $config );
2f61148c 53}
54
77e54b00 55sub generate_reflected_controller_action_method {
56 my ( $app, $model, $method ) = @_;
57 my $method_name = $method->name; # Is it worth passing the actual method object here?
58 sub {
59 my ($self, $c, @args) = @_;
60 $c->res->header('X-From-Model', $model);
61 $c->res->header('X-From-Model-Data', $c->model($model)->$method_name(@args));
62 $c->res->body('OK');
63 };
59fc9d16 64}
65
661;
67