File: MethodProxy.pm

package info (click to toggle)
libdata-methodproxy-perl 0.05-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 116 kB
  • sloc: perl: 267; makefile: 2
file content (245 lines) | stat: -rw-r--r-- 5,704 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package Data::MethodProxy;
use 5.008001;
use strict;
use warnings;
our $VERSION = '0.05';

=encoding utf8

=head1 NAME

Data::MethodProxy - Inject dynamic data into static data.

=head1 SYNOPSIS

    use Data::MethodProxy;
    
    my $mproxy = Data::MethodProxy->new();
    
    my $output = $mproxy->render({
        half_six => ['$proxy', 'main', 'half', 6],
    });
    # { half_six => 3 }
    
    sub half {
        my ($class, $number) = @_;
        return $number / 2;
    }

=head1 DESCRIPTION

A method proxy is an array ref describing a class method to call and the
arguments to pass to it.  The first value of the array ref is the scalar
C<$proxy>, followed by a package name, then a subroutine name which must
callable in the package, and a list of any subroutine arguments.

    [ '$proxy', 'Foo::Bar', 'baz', 123, 4 ]

The above is saying, do this:

    Foo::Bar->baz( 123, 4 );

The L</render> method is the main entry point for replacing all found
method proxies in an arbitrary data structure with the return value of
calling the methods.

=head2 Example

Consider this static YAML configuration:

    ---
    db:
        dsn: DBI:mysql:database=foo
        username: bar
        password: abc123

Putting your database password inside of a configuration file is usually
considered a bad practice.  You can use a method proxy to get around this
without jumping through a bunch of hoops:

    ---
    db:
        dsn: DBI:mysql:database=foo
        username: bar
        password:
            - $proxy
            - MyApp::Config
            - get_db_password
            - foo-bar

When L</render> is called on the above data structure it will
see the method proxy and will replace the array ref with the
return value of calling the method.

A method proxy, in Perl syntax, looks like this:

    ['$proxy', $package, $method, @args]

The C<$proxy> string can also be written as C<&proxy>.  The above is then
converted to a method call and replaced by the return value of the method call:

    $package->$method( @args );

In the above database password example the method call would be this:

    MyApp::Config->get_db_password( 'foo-bar' );

You'd still need to create a C<MyApp::Config> package, and add a
C<get_db_password> method to it.

=cut

use Scalar::Util qw( refaddr );
use Module::Runtime qw( require_module is_module_name );
use Carp qw( croak );

sub new {
    my $class = shift;
    my $self = bless {}, $class;
    return $self;
}

our $FOUND_DATA;

=head1 METHODS

=head2 render

    my $output = $mproxy->render( $input );

Traverses the supplied data looking for method proxies, calling them, and
replacing them with the return value of the method call.  Any value may be
passed, such as a hash ref, an array ref, a method proxy, an object, a scalar,
etc.  Array and hash refs will be recursively searched for method proxies.

If a circular reference is detected an error will be thrown.

=cut

sub render {
    my ($self, $data) = @_;

    return $data if !ref $data;

    local $FOUND_DATA = {} if !$FOUND_DATA;

    my $refaddr = refaddr( $data );
    if ($FOUND_DATA->{$refaddr}) {
        local $Carp::Internal{ (__PACKAGE__) } = 1;
        croak 'Circular reference detected in data passed to render()';
    }
    $FOUND_DATA->{$refaddr} = 1;

    if (ref($data) eq 'HASH') {
        return {
            map { $_ => $self->render( $data->{$_} ) }
            keys( %$data )
        };
    }
    elsif (ref($data) eq 'ARRAY') {
        if ($self->is_valid( $data )) {
            return $self->call( $data );
        }

        return [
            map { $self->render( $_ ) }
            @$data
        ];
    }

    return $data;
}

=head2 call

    my $return = $mproxy->call( ['$proxy', $package, $method, @args] );

Calls the method proxy and returns its return.

=cut

sub call {
    my ($self, $proxy) = @_;

    {
        local $Carp::Internal{ (__PACKAGE__) } = 1;
        croak 'Invalid method proxy passed to call()' if !$self->is_valid( $proxy );
        croak 'Uncallable method proxy passed to call()' if !$self->is_callable( $proxy );
    }

    my ($marker, $package, $method, @args) = @$proxy;
    require_module( $package );
    return $package->$method( @args );
}

=head2 is_valid

    die unless $mproxy->is_valid( ... );

Returns true if the passed value looks like a method proxy.

=cut

sub is_valid {
    my ($self, $proxy) = @_;

    return 0 if ref($proxy) ne 'ARRAY';
    my ($marker, $package, $method, @args) = @$proxy;

    return 0 if !defined $marker;
    return 0 if $marker !~ m{^[&\$]proxy$};
    return 0 if !defined $package;
    return 0 if !defined $method;

    return 1;
}

=head2 is_callable

    die unless $mproxy->is_callable( ... );

Returns true if the passed value looks like a method proxy,
and has a package and method which exist.

=cut

sub is_callable {
    my ($self, $proxy) = @_;

    return 0 if !$self->is_valid( $proxy );
    my ($marker, $package, $method, @args) = @$proxy;

    return 0 if !is_module_name( $package );
    return 0 if !$package->can( $method );

    return 1;
}

1;
__END__

=head1 SUPPORT

Please submit bugs and feature requests to the
Data-MethodProxy GitHub issue tracker:

L<https://github.com/bluefeet/Data-MethodProxy/issues>

=head1 ACKNOWLEDGEMENTS

Thanks to L<ZipRecruiter|https://www.ziprecruiter.com/>
for encouraging their employees to contribute back to the open
source ecosystem.  Without their dedication to quality software
development this distribution would not exist.

=head1 AUTHORS

    Aran Clary Deltac <bluefeet@gmail.com>

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut