Shopify/Model/Item.pm untested

filter: Statementstmt 0.0% 0 / 227 Branchbran 0.0% 0 / 78 Conditioncond 0.0% 0 / 30 MC/DCmcdc 0.0% 0 / 18 Subroutinesub 0.0% 0 / 108 Podpod 0.0% 0 / 97 totaltotal 0.0% 0 / 558 CC 51 SCAR 39.5
CC
51
Cov
0%
from_json
210.0
to_json
210.0
decodeForRef
156.0
CRAP 51.8
1 #!/usr/bin/perl
2  
3 use strict;
4 use warnings;
5  
6 package WWW::Shopify::Model::Item;
7 use DateTime;
8 use WWW::Shopify::Query;
9 use WWW::Shopify::Field;
10 use WWW::Shopify::Field::String;
11  
12 =head1 NAME
13  
14 Item - Main superclass for all the shopify objects.
15  
16 =cut
17  
18 =head1 DESCRIPTION
19  
20 Items are the main super class for all Shopify objects. This class holds glue code that ties the schemas (WWW::Shopify::Model::Product, for example), which only hold definitions about how the Shopify API works, and WWW::Shopify, which is the acutal method for calling Shopify's interface.
21  
22 These objects can be used in many ways; they boil down to one of three states.
23  
24 =over 4
25  
26 =item DBIx::Class Object: The item has been mapped to a DBIx::Class schema and can be stored in a relational database.
27  
28 =item WWW::Shopify::Model Object: The item is in an intemediate state, suitable for querying, perusing and manipulating.
29  
30 =item JSON-Like Hash: The item is similar to the WWW::Shopify::Model, but lacks all-non canonical shopify references, and is ready to be encode_json'd before being sent off to Shopify.
31  
32 =back
33  
34 =cut
35  
36 =head1 METHODS
37  
38 Most of these methods you shouldn't have to mess with, most of them are used to describe the objects appropriately so that testing mock frameworks and database can be created with ease.
39  
40 =cut
41  
42 use Exporter 'import';
43 our @EXPORT = qw(generate_accessor);
44  
45 =head2 new($%params)
46  
47 Generates a new intermediate stage (WWW::Shopify::Model::...) object.
48  
49 =cut
50  
51 use Scalar::Util qw(weaken);
52  
53 sub new {
54 my $self = (defined $_[1]) ? $_[1] : {};
55 weaken($self->{associated_parent}) if $self->{associated_parent};
56 return bless $self, $_[0];
57 }
58  
59 =head2 parent($package)
60  
61 Does this package have a parent?
62  
63 =cut
64  
65 sub parent { return undef; }
66 sub is_item { return 1; }
67  
68 =head2 is_shop($package)
69  
70 Convenience method telling us if we're a WWW::Shopify::Model::Shop.
71  
72 =cut
73  
74 sub is_shop { return undef; }
75  
76 sub graphql_only { return undef; }
77  
78 =head2 singular($package)
79  
80 Returns the text representing the singular form of this package. (WWW::Shopify::Model::Order->singular eq "order").
81  
82 =cut
83  
84 # Returns the singular form of the object. Usually the name of the file.
85 # Is like this, because we want to be able to call this on the package as well as an object in it.
86 sub singular {
87 # If we have a package instead of an instantiated object.
88 if (!ref($_[0])) {
89 die $_[0] unless $_[0] =~ m/(\:\:)?(\w+)$/;
90 my $name = $2;
91 $name =~ s/([a-z])([A-Z])/$1_$2/g;
92 return (lc $name);
93 }
94 # Here, we have an object, so run this function again with the package name.
95 return singular(ref($_[0]));
96 }
97  
98 # Specifies in a text-friendly manner the FULL specific name of this package.
99 sub singular_fully_qualified {
100 if (!ref($_[0])) {
101 die $_[0] unless $_[0] =~ m/Model::([:\w]+)$/;
102 my $name = lc($1);
103 $name =~ s/\:\:/-/g;
104 return $name;
105 }
106 # Here, we have an object, so run this function again with the package name.
107 return singular_fully_qualified(ref($_[0]));
108 }
109  
110 =head2 plural($package)
111  
112 Returns the text representing the plural form of this package. (WWW::Shopify::Model::Address->plural eq "addresses").
113  
114 =cut
115  
116 sub plural { return $_[0]->singular() . "s"; }
117  
118 # Sigh. Yet again let's just violate conventions on a single resource, necessitating yet more methods.
119 # I'm looking at you, fulfillment event.
120 sub url_singular { return $_[0]->singular; }
121 sub url_plural { return $_[0]->plural; }
122  
123 sub needs_login { return undef; }
124 sub needs_form_encoding_get_all { return undef; }
125 sub needs_form_encoding_get { return undef; }
126 sub needs_form_encoding_create { return undef; }
127 sub needs_form_encoding_update { return undef; }
128 sub needs_form_encoding_delete { return undef; }
129  
130 =head2 needs_plus($package)
131  
132 Returns whether or not a Shopify+ account is required to use this resource.
133  
134 =cut
135  
136 sub needs_plus { return undef; }
137  
138 # Determines whether or not it's required for Shopify to manually enable access for this API.
139 sub needs_blessing { return $_[0]->needs_plus; }
140  
141 # List of fields that should be filled automatically on creation.
142 sub is_nested { return undef; }
143 sub identifier { return ("id"); }
144  
145 # Counts the ::. Is helpful in a bunch of ways.
146 sub nested_level {
147 my ($package) = @_;
148 my $level = -2;
149 while ($package =~ m/::/g) {
150 ++$level;
151 }
152 return $level;
153 }
154  
155  
156 # I cannot fucking believe I'm doing this. Everything can be counted.
157 # Oh, except themes. We don't count those. For some arbitrary reason.
158  
159 =head2 countable($package), gettable($package), creatable($package), updatable($package), deletable($package), searchable($package)
160  
161 Determines whether or not this package can perform these main actions. 1 for yes, undef for no.
162  
163 =cut
164  
165 sub countable { return 1; }
166 sub gettable { return 1; }
167 # Whether or not we can get it as a single entity, by ID.
168 sub singlable { return $_[0]->gettable; }
169 sub creatable { return 1; }
170 sub updatable { my @fields = $_[0]->update_fields; return int(@fields) > 0; }
171 sub deletable { return 1; }
172 sub searchable { return undef; }
173  
174 sub get_order { ({'desc' => 'id' }) }
175  
176 =head2 actions($package)
177  
178 Returns an array of special actions that this package can perform (for orders, they can open, close, and cancel).
179  
180 =cut
181  
182 sub actions { return qw(); }
183 use List::Util qw(first);
184 sub can_action { return defined first { $_ eq $_[1] } $_[0]->actions; }
185 sub can_open { return $_[0]->can_action("open"); }
186 sub can_activate { return $_[0]->can_action("activate"); }
187 sub can_deactivate { return $_[0]->can_action("deactivate"); }
188 sub can_enable { return $_[0]->can_action("enable"); }
189 sub can_disable { return $_[0]->can_action("disable"); }
190 sub can_close { return $_[0]->can_action("close"); }
191 sub can_cancel { return $_[0]->can_action("cancel"); }
192 sub can_account_activation_url { return $_[0]->can_action("account_activation_url"); }
193  
194 =head2 create_method($package), update_method($package), delete_method($package)
195  
196 Shopify occasionally arbitrarily changes their update/create methods from POST and PUT around. Sometimes it makes them the same. These say which method is used where, but generally the convention is:
197  
198 =over 4
199  
200 =item CREATE => POST
201  
202 =item UPDATE => PUT
203  
204 =item DELETE => DELETE
205  
206 =back
207  
208 But not always.
209  
210 =cut
211  
212 # I CANNOT FUCKING BELIEVE I AM DOING THIS; WHAT THE FUCK SHOPIFY. WHY!? WHY MAKE IT DIFFERENT ARBITRARILY!?
213 sub create_method { return "POST"; }
214 sub update_method { return "PUT"; }
215 sub delete_method { return "DELETE"; }
216  
217 =head2 queries($package)
218  
219 Returns a hash of WWW::Shopify::Query objects which describe you what kind of filters you can run on this package. (Limit, since_id, created_at_min, etc...)
220  
221 =cut
222  
223 sub queries { return {}; }
224  
225 =head2 unique_fields($package)
226  
227 An array of fields which have to be unique in this package (WWW::Shopify::Model::Customer's email, for example)
228  
229 =cut
230  
231 sub unique_fields { return qw(); }
232  
233 =head2 get_fields($package)
234  
235 Usually every field in a class, but not always; this returns an array of keys that tells you which fields will come back when you perform a normal get request.
236  
237 =cut
238  
239 sub get_fields { return keys(%{$_[0]->fields}); }
240  
241 =head2 creation_minimal($package)
242  
243 Returns an array of fields that are required before you send an object off to be created on Shopify.
244  
245 =cut
246  
247 sub creation_minimal { return (); }
248  
249 =head2 creation_filled($package)
250  
251 Returns an array of fields that you should be getting back filled with data when the object is created on Shopify.
252  
253 =cut
254  
255 sub creation_filled { return qw(id); }
256  
257 =head2 update_fields($package)
258  
259 Returns an array of fields that you can update when an object is already created.
260  
261 =cut
262  
263 sub update_fields { return qw(); }
264  
265 =head2 update_filled($package)
266  
267 Returns an array of fields that will be changed/filled when an object is updated.
268  
269 =cut
270  
271 sub update_filled { return qw(); }
272  
273  
274 =head2 throws_webhooks($package), throws_create_webhooks($package), throws_update_webhooks($package), throws_delete_webhooks($package)
275  
276 Tells you whether or not the object throws webhooks for a living.
277  
278 =cut
279  
280 sub webhook_topic { return $_[0]->plural; }
281 sub throws_webhooks { return undef; }
282 sub webhook_create_name { 'create' }
283 sub throws_create_webhooks { return $_[0]->throws_webhooks; }
284 sub webhook_update_name { 'update' }
285 sub throws_update_webhooks { return $_[0]->throws_webhooks; }
286 sub webhook_delete_name { 'delete' }
287 sub throws_delete_webhooks { return $_[0]->throws_webhooks; }
288  
289 # Oh fucking WOW. WHAT THE FUCK. Variants, of course, delete directly with their id, and modify with it.
290 # Metafields delete with their id, but modify through their parent. They also get through their parents.
291 # Variants of course, get through their id directly. I'm at a loss for words. Why!? Article are different, yet again.
292  
293 =head2 get_all_through_parent($package), get_through_parent($package), create_through_parent($package), update_through_parent($package), delete_through_parent($package)
294  
295 Occasionally, Shopify decides they wanna change up their normal API conventions, and decides to throw us a curve ball, and change up whether or not certain objects have to be accessed through their parent objects /product/3242134/variants/342342.json vs. /variants/342342.json
296  
297 These tell you which objects have to go through their parent, and which don't. It tends to be rather arbitrary.
298  
299 =cut
300  
301 sub get_all_through_parent { return defined $_[0]->parent; }
302 sub get_through_parent { return defined $_[0]->parent; }
303 sub count_through_parent { return $_[0]->get_all_through_parent; }
304 sub create_through_parent { return defined $_[0]->parent; }
305 sub update_through_parent { return defined $_[0]->parent; }
306 sub delete_through_parent { return defined $_[0]->parent; }
307 sub activate_through_parent { return defined $_[0]->parent; }
308 sub deactivate_through_parent { return defined $_[0]->parent; }
309 sub open_through_parent { return defined $_[0]->parent; }
310 sub close_through_parent { return defined $_[0]->parent; }
311 sub cancel_through_parent { return defined $_[0]->parent; }
312 sub enable_through_parent { return defined $_[0]->parent; }
313 sub disable_through_parent { return defined $_[0]->parent; }
314 sub account_activation_url_through_parent { return defined $_[0]->parent; }
315 sub order_through_parent { return defined $_[0]->parent; }
316 sub connect_through_parent { return defined $_[0]->parent; }
317 sub adjust_through_parent { return defined $_[0]->parent; }
318 sub set_through_parent { return defined $_[0]->parent; }
319  
320 sub prefix { '/'; }
321  
322 # Normally this is 403, but, lovely lovely shopify decides to vary this from object to object.
323 sub error_codes_if_unavailable { (403) }
324  
325 =head2 max_per_page
326  
327 Tells you how many you can grab in a single page.
328  
329 =cut
330  
331 sub max_per_page { return 250; }
332  
333 =head2 default_per_page
334  
335 Tells you how many entries you'll get by default.
336  
337 =cut
338  
339 sub paginates { 1; }
340  
341 sub default_per_page { return 50; }
342  
343 =head2 included_in_parent
344  
345 Tells you whether a sub-object is included by defualt when you get an object as a sub-object. Most cases is 1.
346  
347 =cut
348  
349 sub included_in_parent { return 1; }
350  
351 =head2 field($package, $name), fields($package)
352  
353 Returns a WWW::Shopify::Field::... which describes the specified field, or returns a hash containing all fields.
354  
355 =cut
356  
357 sub fields { }
358 sub field { my ($package, $name) = @_; return $package->fields->{$name}; }
359  
360 =head2 associate($self)
361  
362 Returns the WWW::Shopify object that created/updated/deleted this object last.
363  
364 =cut
365  
366 sub associate { $_[0]->{associated_sa} = $_[1] if $_[1]; return $_[0]->{associated_sa}; }
367  
368 =head2 associate_parent($self)
369  
370 Returns the parent associated with this object. If we're a variant, it'll return the parent product (if it had access to it at one point; it usually does). Weak reference.
371  
372 =cut
373  
374  
375 use Scalar::Util qw(weaken);
376 sub associated_parent {
377 if (defined $_[1]) {
378 $_[0]->{associated_parent} = $_[1];
379 weaken($_[0]->{associated_parent});
380 }
381 return $_[0]->{associated_parent};
382 }
383  
384 sub has_metafields { return defined $_[0]->field('metafields'); }
385  
386 =head2 metafields($self)
387  
388 Returns the metafields associated with this item. If they haven't been gotten before, a request is made, and they're cahced inside the object.
389  
390 If you change a metafield, and later want to access it through a copy of the object, and this copy already has looked at the metafields, you'll get a stale copy.
391  
392 If this is the case, call the method below.
393  
394 =cut
395  
396 use Data::Dumper;
397 sub metafields {
398 my $sa = $_[0]->associate;
399 if (!defined $_[0]->{metafields}) {
400 die new WWW::Shopify::Exception("You cannot call metafields on an unassociated item.") unless $sa;
401 $_[0]->{metafields} = [$sa->get_all('Metafield', { parent => $_[0] })];
402 }
403 return $_[0]->{metafields} unless wantarray;
404 return @{$_[0]->{metafields}};
405 }
406  
407 =head2 refesh_metafields($self)
408  
409 Returns the metafields associated with item, but ALWAYS performs a get request.
410  
411 =cut
412  
413 sub refresh_metafields {
414 delete $_[0]->{metafields} if exists $_[0]->{metafields};
415 return $_[0]->metafields;
416 }
417  
418 =head2 add_metafield($self, $metafield)
419  
420 Takes a WWW::Shopify::Model::Metafield object.
421  
422 =cut
423  
424 sub add_metafield {
425 my ($self, $metafield) = @_;
426 my $sa = $_[0]->associate;
427 die new WWW::Shopify::Exception("You cannot add metafields on an unassociated item.") unless $sa;
428 $metafield->associated_parent($self);
429 return $sa->create($metafield);
430 }
431  
432 =head2 from_json($package, $json_hash, [$associated])
433  
434 Returns a WWW::Shopify::Model::... intermediate object from a hash that's been decoded from a JSON object (i.e. normal shopify object in the API docs, decoded using JSON qw(decode_json); ). Does a bunch of nice conversions, like putting DateTime objects in the proper places, and associate each individual obejct with a reference to its parent and to the WWW::Shopify object that created it.
435  
436 =cut
437  
438 sub from_json {
439 my ($package, $json, $associated) = @_;
440  
441 sub decodeForRef {
442 my ($self, $json, $ref, $associated) = @_;
443 for (keys(%{$ref})) {
444 if ($ref->{$_}->is_relation()) {
445 my $package = $ref->{$_}->relation();
446 if ($ref->{$_}->is_many()) {
447 # This may not be necesasry, but this is such fundamental code I don't want to mess with it.
448 next unless exists $json->{$package->plural()} || exists $json->{$_};
449 my @objects;
450 my $index = exists $json->{$package->plural()} ? $package->plural : $_;
451 @objects = defined $json->{$index} ? @{$json->{$index}} : ();
452 $self->{$_} = [map {
453 my $o = $package->from_json($_, $associated);
454 $o->associated_parent($self);
455 $o;
456 } @objects];
457 }
458 elsif ($ref->{$_}->is_one && $ref->{$_}->is_own) {
459 next unless (exists $json->{$_});
460 $self->{$_} = $package->from_json($json->{$_}, $associated);
461 $self->{$_}->associated_parent($self) if $self->{$_};
462 }
463 elsif ($ref->{$_}->is_one) {
464 $self->{$_} = $json->{$_} if exists $json->{$_};
465 }
466 else {
467 die "Relationship specified must be either many, or one in $package.";
468 }
469 }
470 else {
471 $self->{$_} = $ref->{$_}->from_shopify($json->{$_}) if exists $json->{$_};
472 }
473 }
474 }
475 return undef unless $json;
476  
477 my $self = $package->new();
478 $self->associate($associated) if ($associated);
479  
480 $self->decodeForRef($json, $self->fields, $associated);
481 return $self;
482 }
483  
484 =head2 to_json($self)
485  
486 Returns a hash that's ready to be converted in to a JSON string using encode_json from the JSON package.
487  
488 =cut
489  
490 sub to_json($) {
491 my ($self) = @_;
492 my $fields = $self->fields();
493 my $final = {};
494 foreach my $key (keys(%$self)) {
495 next unless exists $fields->{$key};
496 if ($fields->{$key}->is_relation()) {
497 if ($fields->{$key}->is_many()) {
498 # Since metafields don't come prepackaged, we don't get them. Unless we've already got them.
499 next if $key eq "metafields" && !$_[0]->{metafields};
500 my @results = $self->$key();
501 if (int(@results)) {
502 $final->{$key} = [map { $_->to_json() } grep { defined $_ } @results];
503 }
504 else {
505 $final->{$key} = [] if exists $self->{$key};
506 }
507 }
508 if ($fields->{$key}->is_one() && $fields->{$key}->is_reference()) {
509 if (defined $self->$key()) {
510 # This is inconsistent; this if is a stop-gap measure.
511 # Getting directly from teh database seems to make this automatically an id.
512 if (ref($self->$key())) {
513 $final->{$key} = $self->$key()->id();
514 }
515 else {
516 $final->{$key} = $self->$key();
517 }
518 }
519 else {
520 $final->{$key} = undef if exists $self->{$key};
521 }
522 }
523 $final->{$key} = ($self->$key ? $self->$key->to_json() : undef) if (exists $self->{$key} && $fields->{$key}->is_one() && $fields->{$key}->is_own());
524 }
525 else {
526 $final->{$key} = $fields->{$key}->to_shopify($self->$key) if exists $self->{$key};
527 }
528 }
529 return $final;
530 }
531  
532 # Quick n' dirty clone method.
533 sub clone {
534 my ($self) = @_;
535 return ref($self)->from_json($self->to_json);
536 }
537  
538 sub generate_accessors {
539 return join("\n",
540 (map { "__PACKAGE__->queries->{$_}->name('$_');" } keys(%{$_[0]->queries})),
541 (map { "__PACKAGE__->fields->{$_}->name('$_');" } keys(%{$_[0]->fields})),
542 (map { "sub $_ { \$_[0]->{$_} = \$_[1] if defined \$_[1]; return undef unless defined \$_[0]->{$_}; return \@{\$_[0]->{$_}} if wantarray; return \$_[0]->{$_}; }" } grep { $_ ne "metafields" && $_[0]->field($_)->is_relation && $_[0]->field($_)->is_many } keys(%{$_[0]->fields})),
543 (map { "sub $_ { \$_[0]->{$_} = \$_[1] if defined \$_[1]; return \$_[0]->{$_}; }" } grep { $_ ne "metafields" && (!$_[0]->field($_)->is_relation || !$_[0]->field($_)->is_many) } keys(%{$_[0]->fields})),
544 (map { "sub $_ { my \$sa = \$_[0]->associate; die \"Can't call a special action on an unassociated item.\" unless \$sa; return \$sa->$_(\$_[0]); }" } $_[0]->actions)
545 );
546 }
547  
548 sub read_scope { return undef; }
549 sub write_scope { return undef; }
550 # Whether or not the scopes actually need to be authorized; mega-sigh.
551 sub actually_needs_scopes { 1; }
552  
553 =head1 SEE ALSO
554  
555 L<WWW::Shopify>
556  
557 =head1 AUTHOR
558  
559 Adam Harrison
560  
561 =head1 LICENSE
562  
563 See LICENSE in the main directory.
564  
565 =cut
566  
567 1