aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Courseware/UnitsCreate.php
blob: f8fb17b6b5290c0824058c6058387850a3bb632a (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
114
115
116
117
118
119
120
121
122
123
124
<?php

namespace JsonApi\Routes\Courseware;

use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\JsonApiController;
use JsonApi\Routes\ValidationTrait;
use JsonApi\Schemas\Courseware\Unit as UnitSchema;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * Create a block in a container.
 */
class UnitsCreate extends JsonApiController
{
    use ValidationTrait;

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function __invoke(Request $request, Response $response, $args)
    {
        $json = $this->validate($request);
        $user = $this->getUser($request);
        $range = $this->getRange($json);

        if (!$range) {
            throw new RecordNotFoundException();
        }
        if (!Authority::canCreateUnit($user, $range)) {
            throw new AuthorizationFailedException();
        }
        $struct = $this->createUnit($user, $range, $json);

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

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameters)
     */
    protected function validateResourceDocument($json, $data)
    {
        if (!self::arrayHas($json, 'data')) {
            return 'Missing `data` member at document“s top level.';
        }
        if (UnitSchema::TYPE !== self::arrayGet($json, 'data.type')) {
            return 'Wrong `type` member of document“s `data`.';
        }
        if (!self::arrayHas($json, 'data.attributes.title')) {
            return 'Missing `title` value.';
        }
        if (!self::arrayHas($json, 'data.attributes.payload.description')) {
            return 'Missing `description` value.';
        }
        if (!self::arrayHas($json, 'data.relationships.range')) {
            return 'Missing `range` relationship.';
        }
        if (!$this->validateRange($json)) {
            return 'Invalid `range` relationship.';
        }
    }

    private function getRange($json): ?\Range
    {
        $rangeData = self::arrayGet($json, 'data.relationships.range.data');

        try {
            return \RangeFactory::createRange(
                $this->getRangeType($rangeData['type']),
                $rangeData['id']
            );
        } catch (\Exception $e) {
            return null;
        }
    }

    private function validateRange($json): bool
    {
        $range = $this->getRange($json);

        return isset($range);
    }

    private function createUnit(\User $user, \Range $range, array $json)
    {
        $struct = \Courseware\StructuralElement::create([
            'parent_id' => null,
            'range_id' => $range->getRangeId(),
            'range_type' => $range->getRangeType(),
            'owner_id' => $user->id,
            'editor_id' => $user->id,
            'edit_blocker_id' => '',
            'title' => self::arrayGet($json, 'data.attributes.title', ''),
            'purpose' => self::arrayGet($json, 'data.attributes.purpose', ''),
            'payload' => self::arrayGet($json, 'data.attributes.payload', ''),
            'position' => 0
        ]);

        $unit = \Courseware\Unit::create([
            'range_id' => $range->getRangeId(),
            'range_type' => $range->getRangeType(),
            'structural_element_id' => $struct->id,
            'content_type' => 'courseware',
            'creator_id' => $user->id,
            'public' => self::arrayGet($json, 'data.attributes.public', '0'),
            'release_date' => self::arrayGet($json, 'data.attributes.release-date'),
            'withdraw_date' => self::arrayGet($json, 'data.attributes.withdraw-date'),
        ]);

        return $unit;
    }

    private function getRangeType($type): ?string
    {
        $type_map = [
            'courses' => 'course',
            'users'   => 'user',
        ];

        return $type_map[$type] ?? null;
    }
}