|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types = 1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Mikemirten\Component\JsonApi\Hydrator\Extension; |
|
5
|
|
|
|
|
6
|
|
|
use Mikemirten\Component\JsonApi\Document\Behaviour\ErrorsAwareInterface; |
|
7
|
|
|
use Mikemirten\Component\JsonApi\Document\ErrorObject; |
|
8
|
|
|
use Mikemirten\Component\JsonApi\Exception\InvalidDocumentException; |
|
9
|
|
|
use Mikemirten\Component\JsonApi\Hydrator\DocumentHydrator; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* "errors" object extension |
|
13
|
|
|
* |
|
14
|
|
|
* @see http://jsonapi.org/format/#errors |
|
15
|
|
|
* |
|
16
|
|
|
* @package Mikemirten\Component\JsonApi\Hydrator\SectionHandler |
|
17
|
|
|
*/ |
|
18
|
|
|
class ErrorsExtension implements ExtensionInterface |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* {@inheritdoc} |
|
22
|
|
|
*/ |
|
23
|
2 |
|
public function hydrate($object, $source, DocumentHydrator $hydrator) |
|
24
|
|
|
{ |
|
25
|
2 |
|
if (! $object instanceof ErrorsAwareInterface) { |
|
26
|
1 |
|
throw new InvalidDocumentException(sprintf( |
|
27
|
1 |
|
'Given instance of "%s" does not implements "%s"', |
|
28
|
|
|
get_class($object), |
|
29
|
1 |
|
ErrorsAwareInterface::class |
|
30
|
|
|
)); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
1 |
|
foreach ($source as $content) |
|
34
|
|
|
{ |
|
35
|
1 |
|
$error = $this->createError($content, $hydrator); |
|
36
|
|
|
|
|
37
|
1 |
|
$object->addError($error); |
|
38
|
|
|
} |
|
39
|
1 |
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Create error |
|
43
|
|
|
* |
|
44
|
|
|
* @param $source |
|
45
|
|
|
* @param DocumentHydrator $hydrator |
|
46
|
|
|
* @return ErrorObject |
|
47
|
|
|
*/ |
|
48
|
1 |
|
protected function createError($source, DocumentHydrator $hydrator): ErrorObject |
|
49
|
|
|
{ |
|
50
|
1 |
|
$error = new ErrorObject(); |
|
51
|
|
|
|
|
52
|
1 |
|
foreach (['id', 'status', 'code', 'title', 'detail'] as $property) |
|
53
|
|
|
{ |
|
54
|
1 |
|
if (isset($source->$property)) { |
|
55
|
1 |
|
$error->{'set' . ucfirst($property)}($source->$property); |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
1 |
|
$hydrator->hydrateObject($error, $source); |
|
60
|
|
|
|
|
61
|
1 |
|
return $error; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* {@inheritdoc} |
|
66
|
|
|
*/ |
|
67
|
1 |
|
public function supports(): array |
|
68
|
|
|
{ |
|
69
|
1 |
|
return ['errors']; |
|
70
|
|
|
} |
|
71
|
|
|
} |