1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
<?php
namespace JsonApi\Routes\Feedback;
use FeedbackElement;
use FeedbackRange;
use User;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\JsonApiController;
use JsonApi\Routes\ValidationTrait;
use JsonApi\Schemas\FeedbackElement as FeedbackElementSchema;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
/**
* Update a FeedbackElement.
*
* @SuppressWarnings(PHPMD.StaticAccess)
*/
class FeedbackElementsUpdate extends JsonApiController
{
use RangeTypeAware;
use ValidationTrait;
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
* @param array $args
*
* @return Response
*/
public function __invoke(Request $request, Response $response, $args)
{
$this->preparePossibleRangeTypes();
$resource = \FeedbackElement::find($args['id']);
if (!$resource) {
throw new RecordNotFoundException();
}
$json = $this->validate($request);
$user = $this->getUser($request);
if (!Authority::canUpdateFeedbackElement($user, $resource)) {
throw new AuthorizationFailedException();
}
$feedbackElement = $this->update($resource, $json);
return $this->getContentResponse($feedbackElement);
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameters)
*
* @param array $json
* @param mixed $data
*
* @return string|void
*/
protected function validateResourceDocument($json, $data)
{
if (!self::arrayHas($json, 'data')) {
return 'Missing `data` member at document“s top level.';
}
if (FeedbackElementSchema::TYPE !== self::arrayGet($json, 'data.type')) {
return 'Invalid `type` of document“s `data`.';
}
if (!self::arrayHas($json, 'data.id')) {
return 'An existing document must have an `id`.';
}
$required = ['question', 'description'];
foreach ($required as $attribute) {
if (!self::arrayHas($json, 'data.attributes.' . $attribute)) {
return 'Missing `' . $attribute . '` attribute.';
}
}
}
private function update(FeedbackElement $feedbackElement, array $json): FeedbackElement
{
$strAttrs = ['question', 'description'];
foreach ($strAttrs as $attribute) {
if (self::arrayHas($json, 'data.attributes.' . $attribute)) {
$feedbackElement[$attribute] = self::arrayGet($json, 'data.attributes.' . $attribute);
}
}
$feedbackElement->store();
return $feedbackElement;
}
}
|