aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Courseware/ContainersCreate.php
blob: 38d891edb7db85cfcdcbfee23588ac2ef6589c1f (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php

namespace JsonApi\Routes\Courseware;

use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\UnprocessableEntityException;
use JsonApi\JsonApiController;
use JsonApi\Routes\ValidationTrait;
use JsonApi\Schemas\Courseware\Container as ContainerSchema;
use JsonApi\Schemas\Courseware\StructuralElement as StructuralElementSchema;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * Create a container.
 */
class ContainersCreate extends JsonApiController
{
    use ValidationTrait;

    const REL_STRUCTURAL_ELEMENT = 'data.relationships.structural-element';

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function __invoke(Request $request, Response $response, $args)
    {
        $json = $this->validate($request);
        $structElem = $this->getStructElemFromJson($json);
        if (!Authority::canCreateContainer($user = $this->getUser($request), $structElem)) {
            throw new AuthorizationFailedException();
        }
        $container = $this->createContainer($user, $json, $structElem);

        return $this->getCreatedResponse($container);
    }

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameters)
     */
    protected function validateResourceDocument($json, $data)
    {
        if (!self::arrayHas($json, 'data')) {
            return 'Missing `data` member at document“s top level.';
        }
        if (ContainerSchema::TYPE !== self::arrayGet($json, 'data.type')) {
            return 'Wrong `type` member of document“s `data`.';
        }
        if (self::arrayHas($json, 'data.id')) {
            return 'New document must not have an `id`.';
        }

        if (!self::arrayHas($json, 'data.attributes.container-type')) {
            return 'Missing `container-type` attribute.';
        }

        $containerType = self::arrayGet($json, 'data.attributes.container-type');
        if (!$this->validateContainerType($containerType)) {
            return 'Invalid `container-type` attribute.';
        }

        if (!self::arrayHas($json, self::REL_STRUCTURAL_ELEMENT)) {
            return 'Missing `structural-element` relationship.';
        }
        if (!$this->getStructElemFromJson($json)) {
            return 'Invalid `structural-element` relationship.';
        }
    }

    private function validateContainerType(string $containerType)
    {
        return \Courseware\ContainerTypes\ContainerType::isContainerType($containerType);
    }

    private function getStructElemFromJson($json)
    {
        if (!$this->validateResourceObject($json, self::REL_STRUCTURAL_ELEMENT, StructuralElementSchema::TYPE)) {
            return null;
        }
        $structElemId = self::arrayGet($json, self::REL_STRUCTURAL_ELEMENT . '.data.id');

        return \Courseware\StructuralElement::find($structElemId);
    }

    private function createContainer(\User $user, array $json, \Courseware\StructuralElement $structElem)
    {
        $get = function ($key, $default = '') use ($json) {
            return self::arrayGet($json, $key, $default);
        };

        $container = \Courseware\Container::build([
            'structural_element_id' => $structElem->id,
            'owner_id' => $user->id,
            'editor_id' => $user->id,
            'edit_blocker_id' => '',
            'position' => $structElem->countContainers(),
            'container_type' => $get('data.attributes.container-type'),
            'payload' => '',
        ]);

        $payload = $get('data.attributes.payload');
        if ($payload) {
            if (!$container->type->validatePayload((object) $payload)) {
                throw new UnprocessableEntityException('Invalid payload for this `container-type`.');
            }
            $container->type->setPayload($payload);
        }

        $container->store();

        return $container;
    }
}