Passed
Push — master ( ef2d88...898186 )
by Arthur
06:43
created

Transformer   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 49
rs 10
c 0
b 0
f 0
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A collection() 0 3 1
A serialize() 0 3 1
A includeRelations() 0 17 5
A resolve() 0 3 1
A resource() 0 3 1
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
12
use Illuminate\Database\Eloquent\Collection;
13
use Illuminate\Http\Resources\Json\JsonResource;
14
15
abstract class Transformer extends JsonResource
16
{
17
    public $relations = [
18
19
    ];
20
21
    /**
22
     * Resolve the resource to an array.
23
     *
24
     * @param  \Illuminate\Http\Request|null $request
25
     * @return array
26
     */
27
    public function resolve($request = null)
28
    {
29
        return array_merge(parent::resolve($request),$this->filter($this->includeRelations()));
30
    }
31
32
    protected function includeRelations()
33
    {
34
        $relations = [];
35
        foreach ($this->relations as $relation) {
36
            if (is_string($relation) && method_exists(static::class, 'transform' . ucfirst(strtolower($relation)))) {
37
                $method = 'transform' . ucfirst(strtolower($relation));
38
                $data = $this->$method($this->resource);
39
                if ($data instanceof JsonResource) {
40
                    $data->jsonSerialize();
41
                }
42
                $relations[strtolower($relation)] = $data;
43
            } else {
44
                throw new \Exception("invalid relation or not relation_transform_method given in " . get_short_class_name(static::class));
45
            }
46
47
        }
48
        return $relations;
49
    }
50
51
    public static function resource($model)
52
    {
53
        return new static($model);
54
    }
55
56
    public static function collection($resource)
57
    {
58
        return new TransformerCollection($resource, get_called_class());
59
    }
60
61
    public function serialize()
62
    {
63
        return json_decode(json_encode($this->jsonSerialize()), true);
64
    }
65
}
66