1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Phprest\Service\Hateoas; |
4
|
|
|
|
5
|
|
|
use Hateoas\Hateoas; |
6
|
|
|
use JMS\Serializer\DeserializationContext; |
7
|
|
|
use JMS\Serializer\SerializationContext; |
8
|
|
|
use Negotiation\FormatNegotiator; |
9
|
|
|
use Phprest\Exception; |
10
|
|
|
use Phprest\Util\Mime; |
11
|
|
|
use Symfony\Component\HttpFoundation\Request; |
12
|
|
|
use Symfony\Component\HttpFoundation\Response; |
13
|
|
|
|
14
|
|
|
trait Util |
15
|
|
|
{ |
16
|
|
|
use Mime; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param mixed $value |
20
|
|
|
* @param Request $request |
21
|
|
|
* @param Response $response |
22
|
|
|
* |
23
|
|
|
* @throws Exception\NotAcceptable |
24
|
|
|
* |
25
|
|
|
* @return Response |
26
|
|
|
*/ |
27
|
3 |
|
protected function serialize($value, Request $request, Response $response) |
28
|
|
|
{ |
29
|
3 |
|
$mimeProcResult = $this->processMime( |
30
|
3 |
|
(new FormatNegotiator())->getBest($request->headers->get('Accept', '*/*'))->getValue() |
31
|
|
|
); |
32
|
|
|
|
33
|
2 |
|
if ($mimeProcResult->mime === '*/*') { |
34
|
|
|
$mimeProcResult->mime = 'application/vnd.' . $mimeProcResult->vendor . |
35
|
|
|
'+json; version=' . $mimeProcResult->apiVersion; |
36
|
|
|
$mimeProcResult->format = 'json'; |
37
|
|
|
} |
38
|
|
|
|
39
|
2 |
|
if (in_array($mimeProcResult->format, ['json', 'xml'])) { |
40
|
2 |
|
$response->setContent( |
41
|
2 |
|
$this->serviceHateoas()->serialize( |
42
|
2 |
|
$value, |
43
|
2 |
|
$mimeProcResult->format, |
44
|
2 |
|
SerializationContext::create()->setVersion($mimeProcResult->apiVersion) |
|
|
|
|
45
|
|
|
) |
46
|
|
|
); |
47
|
|
|
|
48
|
2 |
|
$response->headers->set('Content-Type', $mimeProcResult->mime); |
49
|
|
|
|
50
|
2 |
|
return $response; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
throw new Exception\NotAcceptable(0, [$mimeProcResult->mime . ' is not supported']); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param string $type |
58
|
|
|
* @param Request $request |
59
|
|
|
* |
60
|
|
|
* @throws Exception\UnsupportedMediaType |
61
|
|
|
* |
62
|
|
|
* @return mixed |
63
|
|
|
*/ |
64
|
2 |
|
protected function deserialize($type, Request $request) |
65
|
|
|
{ |
66
|
2 |
|
$mimeProcResult = $this->processMime($request->headers->get('Content-Type')); |
67
|
|
|
|
68
|
1 |
|
if (is_null($mimeProcResult->format)) { |
|
|
|
|
69
|
|
|
throw new Exception\UnsupportedMediaType(); |
70
|
|
|
} |
71
|
|
|
|
72
|
1 |
|
return $this->serviceHateoas()->getSerializer()->deserialize( |
73
|
1 |
|
$request->getContent(), |
74
|
|
|
$type, |
75
|
1 |
|
$mimeProcResult->format, |
76
|
1 |
|
DeserializationContext::create()->setVersion($mimeProcResult->apiVersion) |
|
|
|
|
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @return Hateoas |
82
|
|
|
*/ |
83
|
|
|
abstract protected function serviceHateoas(); |
84
|
|
|
} |
85
|
|
|
|