Passed
Push — master ( c13b73...f2713c )
by Arthur
05:06
created

TransformerCollection   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 49
rs 10
c 0
b 0
f 0
ccs 1
cts 1
cp 1
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A serialize() 0 3 1
A toArray() 0 9 2
A findIncludedRelations() 0 7 2
A preloadModelRelations() 0 8 3
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: arthur
5
 * Date: 29.10.18
6
 * Time: 09:35.
7
 */
8
9
namespace Foundation\Abstracts\Transformers;
10
11
use Foundation\Contracts\Transformable;
12
use Illuminate\Container\Container;
13
use Illuminate\Database\Eloquent\Model;
14
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
15 3
16
class TransformerCollection extends AnonymousResourceCollection
17 3
{
18
    protected $relations = [];
19
20
    public function __construct($resource, string $collects)
21
    {
22
        $this->relations = $this->findIncludedRelations(Container::getInstance()->make('request'), $resource, $collects);
23
        $resource = $this->preloadModelRelations($resource);
24
        parent::__construct($resource, $collects);
25
    }
26
27
    /**
28
     * @param $request
29
     * @throws \Exception
30
     */
31
    protected function findIncludedRelations($request, $resource, $collects)
32
    {
33
        if (class_implements_interface($collects,Transformable::class)) {
34
            $transformer = $collects::resource($resource->first());
35
            $relations = $transformer->getIncludedRelations($request);
36
        }
37
        return $relations;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $relations does not seem to be defined for all execution paths leading up to this point.
Loading history...
38
    }
39
40
    protected function preloadModelRelations($resource)
41
    {
42
        if ($resource instanceof Model) {
43
            foreach ($this->relations as $relation) {
44
                $resource->load($relation);
45
            }
46
        }
47
        return $resource;
48
    }
49
50
    public function toArray($request)
51
    {
52
        $collection = $this->collection->map(function ($item) {
53
            if ($item instanceof Transformer)
54
                return $item->include($this->relations);
55
            else
56
                return $item;
57
        });
58
        return $collection->map->resolve($request)->all();
59
    }
60
61
62
    public function serialize()
63
    {
64
        return json_decode(json_encode($this->jsonSerialize()), true);
65
    }
66
}
67