Test Setup Failed
Push — develop ( e51f4b...6ef9da )
by Jimmy
01:11 queued 13s
created

Model::getDefaultWheres()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spinen\Halo\Support;
4
5
use ArrayAccess;
6
use GuzzleHttp\Exception\GuzzleException;
7
use Illuminate\Contracts\Support\Arrayable;
8
use Illuminate\Contracts\Support\Jsonable;
9
use Illuminate\Database\Eloquent\Concerns\HasAttributes;
10
use Illuminate\Database\Eloquent\Concerns\HasTimestamps;
11
use Illuminate\Database\Eloquent\Concerns\HidesAttributes;
12
use Illuminate\Database\Eloquent\JsonEncodingException;
13
use Illuminate\Support\Carbon;
14
use Illuminate\Support\Facades\Date;
15
use Illuminate\Support\Str;
16
use Illuminate\Support\Traits\Conditionable;
17
use JsonSerializable;
18
use LogicException;
19
use Spinen\Halo\Concerns\HasClient;
20
use Spinen\Halo\Exceptions\InvalidRelationshipException;
21
use Spinen\Halo\Exceptions\ModelNotFoundException;
22
use Spinen\Halo\Exceptions\ModelReadonlyException;
23
use Spinen\Halo\Exceptions\NoClientException;
24
use Spinen\Halo\Exceptions\TokenException;
25
use Spinen\Halo\Exceptions\UnableToSaveException;
26
use Spinen\Halo\Support\Relations\BelongsTo;
27
use Spinen\Halo\Support\Relations\ChildOf;
28
use Spinen\Halo\Support\Relations\HasMany;
29
use Spinen\Halo\Support\Relations\Relation;
30
31
/**
32
 * Class Model
33
 *
34
 * NOTE: Since we are trying to give a Laravel like feel when interacting
35
 * with the API, there are sections of this code that is very heavily
36
 * patterned/inspired directly from Laravel's Model class.
37
 */
