Test Setup Failed
Push — v2 ( 74186a...c94b75 )
by Alexander
06:56
created

DataNormalizer   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 51
rs 10
c 0
b 0
f 0
wmc 10
lcom 0
cbo 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B normalize() 0 12 5
A normalizeRelation() 0 4 2
A isSingularRelation() 0 12 3
1
<?php
2
3
namespace Flugg\Responder\Resources;
4
5
use Flugg\Responder\Pagination\CursorPaginator;
6
use Illuminate\Contracts\Pagination\Paginator;
7
use Illuminate\Database\Eloquent\Relations\BelongsTo;
8
use Illuminate\Database\Eloquent\Relations\HasOne;
9
use Illuminate\Database\Eloquent\Relations\MorphOne;
10
use Illuminate\Database\Eloquent\Relations\MorphTo;
11
use Illuminate\Database\Eloquent\Relations\Relation;
12
use Illuminate\Database\Query\Builder;
13
14
/**
15
 * This class is responsible for normalizing resource data.
16
 *
17
 * @package flugger/laravel-responder
18
 * @author  Alexander Tømmerås <[email protected]>
19
 * @license The MIT License
20
 */
21
class DataNormalizer
22
{
23
    /**
24
     * Normalize the data for a resource.
25
     *
26
     * @param  mixed $data
27
     * @return mixed
28
     */
29
    public function normalize($data = null)
30
    {
31
        if ($data instanceof Builder || $data instanceof CursorPaginator) {
32
            return $data->get();
33
        } elseif ($data instanceof Paginator) {
34
            return $data->getCollection();
35
        } elseif ($data instanceof Relation) {
36
            return $this->normalizeRelation($data);
37
        }
38
39
        return $data;
40
    }
41
42
    /**
43
     * Normalize a relationship.
44
     *
45
     * @param  \Illuminate\Database\Eloquent\Relations\Relation $relation
46
     * @return \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|null
47
     */
48
    protected function normalizeRelation(Relation $relation)
49
    {
50
        return $this->isSingularRelation($relation) ? $relation->first() : $relation->get();
51
    }
52
53
    /**
54
     * Indicates if a relationship is singular.
55
     *
56
     * @param  \Illuminate\Database\Eloquent\Relations\Relation $relation
57
     * @return bool
58
     */
59
    protected function isSingularRelation(Relation $relation): bool
60
    {
61
        $singularRelations = [BelongsTo::class, HasOne::class, MorphOne::class, MorphTo::class];
62
63
        foreach ($singularRelations as $singularRelation) {
64
            if ($relation instanceof $singularRelation) {
65
                return true;
66
            }
67
        }
68
69
        return false;
70
    }
71
}