Completed
Pull Request — master (#47)
by Freek
04:15
created

FractalFunctionHelper   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 87
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 87
rs 10
c 0
b 0
f 0
wmc 12
lcom 1
cbo 2

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B getFractalInstance() 0 22 5
A setData() 0 6 1
A determineDataType() 0 12 3
A setTransformer() 0 4 1
A setSerializer() 0 4 1
1
<?php
2
3
namespace Spatie\Fractal;
4
5
use League\Fractal\Serializer\SerializerAbstract;
6
use Spatie\Fractal\Exceptions\InvalidFractalHelperArgument;
7
use Traversable;
8
9
class FractalFunctionHelper
10
{
11
    /** @var \Spatie\Fractal\Fractal */
12
    protected $fractal;
13
14
    /** @var array */
15
    protected $arguments;
16
17
    public function __construct(array $arguments)
18
    {
19
        $this->fractal = app(Fractal::class);
20
21
        $this->arguments = $arguments;
22
    }
23
24
    /**
25
     * @return \Spatie\Fractal\Fractal
26
     *
27
     * @throws \Spatie\Fractal\Exceptions\InvalidFractalHelperArgument
28
     */
29
    public function getFractalInstance()
30
    {
31
        if (count($this->arguments) === 1) {
32
            throw InvalidFractalHelperArgument::secondArgumentMissing();
33
        }
34
35
        if (count($this->arguments) >= 2) {
36
            $this->setData($this->arguments[0]);
37
38
            $this->setTransformer($this->arguments[1]);
39
        }
40
41
        if (count($this->arguments) >= 3) {
42
            $this->setSerializer($this->arguments[2]);
43
        }
44
45
        if (count($this->arguments) > 3) {
46
            throw InvalidFractalHelperArgument::tooManyArguments($this->arguments);
47
        }
48
49
        return $this->fractal;
50
    }
51
52
    /**
53
     * @param mixed $data
54
     */
55
    public function setData($data)
56
    {
57
        $dataType = $this->determineDataType($data);
58
59
        $this->fractal->data($dataType, $data);
60
    }
61
62
    /**
63
     * @param mixed $data
64
     *
65
     * @return string
66
     */
67
    protected function determineDataType($data)
68
    {
69
        if (is_array($data)) {
70
            return 'collection';
71
        }
72
73
        if ($data instanceof Traversable) {
74
            return 'collection';
75
        }
76
77
        return 'item';
78
    }
79
80
    /**
81
     * @param callable|\League\Fractal\TransformerAbstract $transformer
82
     */
83
    protected function setTransformer($transformer)
84
    {
85
        $this->fractal->transformWith($transformer);
86
    }
87
88
    /**
89
     * @param \League\Fractal\Serializer\SerializerAbstract $serializer
90
     */
91
    protected function setSerializer(SerializerAbstract $serializer)
92
    {
93
        $this->fractal->serializeWith($serializer);
94
    }
95
}
96