Completed
Pull Request — master (#83)
by
unknown
01:49
created

Fractal   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 69
rs 10
c 1
b 0
f 0
wmc 9
lcom 0
cbo 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B respond() 0 28 5
A create() 0 16 3
1
<?php
2
3
namespace Spatie\Fractal;
4
5
use League\Fractal\Manager;
6
use Illuminate\Http\JsonResponse;
7
use Spatie\Fractalistic\Fractal as Fractalistic;
8
use League\Fractal\Serializer\SerializerAbstract;
9
10
class Fractal extends Fractalistic
11
{
12
    /** @param \League\Fractal\Manager $manager */
13
    public function __construct(Manager $manager)
14
    {
15
        parent::__construct($manager);
16
    }
17
18
    /**
19
     * Return a new JSON response.
20
     *
21
     * @param  callable|int $statusCode
22
     * @param  callable|array $headers
23
     *
24
     * @return \Illuminate\Http\JsonResponse
25
     */
26
    public function respond($statusCode = 200, $headers = [])
27
    {
28
        $response = new JsonResponse();
29
30
        $response->setData($this->createData()->toArray());
31
32
        if (is_int($statusCode)) {
33
            $statusCode = function (JsonResponse $response) use ($statusCode) {
34
                return $response->setStatusCode($statusCode);
35
            };
36
        }
37
38
        if (is_array($headers)) {
39
            $headers = function (JsonResponse $response) use ($headers) {
40
                return $response->withHeaders($headers);
41
            };
42
        }
43
44
        if (is_callable($statusCode)) {
45
            $statusCode($response);
46
        }
47
48
        if (is_callable($headers)) {
49
            $headers($response);
50
        }
51
52
        return $response;
53
    }
54
55
    /**
56
     * @param null|mixed $data
57
     * @param null|callable|\League\Fractal\TransformerAbstract $transformer
58
     * @param null|\League\Fractal\Serializer\SerializerAbstract $serializer
59
     *
60
     * @return \Spatie\Fractalistic\Fractal
61
     */
62
    public static function create($data = null, $transformer = null, $serializer = null)
63
    {
64
        $fractal = parent::create($data, $transformer, $serializer);
65
66
        $serializer = config('laravel-fractal.default_serializer');
67
68
        if (! empty($serializer)) {
69
            if ($serializer instanceof SerializerAbstract) {
70
                $fractal->serializeWith($serializer);
71
            } else {
72
                $fractal->serializeWith(new $serializer());
73
            }
74
        }
75
76
        return $fractal;
77
    }
78
}
79