Transfigure.pm

filter: Statementstmt 75.0% 6 / 8 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 81.8% 9 / 11 CC 1 SCAR 0.9
CC
1
Cov
75%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Transfigure/Type/DateTime/Duration.pm ↑ Summary Transfigure/Default.pm »
1 package Data::Transfigure 1.03;
2 13 ▶use v5.26;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 13 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 # ABSTRACT: performs rule-based data transfigurations of arbitrary structures
6  
7 =encoding UTF-8
8
9 =head1 NAME
10
11 Data::Transfigure - performs rule-based data transfigurations of arbitrary structures
12
13 =head1 SYNOPSIS
14  
15 use Data::Transfigure;
16  
17 my $d = Data::Transfigure->std();
18 $d->add_transfigurators(qw(
19 Data::Transfigure::Type::DateTime::Duration
20 Data::Transfigure::HashKeys::CamelCase
21 ), Data::Transfigure::Type->new(
22 type => 'Activity::Run'.
23 handler => sub ($data) {
24 {
25 start => $data->start_time, # DateTime
26 time => $data->time, # DateTime::Duration
27 distance => $data->distance, # number
28 pace => $data->pace, # DateTime::Duration
29 }
30 }
31 ));
32  
33 my $list = [
34 { user_id => 3, run => Activity::Run->new(...) },
35 { user_id => 4, ride => Activity::Ride->new(...) },
36 ];
37  
38 $d->transfigure($list); # [
39 # {
40 # userID => 3
41 # run => {
42 # start => "2023-05-15T074:11:14",
43 # time => "PT30M5S",
44 # distance => "5",
45 # pace => "PT9M30S",
46 # }
47 # },
48 # {
49 # userID => 4,
50 # ride => "Activity::Ride=HASH(0x2bbd7d16f640)",
51 # },
52 # ]
53  
54 =head1 DESCRIPTION
55  
56 C<Data::Transfigure> allows you to write reusable rules ('transfigurators') to modify
57 parts (or all) of a data structure. There are many possible applications of this,
58 but it was primarily written to handle converting object graphs of ORM objects
59 into a structure that could be converted to JSON and delivered as an API endpoint
60 response. One of the challenges of such a system is being able to reuse code
61 because many different controllers could need to convert the an object type to
62 the same structure, but then other controllers might need to convert that same
63 type to a different structure.
64  
65 A number of transfigurator roles and classes are included with this distribution:
66  
67 =over
68  
69 =item * L<Data::Transfigure::Node>
70 the root role which all transfigurators must implement
71  
72 =item * L<Data::Transfigure::Default>
73 a low priority transfigurator that only applies when no other transfigurators do
74  
75 =item * L<Data::Transfigure::Default::ToString>
76 a transfigurator that stringifies any value that is not otherwise transfigured
77  
78 =item * L<Data::Transfigure::Type>
79 a transfigurator that matches against one or more data types
80  
81 =item * L<Data::Transfigure::Type::DateTime>
82 transfigures DateTime objects to L<ISO8601|https://en.wikipedia.org/wiki/ISO_8601>
83 format.
84  
85 =item * L<Data::Transfigure::Type::DateTime::Duration>
86 transfigures L<DateTime::Duration> objects to
87 L<ISO8601|https://en.wikipedia.org/wiki/ISO_8601#Durations> (duration!) format
88  
89 =item * L<Data::Transfigure::Type::DBIx>
90 transfigures L<DBIx::Class::Row> instances into hashrefs of colname->value
91 pairs. Does not recurse across relationships
92  
93 =item * L<Data::Transfigure::Type::DBIx::Recursive>
94 transfigures L<DBIx::Class::Row> instances into hashrefs of colname->value pairs,
95 recursing down to_one-type relationships
96  
97 =item * L<Data::Transfigure::Value>
98 a transfigurator that matches against data values (exactly, by regex, or by coderef
99 callback)
100  
101 =item * L<Data::Transfigure::Position>
102 a compound transfigurator that specifies one or more locations within the data
103 structure to apply to, in addition to whatever other criteria its transfigurator
104 specifies
105  
106 =item * L<Data::Transfigure::Tree>
107 a transfigurator that is applied to the entire data structure after all
108 node transfigurations have been completed
109  
110 =item * L<Data::Transfigure::HashKeys::CamelCase>
111 a transfigurator that converts all hash keys in the data structure to
112 lowerCamelCase
113  
114 =item * L<Data::Transfigure::HashKeys::SnakeCase>
115 a transfigurator that converts all hash keys in the data structure to
116 snake_case
117  
118 =item * L<Data::Transfigure::HashKeys::CapitalizedIDSuffix>
119 a transfigurator that converts "Id" at the end of hash keys (as results from
120 lowerCamelCase conversion) to "ID"
121  
122 =item * L<Data::Transfigure::HashFilter::Undef>
123 a transfigurator that removes key/value pairs where the value is undefined and
124 the key matches a certain pattern
125  
126 =item * L<Data::Transfigure::Tree::Merge>
127 a transfigurator that expands marked hash keys' HashRef values into the enclosing
128 hash, overwriting common keys
129  
130 =back
131  
132 =cut
133  
134 0 ▶use Object::Pad;
Subroutine BEGIN: called CC=1 SCAR=2.6
135  
136 class Data::Transfigure 1.00 {
137 use Exporter qw(import);
138  
139 use Data::Compare;
140  
141 use Data::Transfigure::Default;
142 use Data::Transfigure::Value;
143 use Data::Transfigure::Position;
144  
145 use Data::Transfigure::Constants;
146  
147 use List::Util qw(max);
148 use Module::Util qw(module_path);
149 use Scalar::Util qw(blessed);
150 use Readonly;
151  
152 field @transfigurators;
153 field @post_transfigurators;
154  
155 our @EXPORT_OK = qw(hk_rewrite_cb concat_position);
156  
157 sub hk_rewrite_cb ($h, $cb) {
158 if (ref($h) eq 'HASH') {
159 foreach (keys($h->%*)) {
160 hk_rewrite_cb($h->{$cb->($_)} = delete($h->{$_}), $cb);
161 }
162 } elsif (ref($h) eq 'ARRAY') {
163 foreach my $o ($h->@*) {
164 hk_rewrite_cb($o, $cb);
165 }
166 }
167 return $h;
168 }
169  
170 sub concat_position ($base, $add) {
171 $base //= q{};
172 $add //= q{};
173 $base =~ s|/+$||;
174 $add =~ s|^/+||;
175 return join('/', ($base eq '/' ? '' : $base, $add));
176 }
177  
178 #<<V perltidy can't handle Object::Pad's lexical methods
179 method $check_frame ($frame, $stack) {
180 foreach my $c (reverse $stack->@*) {
181 return 1 if($c->[0] == $frame->[0] && Compare($c->[1], $frame->[1]));
182 }
183 return 0;
184 }
185  
186 method $get_matching_transfigurator_idx ($data, $path) {
187 my @match;
188 for (my $i = 0 ; $i < @transfigurators ; $i++) {
189 my $v = $transfigurators[$i]->applies_to(value => $data, position => $path);
190 push(@match, {value => $v, index => $i}) if ($v != $NO_MATCH);
191 }
192 return undef unless (@match);
193  
194 my $best_match = max(map {$_->{value}} @match);
195 @match = sort {$b->{index} - $a->{index}} grep {$_->{value} == $best_match} @match;
196 return $match[0]->{index};
197 }
198  
199 method $transfigure ($data, $path, $stack = []) {
200 my ($idx, $frame);
201 if(ref($data) eq 'ARRAY') {
202 $frame = [-2, $data];
203 die("Deep recursion detected in Data::Transfigure::transfigure\n") if($self->$check_frame($frame, $stack));
204 $data = [ map{ __SUB__->($self, $data->[$_], concat_position($path, $_), [$stack->@*, ]) } 0..$#$data ] # transfigure members of array
205 } elsif(ref($data) eq 'HASH') {
206 $frame = [-1, $data];
207 die("Deep recursion detected in Data::Transfigure::transfigure\n") if($self->$check_frame($frame, $stack));
208 $data = { map { $_ => __SUB__->($self, $data->{$_}, concat_position($path, $_), [$stack->@*, $frame]) } keys($data->%*) } # trannsfigure values of hash
209 }
210
211 $idx = $self->$get_matching_transfigurator_idx($data, $path); # transfigure the data item
212 return $data unless(defined($idx));
213  
214 $frame = [$idx, $data];
215 die("Deep recursion detected in Data::Transfigure::transfigure\n") if($self->$check_frame($frame, $stack));
216 $data = $transfigurators[$idx]->transfigure($data);
217 $data = __SUB__->($self, $data, $path, [$stack->@*, $frame]) if (ref($data)); #recursively transfigure the transfigured data item
218 return $data;
219 }
220  
221 method $add_standard_transfigurators () {
222 $self->add_transfigurators(
223 'Data::Transfigure::Default::ToString',
224 Data::Transfigure::Value->new(
225 value => undef,
226 handler => sub ($data) {
227 return undef;
228 }
229 ),
230 );
231 }
232  
233 method $remove_all_transfigurators () {
234 @transfigurators = ();
235 @post_transfigurators = ();
236 }
237 #>>V
238  
239 =pod
240  
241 =head1 CONSTRUCTORS
242  
243 =head2 Data::Transfigure->new()
244  
245 Constructs a new default instance that pre-adds
246 L<Data::Transfigure::Default::ToString> to stringify values that are not otherwise
247 transfigured by user-provided transfigurators. Preserves (does not transfigure to
248 empty string) undefined values.
249  
250 =head2 Data::Transfigure->bare()
251  
252 Returns a "bare-bones" instance that has no builtin data transfigurators.
253  
254 =cut
255  
256 sub bare ($class) {
257 my $t = Data::Transfigure->new();
258 $t->$remove_all_transfigurators();
259 return $t;
260 }
261  
262 =pod
263  
264 =head2 Data::Transfigure->dbix()
265  
266 Adds L<Data::Transfigure::DBIx::Recursive> to to handle C<DBIx::Class> result rows
267  
268 =cut
269  
270 sub dbix ($class) {
271 my $t = $class->new();
272 $t->add_transfigurators('Data::Transfigure::Type::DBIx::Recursive',);
273 return $t;
274 }
275  
276 ADJUST {
277 $self->$add_standard_transfigurators();
278 }
279  
280 =pod
281  
282 =head1 METHODS
283  
284 =head2 add_transfigurators( @list )
285  
286 Registers one or more data transfigurators with the C<Data::Transfigure> instance.
287  
288 $t->add_transfigurators(Data::Transfigure::Type->new(
289 type => 'DateTime',
290 handler => sub ($data) {
291 $data->strftime('%F')
292 }
293 ));
294  
295 Each element of C<@list> must implement the L<Data::Transfigure::Node> role, though
296 these can either be strings containing class names or object instances.
297  
298 C<Data::Transfigure> will automatically load class names passed in this list and
299 construct an object instance from that class. This will fail if the class's C<new>
300 constructor does not exist or has required parameters.
301  
302 $t->add_transfigurators(qw(Data::Transfigure::Type::DateTime Data::Transfigure::Type::DBIx));
303  
304 ArrayRefs passed in this list will be expanded and their contents will be treated
305 the same as any item passed directly to this method.
306  
307 my $default = Data::Transfigure::Type::Default->new(
308 handler => sub ($data) {
309 "[$data]"
310 }
311 );
312 my $bundle = [q(Data::Transfigure::Type::DateTime), $default];
313 $t->add_transfigurators($bundle);
314  
315 When transfiguring data, only one transfigurator will be applied to each data element,
316 prioritizing the most-specific types of matches. Among transfigurators that have
317 equal match types, those added later have priority over those added earlier.
318  
319 =cut
320  
321 method add_transfigurators (@args) {
322 foreach my $t (map {ref($_) eq 'ARRAY' ? $_->@* : $_} @args) {
323 if (!defined($t)) {
324 die("Cannot register undef");
325 } elsif (ref($t)) {
326 die("Cannot register non-Data::Transfigure::Node/Tree implementers ($t)")
327 unless ($t->DOES('Data::Transfigure::Node') || $t->DOES('Data::Transfigure::Tree'));
328 } elsif ($t eq 'Data::Transfigure::Node') {
329 die('Cannot register Role');
330 } else {
331 require(module_path($t));
332 die("Cannot register non-Data::Transfigure::Node/Tree implementers ($t)")
333 unless ($t->DOES('Data::Transfigure::Node') || $t->DOES('Data::Transfigure::Tree'));
334 $t = $t->new() unless (ref($t));
335 }
336 if ($t->DOES('Data::Transfigure::Node')) {
337 push(@transfigurators, $t);
338 } elsif ($t->DOES('Data::Transfigure::Tree')) {
339 push(@post_transfigurators, $t);
340 }
341 }
342 my @all = (@transfigurators, @post_transfigurators);
343 return wantarray ? @all : scalar @all;
344 }
345  
346 =pod
347  
348 =head2 add_transfigurator_at( $position => $transfigurator )
349  
350 C<add_transfigurator_at> is a convenience method for creating and adding a
351 positional transfigurator (one that applies to a specific data-path within the given
352 structure) in a single step.
353  
354 See L<Data::Transfigure::Position> for more on positional transfigurators.
355  
356 =cut
357  
358 method add_transfigurator_at ($position, $transfigurator) {
359 push(
360 @transfigurators,
361 Data::Transfigure::Position->new(
362 position => $position,
363 transfigurator => $transfigurator
364 )
365 );
366 }
367  
368 =pod
369  
370 =head2 transfigure( $data )
371  
372 Transfigures the data according to the transfigurators added to the instance and
373 returns it. The data structure passed to the method is unmodified.
374  
375 =cut
376  
377 method transfigure ($data) {
378 my $d = $self->$transfigure($data, '/');
379 $d = $_->transfigure($d) foreach (@post_transfigurators);
380 return $d;
381 }
382  
383 }
384  
385 =pod
386  
387 =head1 AUTHOR
388  
389 Mark Tyrrell C<< <mark@tyrrminal.dev> >>
390  
391 =head1 LICENSE
392  
393 Copyright (c) 2024 Mark Tyrrell
394  
395 Permission is hereby granted, free of charge, to any person obtaining a copy
396 of this software and associated documentation files (the "Software"), to deal
397 in the Software without restriction, including without limitation the rights
398 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
399 copies of the Software, and to permit persons to whom the Software is
400 furnished to do so, subject to the following conditions:
401  
402 The above copyright notice and this permission notice shall be included in all
403 copies or substantial portions of the Software.
404  
405 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
406 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
407 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
408 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
409 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
410 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
411 SOFTWARE.
412  
413 =cut
414  
415 1;
416  
417 __END__
« Transfigure/Type/DateTime/Duration.pm ↑ Summary Transfigure/Default.pm »