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
95
96
97
|
<?php
namespace JsonApi\Routes\Courseware;
use Courseware\Block;
use Courseware\Container;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\Errors\UnprocessableEntityException;
use JsonApi\JsonApiController;
use JsonApi\Routes\ValidationTrait;
use JsonApi\Schemas\Courseware\Block as BlockSchema;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Studip\Activity\Activity;
use Studip\Activity\CoursewareProvider;
/**
* Update one Block.
*/
class BlocksUpdate extends JsonApiController
{
use EditBlockAwareTrait;
use ValidationTrait;
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function __invoke(Request $request, Response $response, $args)
{
if (!($resource = Block::find($args['id']))) {
throw new RecordNotFoundException();
}
$json = $this->validate($request, $resource);
if (!Authority::canUpdateBlock($user = $this->getUser($request), $resource)) {
throw new AuthorizationFailedException();
}
$resource = $this->updateBlock($user, $resource, $json);
return $this->getContentResponse($resource);
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameters)
*/
protected function validateResourceDocument($json, $data)
{
if (!self::arrayHas($json, 'data')) {
return 'Missing `data` member at document“s top level.';
}
if (BlockSchema::TYPE !== self::arrayGet($json, 'data.type')) {
return 'Wrong `type` member of document“s `data`.';
}
if (!self::arrayHas($json, 'data.id')) {
return 'Document must have an `id`.';
}
}
private function updateBlock(\User $user, Block $resource, array $json): Block
{
return $this->updateLockedResource($user, $resource, function ($user, $resource) use ($json) {
$get = function ($key, $default = '') use ($json) {
return self::arrayGet($json, $key, $default);
};
if ($payload = $get('data.attributes.payload')) {
if (!$resource->type->validatePayload((object) $payload)) {
throw new UnprocessableEntityException('Invalid payload for this `block-type`.');
}
$resource->type->setPayload($payload);
}
if ($category = $get('data.attributes.category')) {
$resource->category = $category;
}
if ($position = $get('data.attributes.position')) {
$resource->position = $position;
}
if (is_bool($get('data.attributes.visible'))) {
$resource->visible = $get('data.attributes.visible');
}
if ($get('data.relationships.container.data.id')) {
$resource->container_id = $get('data.relationships.container.data.id');
}
$resource->editor_id = $user->id;
$resource->store();
return $resource;
});
}
}
|