aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/ConfigValues/ConfigValuesUpdate.php
blob: 97411404a6b0e271abadcf425b218a6afa4716f0 (plain)
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
<?php

namespace JsonApi\Routes\ConfigValues;

use InvalidArgumentException;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\NotImplementedException;
use JsonApi\Routes\ValidationTrait;
use JsonApi\Schemas\ConfigValue as ConfigValueSchema;
use JsonApi\JsonApiController;

class ConfigValuesUpdate extends JsonApiController
{
    use ValidationTrait;
    use HelperTrait;

    protected $allowedIncludePaths = [];

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function __invoke(Request $request, Response $response, $args)
    {
        [$rangeId, $field] = $this->parseId($args['id']);
        $range = $this->getRange($rangeId);
        if (!Authority::canEditConfigValue($this->getUser($request), $range)) {
            throw new AuthorizationFailedException();
        }
        $resource = $this->findOrFakeConfigValue($range, $field);

        // TODO: zunächst kann diese Route nur Konfigurationseinstellungen vom Typ bool ändern
        if ('boolean' !== $resource->entry['type'] && $resource->entry['field'] !== 'MY_COURSES_OPEN_GROUPS') {
            throw new NotImplementedException();
        }

        $json = $this->validate($request, $resource);
        $resource = $this->updateConfigValue($resource, $json);

        return $this->getContentResponse($resource);
    }

    protected function validateResourceDocument($json, $resource)
    {
        if (!self::arrayHas($json, 'data')) {
            return 'Missing `data` member at document´s top level.';
        }

        if (ConfigValueSchema::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`.';
        }

        if (self::arrayGet($json, 'data.id') !== $this->generateId($resource)) {
            return 'Mismatch between URI parameter and document `id`.';
        }

        if (!self::arrayHas($json, 'data.attributes.value')) {
            return 'The attribute `value` must exist.';
        }
    }

    private function updateConfigValue(\ConfigValue $resource, array $json): \ConfigValue
    {
        if (!($config = $resource->getConfigObject())) {
            throw new InvalidArgumentException('Invalid configuration object.');
        }
        $config->store($resource['field'], self::arrayGet($json, 'data.attributes.value'));

        return $resource;
    }
}