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
|
|
|
|