Completed
Push — master ( 09e7b0...b7cea0 )
by Pavel
03:54
created

RestResponseFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php namespace Pz\Doctrine\Rest;
2
3
use League\Fractal\Resource\ResourceInterface;
4
use Pz\Doctrine\Rest\Contracts\RestRequestContract;
5
use Pz\Doctrine\Rest\Fractal\JsonApiSerializer;
6
use Pz\Doctrine\Rest\Fractal\Manager;
7
use Pz\Doctrine\Rest\Fractal\ScopeFactory;
8
use Symfony\Component\HttpFoundation\JsonResponse;
9
10
class RestResponseFactory
11
{
12
    /**
13
     * @var int
14
     */
15
    protected $jsonEncodingOptions;
16
17
    /**
18
     * RestResponseFactory constructor.
19
     * @param int $jsonEncodingOptions
20
     */
21 28
    public function __construct($jsonEncodingOptions = null)
22
    {
23 28
        $this->jsonEncodingOptions = $jsonEncodingOptions;
24 28
    }
25
26
    /**
27
     * Return configured fractal by request format.
28
     *
29
     * @param RestRequestContract $request
30
     *
31
     * @return Manager
32
     */
33 19
    protected function fractal(RestRequestContract $request)
34
    {
35 19
        $fractal = new Manager(new ScopeFactory(), $request);
36 19
        $fractal->setSerializer(new JsonApiSerializer($request));
37
38 19
        if ($includes = $request->getInclude()) {
39 19
            $fractal->parseIncludes($includes);
40
        }
41
42 19
        if ($excludes = $request->getExclude()) {
43 1
            $fractal->parseExcludes($excludes);
44
        }
45
46 19
        if ($fields = $request->getFields()) {
47 5
            $fractal->parseFieldsets($fields);
48
        }
49
50 19
        return $fractal;
51
    }
52
53
    /**
54
     * @param RestRequestContract    $request
55
     * @param ResourceInterface|null $resource
56
     * @param int                    $httStatus
57
     * @param array                  $headers
58
     *
59
     * @return RestResponse
60
     */
61 19
    public function resource(
62
        RestRequestContract $request,
63
        ResourceInterface   $resource = null,
64
        int                 $httStatus = RestResponse::HTTP_OK,
65
        array               $headers = []
66
    ) {
67 19
        $data = $resource ? $this->fractal($request)->createData($resource)->toArray() : null;
68
69 19
        $response = RestResponse::create($data, $httStatus, $headers);
70
71 19
        if ($this->jsonEncodingOptions) {
72
            $response->setEncodingOptions($this->jsonEncodingOptions);
73
        }
74
75 19
        return $response;
76
    }
77
78
    /**
79
     * @return RestResponse
80
     */
81 4
    public function noContent()
82
    {
83 4
        return RestResponse::noContent();
84
    }
85
}
86