Completed
Pull Request — master (#1)
by
unknown
04:31
created

Model::toJson()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 11
ccs 3
cts 3
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Spinen\ClickUp\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 JsonSerializable;
17
use LogicException;
18
use Spinen\ClickUp\Concerns\HasClient;
19
use Spinen\ClickUp\Exceptions\InvalidRelationshipException;
20
use Spinen\ClickUp\Exceptions\ModelNotFoundException;
21
use Spinen\ClickUp\Exceptions\ModelReadonlyException;
22
use Spinen\ClickUp\Exceptions\NoClientException;
23
use Spinen\ClickUp\Exceptions\TokenException;
24
use Spinen\ClickUp\Exceptions\UnableToSaveException;
25
use Spinen\ClickUp\Support\Relations\BelongsTo;
26
use Spinen\ClickUp\Support\Relations\ChildOf;
27
use Spinen\ClickUp\Support\Relations\HasMany;
28
use Spinen\ClickUp\Support\Relations\Relation;
29
30
/**
31
 * Class Model
32
 *
33
 * @package Spinen\ClickUp\Support
34
 */
35
abstract class Model implements Arrayable, ArrayAccess, Jsonable, JsonSerializable
36
{
37
    use HasAttributes {
38
        asDateTime as originalAsDateTime;
39
    }
40
    use HasClient, HasTimestamps, HidesAttributes;
41
42
    /**
43
     * Indicates if the model exists.
44
     *
45
     * @var bool
46
     */
47
    public $exists = false;
48
49
    /**
50
     * Indicates if the IDs are auto-incrementing.
51
     *
52
     * @var bool
53
     */
54
    public $incrementing = false;
55
56
    /**
57
     * The "type" of the primary key ID.
58
     *
59
     * @var string
60
     */
61
    protected $keyType = 'int';
62
63
    /**
64
     * Is resource nested behind parentModel
65
     *
66
     * Several of the endpoints are nested behind another model for relationship, but then to
67
     * interact with the specific model, then are not nested.  This property will know when to
68
     * keep the specific model nested.
69
     *
70
     * @var bool
71
     */
72
    protected $nested = false;
73
74
    /**
75
     * Optional parentModel instance
76
     *
77
     * @var Model $parentModel
78
     */
79
    public $parentModel;
80
81
    /**
82
     * Path to API endpoint.
83
     *
84
     * @var string
85
     */
86
    protected $path = null;
87
88
    /**
89
     * The primary key for the model.
90
     *
91
     * @var string
92
     */
93
    protected $primaryKey = 'id';
94
95
    /**
96
     * Is the model readonly?
97
     *
98
     * @var bool
99
     */
100
    protected $readonlyModel = false;
101
102
    /**
103
     * The loaded relationships for the model.
104
     *
105
     * @var array
106
     */
107
    protected $relations = [];
108
109
    /**
110
     * Some of the responses have the collections under a property
111
     *
112
     * @var string|null
113
     */
114
    protected $responseCollectionKey = null;
115
116
    /**
117
     * Some of the responses have the data under a property
118
     *
119
     * @var string|null
120
     */
121
    protected $responseKey = null;
122
123
    /**
124
     * Are timestamps in milliseconds?
125
     *
126
     * @var boolean
127
     */
128
    protected $timestampsInMilliseconds = true;
129
130
    /**
131
     * The name of the "created at" column.
132
     *
133
     * @var string
134
     */
135
    const CREATED_AT = 'created_at';
136
137
    /**
138
     * The name of the "updated at" column.
139
     *
140
     * @var string
141
     */
142
    const UPDATED_AT = 'updated_at';
143
144
    /**
145
     * Model constructor.
146
     *
147
     * @param array|null $attributes
148
     * @param Model|null $parentModel
149
     */
150 190
    public function __construct(array $attributes = [], Model $parentModel = null)
151
    {
152
        // All dates from API comes as epoch
153 190
        $this->dateFormat = 'U';
154
        // None of this  models will use timestamps, but need the date casting
155 190
        $this->timestamps = false;
156
157 190
        $this->syncOriginal();
158
159 190
        $this->fill($attributes);
160 190
        $this->parentModel = $parentModel;
161
    }
162
163
    /**
164
     * Dynamically retrieve attributes on the model.
165
     *
166
     * @param string $key
167
     *
168
     * @return mixed
169
     */
170 94
    public function __get($key)
171
    {
172 94
        return $this->getAttribute($key);
173
    }
174
175
    /**
176
     * Determine if an attribute or relation exists on the model.
177
     *
178
     * @param string $key
179
     *
180
     * @return bool
181
     */
182 2
    public function __isset($key)
183
    {
184 2
        return $this->offsetExists($key);
185
    }
186
187
    /**
188
     * Dynamically set attributes on the model.
189
     *
190
     * @param string $key
191
     * @param mixed $value
192
     *
193
     * @return void
194
     * @throws ModelReadonlyException
195
     */
196 79
    public function __set($key, $value)
197
    {
198 79
        if ($this->readonlyModel) {
199 1
            throw new ModelReadonlyException();
200
        }
201
202 78
        $this->setAttribute($key, $value);
203
    }
204
205
    /**
206
     * Convert the model to its string representation.
207
     *
208
     * @return string
209
     */
210 1
    public function __toString()
211
    {
212 1
        return $this->toJson();
213
    }
214
215
    /**
216
     * Unset an attribute on the model.
217
     *
218
     * @param string $key
219
     *
220
     * @return void
221
     */
222 2
    public function __unset($key)
223
    {
224 2
        $this->offsetUnset($key);
225
    }
226
227
    /**
228
     * Return a timestamp as DateTime object.
229
     *
230
     * @param  mixed  $value
231
     * @return \Illuminate\Support\Carbon
232
     */
233
    protected function asDateTime($value)
234
    {
235
        if (is_numeric($value) && $this->timestampsInMilliseconds) {
236
            return Date::createFromTimestampMs($value);
237
        }
238
239
        return $this->originalAsDateTime($value);
240
    }
241
242
    /**
243
     * Assume foreign key
244
     *
245
     * @param string $related
246
     *
247
     * @return string
248
     */
249 30
    protected function assumeForeignKey($related): string
250
    {
251 30
        return Str::snake((new $related())->getResponseKey()) . '_id';
252
    }
253
254
    /**
255
     * Relationship that makes the model belongs to another model
256
     *
257
     * @param string $related
258
     * @param string|null $foreignKey
259
     *
260
     * @return BelongsTo
261
     * @throws InvalidRelationshipException
262
     * @throws ModelNotFoundException
263
     * @throws NoClientException
264
     */
265 8
    public function belongsTo($related, $foreignKey = null): BelongsTo
266
    {
267 8
        $foreignKey = is_null($foreignKey) ? $this->assumeForeignKey($related) : $foreignKey;
268
269 8
        $builder = (new Builder())->setClass($related)
270 8
                                  ->setClient($this->getClient());
271
272 8
        return new BelongsTo($builder, $this, $foreignKey);
273
    }
274
275
    /**
276
     * Relationship that makes the model child to another model
277
     *
278
     * @param string $related
279
     * @param string|null $foreignKey
280
     *
281
     * @return ChildOf
282
     * @throws InvalidRelationshipException
283
     * @throws ModelNotFoundException
284
     * @throws NoClientException
285
     */
286 25
    public function childOf($related, $foreignKey = null): ChildOf
287
    {
288 25
        $foreignKey = is_null($foreignKey) ? $this->assumeForeignKey($related) : $foreignKey;
289
290 25
        $builder = (new Builder())->setClass($related)
291 25
                                  ->setClient($this->getClient())
292 25
                                  ->setParent($this);
293
294 25
        return new ChildOf($builder, $this, $foreignKey);
295
    }
296
297
    /**
298
     * Delete the model from ClickUp
299
     *
300
     * @return boolean
301
     * @throws NoClientException
302
     * @throws TokenException
303
     */
304 3
    public function delete(): bool
305
    {
306
        // TODO: Make sure that the model supports being deleted
307 3
        if ($this->readonlyModel) {
308 1
            return false;
309
        }
310
311
        try {
312 2
            $this->getClient()
313 2
                 ->delete($this->getPath());
314
315 1
            return true;
316 1
        } catch (GuzzleException $e) {
317
            // TODO: Do something with the error
318
319 1
            return false;
320
        }
321
    }
322
323
    /**
324
     * Fill the model with the supplied properties
325
     *
326
     * @param array $attributes
327
     *
328
     * @return $this
329
     */
330 190
    public function fill(array $attributes = []): self
331
    {
332 190
        foreach ($attributes as $attribute => $value) {
333 51
            $this->setAttribute($attribute, $value);
334
        }
335
336 190
        return $this;
337
    }
338
339
    /**
340
     * Get the value indicating whether the IDs are incrementing.
341
     *
342
     * @return bool
343
     */
344 122
    public function getIncrementing(): bool
345
    {
346 122
        return $this->incrementing;
347
    }
348
349
    /**
350
     * Get the value of the model's primary key.
351
     *
352
     * @return mixed
353
     */
354 23
    public function getKey()
355
    {
356 23
        return $this->getAttribute($this->getKeyName());
357
    }
358
359
    /**
360
     * Get the primary key for the model.
361
     *
362
     * @return string
363
     */
364 57
    public function getKeyName(): string
365
    {
366 57
        return $this->primaryKey;
367
    }
368
369
    /**
370
     * Get the auto-incrementing key type.
371
     *
372
     * @return string
373
     */
374 1
    public function getKeyType(): string
375
    {
376 1
        return $this->keyType;
377
    }
378
379
    /**
380
     * Build API path
381
     *
382
     * Put anything on the end of the URI that is passed in
383
     *
384
     * @param string|null $extra
385
     * @param array|null $query
386
     *
387
     * @return string
388
     */
389 22
    public function getPath($extra = null, array $query = []): ?string
390
    {
391
        // Start with path to resource without "/" on end
392 22
        $path = rtrim($this->path, '/');
393
394
        // If have an id, then put it on the end
395 22
        if ($this->getKey()) {
396 6
            $path .= '/' . $this->getKey();
397
        }
398
399
        // Stick any extra things on the end
400 22
        if (!is_null($extra)) {
401 4
            $path .= '/' . ltrim($extra, '/');
402
        }
403
404
        // Convert query to querystring format and put on the end
405 22
        if (!empty($query)) {
406 2
            $path .= '?' . http_build_query($query);
407
        }
408
409
        // If there is a parentModel & not have an id (unless for nested), then prepend parentModel
410 22
        if (!is_null($this->parentModel) && (!$this->getKey() || $this->isNested())) {
411 4
            return $this->parentModel->getPath($path);
412
        }
413
414 22
        return $path;
415
    }
416
417
    /**
418
     * Get a relationship value from a method.
419
     *
420
     * @param string $method
421
     *
422
     * @return mixed
423
     *
424
     * @throws LogicException
425
     */
426 5
    public function getRelationshipFromMethod($method)
427
    {
428 5
        $relation = $this->{$method}();
429
430 5
        if (!$relation instanceof Relation) {
431 2
            if (is_null($relation)) {
432 1
                throw new LogicException(
433 1
                    sprintf(
434 1
                        '%s::%s must return a relationship instance, but "null" was returned. Was the "return" keyword used?',
435 1
                        static::class,
436 1
                        $method
437
                    )
438
                );
439
            }
440
441 1
            throw new LogicException(
442 1
                sprintf(
443 1
                    '%s::%s must return a relationship instance.',
444 1
                    static::class,
445 1
                    $method
446
                )
447
            );
448
        }
449
450 3
        return tap(
451 3
            $relation->getResults(),
452
            function ($results) use ($method) {
453 3
                $this->setRelation($method, $results);
454 3
            }
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
     * @return string|null
464
     */
465 14
    public function getResponseCollectionKey(): ?string
466
    {
467 14
        return $this->responseCollectionKey ?? Str::plural($this->getResponseKey());
468
    }
469
470
    /**
471
     * Name of the wrapping key of response
472
     *
473
     * If none provided, assume camelCase of class name
474
     *
475
     * @return string|null
476
     */
477 46
    public function getResponseKey(): ?string
478
    {
479 46
        return $this->responseKey ?? Str::camel(class_basename(static::class));
480
    }
481
482
    /**
483
     * Many of the results include collection of related data, so cast it
484
     *
485
     * @param string $related
486
     * @param array $given
487
     * @param bool $reset Some of the values are nested under a property, so peel it off
488
     *
489
     * @return Collection
490
     * @throws NoClientException
491
     */
492 20
    public function givenMany($related, $given, $reset = false): Collection
493
    {
494
        /** @var Model $model */
495 20
        $model = (new $related([], $this->parentModel))->setClient($this->getClient());
496
497 20
        return (new Collection($given))->map(
498
            function ($attributes) use ($model, $reset) {
499 1
                return $model->newFromBuilder($reset ? reset($attributes) : $attributes);
500 20
            }
501
        );
502
    }
503
504
    /**
505
     * Many of the results include related data, so cast it to object
506
     *
507
     * @param string $related
508
     * @param array $attributes
509
     * @param bool $reset Some of the values are nested under a property, so peel it off
510
     *
511
     * @return Model
512
     * @throws NoClientException
513
     */
514 16
    public function givenOne($related, $attributes, $reset = false): Model
515
    {
516 16
        return (new $related([], $this->parentModel))->setClient($this->getClient())
517 16
                                                     ->newFromBuilder($reset ? reset($attributes) : $attributes);
518
    }
519
520
    /**
521
     * Relationship that makes the model have a collection of another model
522
     *
523
     * @param string $related
524
     *
525
     * @return HasMany
526
     * @throws InvalidRelationshipException
527
     * @throws ModelNotFoundException
528
     * @throws NoClientException
529
     */
530 27
    public function hasMany($related): HasMany
531
    {
532 27
        $builder = (new Builder())->setClass($related)
533 27
                                  ->setClient($this->getClient())
534 27
                                  ->setParent($this);
535
536 27
        return new HasMany($builder, $this);
537
    }
538
539
    /**
540
     * Is endpoint nested behind another endpoint
541
     *
542
     * @return bool
543
     */
544 2
    public function isNested(): bool
545
    {
546 2
        return $this->nested ?? false;
547
    }
548
549
    /**
550
     * Convert the object into something JSON serializable.
551
     *
552
     * @return array
553
     */
554 1
    public function jsonSerialize(): array
555
    {
556 1
        return $this->toArray();
557
    }
558
559
    /**
560
     * Create a new model instance that is existing.
561
     *
562
     * @param array $attributes
563
     *
564
     * @return static
565
     */
566 24
    public function newFromBuilder($attributes = []): self
567
    {
568 24
        $model = $this->newInstance([], true);
569
570 24
        $model->setRawAttributes((array)$attributes, true);
571
572 24
        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 array $attributes
582
     * @param bool $exists
583
     *
584
     * @return static
585
     */
586 29
    public function newInstance(array $attributes = [], $exists = false): self
587
    {
588 29
        $model = (new static($attributes, $this->parentModel))->setClient($this->client);
589
590 29
        $model->exists = $exists;
591
592 29
        return $model;
593
    }
594
595
    /**
596
     * Determine if the given attribute exists.
597
     *
598
     * @param mixed $offset
599
     *
600
     * @return bool
601
     */
602 5
    public function offsetExists($offset)
603
    {
604 5
        return !is_null($this->getAttribute($offset));
605
    }
606
607
    /**
608
     * Get the value for a given offset.
609
     *
610
     * @param mixed $offset
611
     *
612
     * @return mixed
613
     */
614 2
    public function offsetGet($offset)
615
    {
616 2
        return $this->getAttribute($offset);
617
    }
618
619
    /**
620
     * Set the value for a given offset.
621
     *
622
     * @param mixed $offset
623
     * @param mixed $value
624
     *
625
     * @return void
626
     * @throws ModelReadonlyException
627
     */
628 2
    public function offsetSet($offset, $value): void
629
    {
630 2
        if ($this->readonlyModel) {
631 1
            throw new ModelReadonlyException();
632
        }
633
634 1
        $this->setAttribute($offset, $value);
635
    }
636
637
    /**
638
     * Unset the value for a given offset.
639
     *
640
     * @param mixed $offset
641
     *
642
     * @return void
643
     */
644 3
    public function offsetUnset($offset): void
645
    {
646 3
        unset($this->attributes[$offset], $this->relations[$offset]);
647
    }
648
649
    /**
650
     * Determine if the given relation is loaded.
651
     *
652
     * @param string $key
653
     *
654
     * @return bool
655
     */
656 60
    public function relationLoaded($key): bool
657
    {
658 60
        return array_key_exists($key, $this->relations);
659
    }
660
661
    /**
662
     * Save the model in ClickUp
663
     *
664
     * @return bool
665
     * @throws NoClientException
666
     * @throws TokenException
667
     */
668 7
    public function save(): bool
669
    {
670
        // TODO: Make sure that the model supports being saved
671 7
        if ($this->readonlyModel) {
672 1
            return false;
673
        }
674
675
        try {
676 6
            if (!$this->isDirty()) {
677 1
                return true;
678
            }
679
680 5
            if ($this->exists) {
681 1
                $response = $this->getClient()
682 1
                                 ->put($this->getPath(), $this->getDirty());
683
684
                // Record the changes
685 1
                $this->syncChanges();
686
687
                // Reset the model with the results as we get back the full model
688 1
                $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\ClickUp\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

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