aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Courseware/PublicLinksUpdate.php
blob: 9c43f84cfe74816202c44dc1fd264d6a2602004b (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
77
78
<?php

namespace JsonApi\Routes\Courseware;

use Courseware\PublicLink;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\Errors\UnprocessableEntityException;
use JsonApi\JsonApiController;
use JsonApi\Routes\TimestampTrait;
use JsonApi\Routes\ValidationTrait;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * Update one PublicLink.
 */
class PublicLinksUpdate extends JsonApiController
{
    use TimestampTrait;
    use ValidationTrait;
        /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function __invoke(Request $request, Response $response, $args)
    {
        $resource = PublicLink::find($args['id']);
        if (!$resource) {
            throw new RecordNotFoundException();
        }
        $json = $this->validate($request, $resource);
        if (!Authority::canUpdatePublicLink($user = $this->getUser($request), $resource)) {
            throw new AuthorizationFailedException();
        }
        $resource = $this->updatePublicLink($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 (!self::arrayHas($json, 'data.id')) {
            return 'Document must have an `id`.';
        }

        if (self::arrayHas($json, 'data.attributes.expire-date')) {
            $expire_date = self::arrayGet($json, 'data.attributes.expire-date');
            if (!self::isValidTimestamp($expire_date)) {
                return '`expire-date` is not an ISO 8601 timestamp.';
            }
        }
    }

    private function updatePublicLink(PublicLink $resource, array $json): PublicLink
    {
        $get = function ($key, $default = '') use ($json) {
            return self::arrayGet($json, $key, $default);
        };

        $resource->password = $get('data.attributes.password');

        $expire_date = $get('data.attributes.expire-date');
        $expireDate = self::fromISO8601($expire_date);
        $resource->expire_date =  $expireDate->getTimestamp();

        $resource->store();

        return $resource;
    }

}