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