Passed
Push — master ( 383b45...c02d9e )
by Pavel
01:44
created

RestResponseFactory::fractal()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 8
nop 1
dl 0
loc 18
ccs 10
cts 10
cp 1
crap 4
rs 9.2
c 0
b 0
f 0
1
<?php namespace Pz\Doctrine\Rest;
2
3
use League\Fractal\Manager;
4
use League\Fractal\Resource\ResourceInterface;
5
use League\Fractal\Serializer\JsonApiSerializer;
6
use Pz\Doctrine\Rest\Contracts\RestRequestContract;
7
8
class RestResponseFactory
9
{
10
    /**
11
     * Return configured fractal by request format.
12
     *
13
     * @param RestRequestContract $request
14
     *
15
     * @return Manager
16
     */
17 11
    protected static function fractal(RestRequestContract $request)
18
    {
19 11
        $fractal = new Manager();
20 11
        $fractal->setSerializer(new JsonApiSerializer($request->getBaseUrl()));
21
22 11
        if ($includes = $request->getInclude()) {
23 4
            $fractal->parseIncludes($includes);
24
        }
25
26 11
        if ($excludes = $request->getExclude()) {
27 1
            $fractal->parseExcludes($excludes);
28
        }
29
30 11
        if ($fields = $request->getFields()) {
31 4
            $fractal->parseFieldsets($fields);
32
        }
33
34 11
        return $fractal;
35
    }
36
37
    /**
38
     * @param RestRequestContract    $request
39
     * @param ResourceInterface|null $resource
40
     * @param int                    $httStatus
41
     * @param array                  $headers
42
     *
43
     * @return RestResponse
44
     */
45 11
    public function resource(
46
        RestRequestContract         $request,
47
        ResourceInterface   $resource = null,
48
        int                 $httStatus = RestResponse::HTTP_OK,
49
        array               $headers = []
50
    ) {
51 11
        $data = $resource ? $this->fractal($request)->createData($resource)->toArray() : null;
52
53 10
        return RestResponse::create($data, $httStatus, $headers);
54
    }
55
}
56