38
abstract class Model implements Arrayable, ArrayAccess, Jsonable, JsonSerializable
39
{
40
    use Conditionable;
41
    use HasAttributes {
0 ignored issues
show
introduced by
The trait Illuminate\Database\Eloq...\Concerns\HasAttributes requires some properties which are not provided by Spinen\Halo\Support\Model: $preventsLazyLoading, $name, $map, $set, $withCaching, $withObjectCaching, $get, $value
Loading history...
42
        asDateTime as originalAsDateTime;
43
    }
44
    use HasClient;
45
    use HasTimestamps;
46
    use HidesAttributes;
47
48
    /**
49
     * Default wheres to send.  They are overwrote by any matching where calls.
50
     */
51
    public array $defaultWheres = [];
52
53
    /**
54
     * Indicates if the model exists.
55
     */
56
    public bool $exists = false;
57
58
    /**
59
     * Indicates if the IDs are auto-incrementing.
60
     */
61
    public bool $incrementing = false;
62
63
    /**
64
     * The "type" of the primary key ID.
65
     */
66
    protected string $keyType = 'int';
67
68
    /**
69
     * Is resource nested behind parentModel
70
     *
71
     * Several of the endpoints are nested behind another model for relationship, but then to
72
     * interact with the specific model, then are not nested.  This property will know when to
73
     * keep the specific model nested.
74
     */
75
    protected bool $nested = false;
76
77
    /**
78
     * Parameter for order by direction
79
     *
80
     * Default is "$orderByParameter . 'desc'"
81
     */
82
    protected ?string $orderByDirectionParameter = null;
83
84
    /**
85
     * Parameter for order by column
86
     */
87
    protected string $orderByParameter = 'order';
88
89
    /**
90
     * Optional parentModel instance
91
     */
92
    public ?Model $parentModel;
93
94
    /**
95
     * Path to API endpoint.
96
     */
97
    protected string $path;
98
99
    /**
100
     * The primary key for the model.
101
     */
102
    protected string $primaryKey = 'id';
103
104
    /**
105
     * Is the model readonly?
106
     */
107
    protected bool $readonlyModel = false;
108
109
    /**
110
     * The loaded relationships for the model.
111
     */
112
    protected array $relations = [];
113
114
    /**
115
     * Some of the responses have the collections under a property
116
     */
117
    protected ?string $responseCollectionKey = null;
118
119
    /**
120
     * Some of the responses have the data under a property
121
     */
122
    protected ?string $responseKey = null;
123
124
    /**
125
     * Are timestamps in milliseconds?
126
     */
127
    protected bool $timestampsInMilliseconds = true;
128
129
    /**
130
     * Indicates if the model was inserted during the current request lifecycle.
131
     *
132
     * @var bool
133
     */
134
    public $wasRecentlyCreated = false;
135
136
    /**
137
     * The name of the "created at" column.
138
     *
139
     * @var string
140
     */
141
    const CREATED_AT = null;
142
143
    /**
144
     * The name of the "updated at" column.
145
     *
146
     * @var string
147
     */
148
    const UPDATED_AT = null;
149
150
    /**
151
     * Model constructor.
152
     */
153
    public function __construct(?array $attributes = [], Model $parentModel = null)
154
    {
155
        // All dates from API comes as epoch with milliseconds
156
        $this->dateFormat = 'Uv';
157
        // None of these models will use timestamps, but need the date casting
158
        $this->timestamps = false;
159
160
        $this->syncOriginal();
161
162
        $this->fill($attributes);
163
        $this->parentModel = $parentModel;
164
    }
165
166
    /**
167
     * Dynamically retrieve attributes on the model.
168
     */
169
    public function __get(string $key)
170
    {
171
        return $this->getAttribute($this->keyMap($key));
172
    }
173
174
    /**
175
     * Determine if an attribute or relation exists on the model.
176
     */
177
    public function __isset(string $key): bool
178
    {
179
        return $this->offsetExists($this->keyMap($key));
180
    }
181
182
    /**
183
     * Dynamically set attributes on the model.
184
     *
185
     * @param  string  $key
186
     * @return void
187
     *
188
     * @throws ModelReadonlyException
189
     */
190
    public function __set($key, $value)
191
    {
192
        if ($this->readonlyModel) {
193
            throw new ModelReadonlyException();
194
        }
195
196
        $this->setAttribute($this->keyMap($key), $value);
197
    }
198
199
    /**
200
     * Convert the model to its string representation.
201
     *
202
     * @return string
203
     */
204
    public function __toString()
205
    {
206
        return $this->toJson();
207
    }
208
209
    /**
210
     * Unset an attribute on the model.
211
     *
212
     * @param  string  $key
213
     * @return void
214
     */
215
    public function __unset($key)
216
    {
217
        $this->offsetUnset($this->keyMap($key));
218
    }
219
220
    /**
221
     * Return a timestamp as DateTime object.
222
     *
223
     * @return Carbon
224
     */
225
    protected function asDateTime($value)
226
    {
227
        if (is_numeric($value) && $this->timestampsInMilliseconds) {
228
            return Date::createFromTimestampMs($value);
229
        }
230
231
        return $this->originalAsDateTime($value);
232
    }
233
234
    /**
235
     * Assume foreign key
236
     *
237
     * @param  string  $related
238
     */
239
    protected function assumeForeignKey($related): string
240
    {
241
        return Str::snake((new $related())->getResponseKey()).'_id';
242
    }
243
244
    /**
245
     * Relationship that makes the model belongs to another model
246
     *
247
     * @param  string  $related
248
     * @param  string|null  $foreignKey
249
     *
250
     * @throws InvalidRelationshipException
251
     * @throws ModelNotFoundException
252
     * @throws NoClientException
253
     */
254
    public function belongsTo($related, $foreignKey = null): BelongsTo
255
    {
256
        $foreignKey = $foreignKey ?? $this->assumeForeignKey($related);
257
258
        $builder = (new Builder())->setClass($related)
259
                                  ->setClient($this->getClient());
260
261
        return new BelongsTo($builder, $this, $foreignKey);
262
    }
263
264
    /**
265
     * Relationship that makes the model child to another model
266
     *
267
     * @param  string  $related
268
     * @param  string|null  $foreignKey
269
     *
270
     * @throws InvalidRelationshipException
271
     * @throws ModelNotFoundException
272
     * @throws NoClientException
273
     */
274
    public function childOf($related, $foreignKey = null): ChildOf
275
    {
276
        $foreignKey = $foreignKey ?? $this->assumeForeignKey($related);
277
278
        $builder = (new Builder())->setClass($related)
279
                                  ->setClient($this->getClient())
280
                                  ->setParent($this);
281
282
        return new ChildOf($builder, $this, $foreignKey);
283
    }
284
285
    /**
286
     * Convert boolean to a string as their API expects "true"/"false
287
     */
288
    protected function convertBoolToString(mixed $value): mixed
289
    {
290
        return match (true) {
291
            is_array($value) => array_map([$this, 'convertBoolToString'], $value),
292
            is_bool($value) => $value ? 'true' : 'false',
293
            default => $value,
294
        };
295
    }
296
297
    /**
298
     * Delete the model from Halo
299
     *
300
     * @throws NoClientException
301
     * @throws TokenException
302
     */
303
    public function delete(): bool
304
    {
305
        // TODO: Make sure that the model supports being deleted
306
        if ($this->readonlyModel) {
307
            return false;
308
        }
309
310
        try {
311
            $this->getClient()
312
                 ->delete($this->getPath());
313
314
            return true;
315
        } catch (GuzzleException $e) {
316
            // TODO: Do something with the error
317
318
            return false;
319
        }
320
    }
321
322
    /**
323
     * Fill the model with the supplied properties
324
     */
325
    public function fill(?array $attributes = []): self
326
    {
327
        foreach ((array) $attributes as $attribute => $value) {
328
            $this->setAttribute($attribute, $value);
329
        }
330
331
        return $this;
332
    }
333
334
    /**
335
     * Merge any where in the defaultWheres property with any passed in.
336
     */
337
    public function getDefaultWheres(array $query = []): array
338
    {
339
        return [
340
            ...$this->defaultWheres,
341
            ...$query,
342
        ];
343
    }
344
345
    /**
346
     * Get the value indicating whether the IDs are incrementing.
347
     */
348
    public function getIncrementing(): bool
349
    {
350
        return $this->incrementing;
351
    }
352
353
    /**
354
     * Get the value of the model's primary key.
355
     */
356
    public function getKey()
357
    {
358
        return $this->getAttribute($this->getKeyName());
359
    }
360
361
    /**
362
     * Get the primary key for the model.
363
     */
364
    public function getKeyName(): string
365
    {
366
        return $this->primaryKey;
367
    }
368
369
    /**
370
     * Get the auto-incrementing key type.
371
     */
372
    public function getKeyType(): string
373
    {
374
        return $this->keyType;
375
    }
376
377
    /**
378
     * Get the parameter the endpoint uses to sort.
379
     */
380
    public function getOrderByDirectionParameter(): string
381
    {
382
        return $this->orderByDirectionParameter ?? $this->getOrderByParameter().'desc';
383
    }
384
385
    /**
386
     * Get the parameter the endpoint uses to sort.
387
     */
388
    public function getOrderByParameter(): string
389
    {
390
        return $this->orderByParameter;
391
    }
392
393
    /**
394
     * Build API path
395
     *
396
     * Put anything on the end of the URI that is passed in
397
     *
398
     * @param  string|null  $extra
399
     * @param  array|null  $query
400
     * @return string
401
     */
402
    public function getPath($extra = null, array $query = []): ?string
403
    {
404
        // Start with path to resource without "/" on end
405
        $path = rtrim($this->path, '/');
406
407
        // If have an id, then put it on the end
408
        if ($this->getKey()) {
409
            $path .= '/'.$this->getKey();
410
        }
411
412
        // Stick any extra things on the end
413
        if (! is_null($extra)) {
414
            $path .= '/'.ltrim($extra, '/');
415
        }
416
417
        if (! empty($query = $this->getDefaultWheres($query))) {
418
            $path .= '?'.http_build_query($this->convertBoolToString($query));
419
        }
420
421
        // If there is a parentModel & not have an id (unless for nested), then prepend parentModel
422
        if (! is_null($this->parentModel) && (! $this->getKey() || $this->isNested())) {
423
            return $this->parentModel->getPath($path);
424
        }
425
426
        return $path;
427
    }
428
429
    /**
430
     * Get a relationship value from a method.
431
     *
432
     * @param  string  $method
433
     *
434
     * @throws LogicException
435
     */
436
    public function getRelationshipFromMethod($method)
437
    {
438
        $relation = $this->{$method}();
439
440
        if (! $relation instanceof Relation) {
441
            $exception_message = is_null($relation)
442
                ? '%s::%s must return a relationship instance, but "null" was returned. Was the "return" keyword used?'
443
                : '%s::%s must return a relationship instance.';
444
445
            throw new LogicException(
446
                sprintf($exception_message, static::class, $method)
447
            );
448
        }
449
450
        return tap(
451
            $relation->getResults(),
452
            function ($results) use ($method) {
453
                $this->setRelation($method, $results);
454
            }
455
        );
456
    }
457
458
    /**
459
     * Name of the wrapping key when response is a collection
460
     *
461
     * If none provided, assume plural version responseKey
462
     */
463
    public function getResponseCollectionKey(): ?string
464
    {
465
        return $this->responseCollectionKey ?? Str::plural($this->getResponseKey());
466
    }
467
468
    /**
469
     * Name of the wrapping key of response
470
     *
471
     * If none provided, assume camelCase of class name
472
     */
473
    public function getResponseKey(): ?string
474
    {
475
        return $this->responseKey ?? Str::camel(class_basename(static::class));
476
    }
477
478
    /**
479
     * Many of the results include collection of related data, so cast it
480
     *
481
     * @param  string  $related
482
     * @param  array  $given
483
     * @param  bool  $reset Some of the values are nested under a property, so peel it off
484
     *
485
     * @throws NoClientException
486
     */
487
    public function givenMany($related, $given, $reset = false): Collection
488
    {
489
        /** @var Model $model */
490
        $model = (new $related([], $this->parentModel))->setClient($this->getClient());
491
492
        return (new Collection($given))->map(
0 ignored issues
show
Bug introduced by
$given of type array is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $items of Spinen\Halo\Support\Collection::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

492
        return (new Collection(/** @scrutinizer ignore-type */ $given))->map(
Loading history...
493
            function ($attributes) use ($model, $reset) {
494
                return $model->newFromBuilder($reset ? reset($attributes) : $attributes);
495
            }
496
        );
497
    }
498
499
    /**
500
     * Many of the results include related data, so cast it to object
501
     *
502
     * @param  string  $related
503
     * @param  array  $attributes
504
     * @param  bool  $reset Some of the values are nested under a property, so peel it off
505
     *
506
     * @throws NoClientException
507
     */
508
    public function givenOne($related, $attributes, $reset = false): Model
509
    {
510
        return (new $related([], $this->parentModel))->setClient($this->getClient())
511
                                                     ->newFromBuilder($reset ? reset($attributes) : $attributes);
512
    }
513
514
    /**
515
     * Relationship that makes the model have a collection of another model
516
     *
517
     * @param  string  $related
518
     *
519
     * @throws InvalidRelationshipException
520
     * @throws ModelNotFoundException
521
     * @throws NoClientException
522
     */
523
    public function hasMany($related): HasMany
524
    {
525
        $builder = (new Builder())->setClass($related)
526
                                  ->setClient($this->getClient())
527
                                  ->setParent($this);
528
529
        return new HasMany($builder, $this);
530
    }
531
532
    /**
533
     * Is endpoint nested behind another endpoint
534
     */
535
    public function isNested(): bool
536
    {
537
        return $this->nested ?? false;
538
    }
539
540
    /**
541
     * Convert the object into something JSON serializable.
542
     */
543
    public function jsonSerialize(): array
544
    {
545
        return $this->toArray();
546
    }
547
548
    /**
549
     * Map keys to names that are more standard to our use
550
     */
551
    protected function keyMap(string $key): string
552
    {
553
        // TODO: Is this a good idea?
554
        return match ($key) {
555
            'color' => 'colour',
556
            default => $key,
557
        };
558
    }
559
560
    /**
561
     * Create a new model instance that is existing.
562
     *
563
     * @param  array  $attributes
564
     * @return static
565
     */
566
    public function newFromBuilder($attributes = []): self
567
    {
568
        $model = $this->newInstance([], true);
569
570
        $model->setRawAttributes((array) $attributes, true);
571
572
        return $model;
573
    }
574
575
    /**
576
     * Create a new instance of the given model.
577
     *
578
     * Provides a convenient way for us to generate fresh model instances of this current model.
579
     * It is particularly useful during the hydration of new objects via the builder.
580
     *
581
     * @param  bool  $exists
582
     * @return static
583
     */
584
    public function newInstance(array $attributes = [], $exists = false): self
585
    {
586
        $model = (new static($attributes, $this->parentModel))->setClient($this->client);
587
588
        $model->exists = $exists;
589
590
        return $model;
591
    }
592
593
    /**
594
     * Determine if the given attribute exists.
595
     */
596
    public function offsetExists($offset): bool
597
    {
598
        return ! is_null($this->getAttribute($offset));
599
    }
600
601
    /**
602
     * Get the value for a given offset.
603
     */
604
    public function offsetGet($offset): mixed
605
    {
606
        return $this->getAttribute($offset);
607
    }
608
609
    /**
610
     * Set the value for a given offset.
611
     *
612
     *
613
     * @throws ModelReadonlyException
614
     */
615
    public function offsetSet($offset, $value): void
616
    {
617
        if ($this->readonlyModel) {
618
            throw new ModelReadonlyException();
619
        }
620
621
        $this->setAttribute($offset, $value);
622
    }
623
624
    /**
625
     * Unset the value for a given offset.
626
     */
627
    public function offsetUnset($offset): void
628
    {
629
        unset($this->attributes[$offset], $this->relations[$offset]);
630
    }
631
632
    /**
633
     * Laravel allows control of accessing missing attributes, so we just return false
634
     *
635
     * @return bool
636
     */
637
    public static function preventsAccessingMissingAttributes()
638
    {
639
        return false;
640
    }
641
642
    /**
643
     * Determine if the given relation is loaded.
644
     *
645
     * @param  string  $key
646
     */
647
    public function relationLoaded($key): bool
648
    {
649
        return array_key_exists($key, $this->relations);
650
    }
651
652
    /**
653
     * Laravel allows the resolver to be set at runtime, so we just return null
654
     *
655
     * @param  string  $class
656
     * @param  string  $key
657
     * @return null
658
     */
659
    public function relationResolver($class, $key)
660
    {
661
        return null;
662
    }
663
664
    /**
665
     * Save the model in Halo
666
     *
667
     * @throws NoClientException
668
     * @throws TokenException
669
     */
670
    public function save(): bool
671
    {
672
        // TODO: Make sure that the model supports being saved
673
        if ($this->readonlyModel) {
674
            return false;
675
        }
676
677
        try {
678
            if (! $this->isDirty()) {
679
                return true;
680
            }
681
682
            if ($this->exists) {
683
                // TODO: If we get null from the PUT, throw/handle exception
684
                $response = $this->getClient()
685
                                 ->put($this->getPath(), $this->getDirty());
686
687
                // Record the changes
688
                $this->syncChanges();
689
690
                // Reset the model with the results as we get back the full model
691
                $this->setRawAttributes($response, true);
0 ignored issues
show
Bug introduced by
It seems like $response can also be of type null; however, parameter $attributes of Spinen\Halo\Support\Model::setRawAttributes() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

691
                $this->setRawAttributes(/** @scrutinizer ignore-type */ $response, true);
Loading history...
692
693
                return true;
694
            }
695
696
            $response = $this->getClient()
697
                             ->post($this->getPath(), $this->toArray());
698
699
            $this->exists = true;
700
701
            $this->wasRecentlyCreated = true;
702
703
            // Reset the model with the results as we get back the full model
704
            $this->setRawAttributes($response, true);
705
706
            return true;
707
        } catch (GuzzleException $e) {
708
            // TODO: Do something with the error
709
710
            return false;
711
        }
712
    }
713
714
    /**
715
     * Save the model in Halo, but raise error if fail
716
     *
717
     * @throws NoClientException
718
     * @throws TokenException
719
     * @throws UnableToSaveException
720
     */
721
    public function saveOrFail(): bool
722
    {
723
        if (! $this->save()) {
724
            throw new UnableToSaveException();
725
        }
726
727
        return true;
728
    }
729
730
    /**
731
     * Set the readonly
732
     *
733
     * @param  bool  $readonly
734
     * @return $this
735
     */
736
    public function setReadonly($readonly = true): self
737
    {
738
        $this->readonlyModel = $readonly;
739
740
        return $this;
741
    }
742
743
    /**
744
     * Set the given relationship on the model.
745
     *
746
     * @param  string  $relation
747
     * @return $this
748
     */
749
    public function setRelation($relation, $value): self
750
    {
751
        $this->relations[$relation] = $value;
752
753
        return $this;
754
    }
755
756
    /**
757
     * Convert the model instance to an array.
758
     */
759
    public function toArray(): array
760
    {
761
        return array_merge($this->attributesToArray(), $this->relationsToArray());
762
    }
763
764
    /**
765
     * Convert the model instance to JSON.
766
     *
767
     * @param  int  $options
768
     *
769
     * @throws JsonEncodingException
770
     */
771
    public function toJson($options = 0): string
772
    {
773
        $json = json_encode($this->jsonSerialize(), $options);
774
775
        // @codeCoverageIgnoreStart
776
        if (JSON_ERROR_NONE !== json_last_error()) {
777
            throw JsonEncodingException::forModel($this, json_last_error_msg());
778
        }
779
        // @codeCoverageIgnoreEnd
780
781
        return $json;
782
    }
783
}
784