aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Files/FileRefsUpdate.php
blob: 79000cc7445c919defec21820232c80a12c02cb8 (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
<?php

namespace JsonApi\Routes\Files;

use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\JsonApiController;
use JsonApi\Routes\ValidationTrait;
use Neomerx\JsonApi\Exceptions\JsonApiException;
use Neomerx\JsonApi\Schema\Error;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class FileRefsUpdate extends JsonApiController
{
    use RoutesHelperTrait, ValidationTrait;

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameters)
     */
    public function __invoke(Request $request, Response $response, $args)
    {
        if (!$fileRef = \FileRef::find($args['id'])) {
            throw new RecordNotFoundException();
        }

        if (!Authority::canUpdateFileRef($user = $this->getUser($request), $fileRef)) {
            throw new AuthorizationFailedException();
        }

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

        $this->updateFileRef($fileRef, $json, $user);

        $fileRef->restore();

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

    private function updateFileRef(\FileRef $fileRef, array $json, \User $user)
    {
        $getTrimmed = function ($key, $default = '') use ($json) {
            return trim(self::arrayGet($json, $key, $default));
        };

        $name = $getTrimmed('data.attributes.name', $fileRef->name);
        $description = $getTrimmed('data.attributes.description', $fileRef->description);
        $termsId = $getTrimmed(
            'data.relationships.terms-of-use.data.id',
            $fileRef->content_terms_of_use_id
        );

        if ($fileRef->name === $name
            && $fileRef->description === $description
            && $fileRef->content_terms_of_use_id === $termsId
        ) {
            return;
        }

        $result = \FileManager::editFileRef($fileRef, $user, $name, $description, $termsId);

        if (!$result instanceof \FileRef) {
            throw new JsonApiException(array_map(function ($error) {
                return new Error('Bad Request Error', null, null, null, 400, $error);
            }, $result), 400);
        }
    }

    protected function validateResourceDocument($json, $data)
    {
        if ($err = $this->validateFileRefResourceObject($json, $data)) {
            return $err;
        }
    }
}