aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Courseware/StructuralElementsUpdate.php
blob: ae58bcae41db221fada1e82a6075d28cee5abbf4 (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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
<?php

namespace JsonApi\Routes\Courseware;

use Courseware\StructuralElement;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\JsonApiController;
use JsonApi\Routes\TimestampTrait;
use JsonApi\Routes\ValidationTrait;
use JsonApi\Schemas\Courseware\StructuralElement as StructuralElementSchema;
use JsonApi\Schemas\FileRef as FileRefSchema;
use JsonApi\Schemas\StockImage as StockImageSchema;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * Update one Block.
 */
class StructuralElementsUpdate extends JsonApiController
{
    use EditBlockAwareTrait;
    use TimestampTrait;
    use ValidationTrait;

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function __invoke(Request $request, Response $response, $args)
    {
        $resource = StructuralElement::find($args['id']);
        if (!$resource) {
            throw new RecordNotFoundException();
        }
        $json = $this->validate($request, $resource);
        if (!Authority::canUpdateStructuralElement($user = $this->getUser($request), $resource)) {
            throw new AuthorizationFailedException();
        }
        $resource = $this->updateStructuralElement($user, $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 (StructuralElementSchema::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::arrayHas($json, 'data.relationships.parent')) {
            // Sonderfall: Wurzel hat kein parent und kann auch nicht verändert werden
            if ($data->isRootNode()) {
                if (null !== self::arrayGet($json, 'data.relationships.parent.data')) {
                    return 'Cannot modify `parent` of a root node.';
                }

                // Regelfall: Es gibt die Relation, aber `parent` ist ungültig.
            } else {
                $parent = $this->getParentFromJson($json);
                if (!$parent) {
                    return 'Invalid `parent` relationship.';
                }

                // keine Schleifen
                if (
                    in_array(
                        $data->id,
                        array_merge(
                            [$parent->id],
                            array_map(function ($ancestor) {
                                return $ancestor->id;
                            }, $parent->findAncestors())
                        )
                    )
                ) {
                    return 'Invalid `parent` relationship resulting in a cycle.';
                }
            }
        }

        $imageRelationship = 'data.relationships.' . StructuralElementSchema::REL_IMAGE;
        if (self::arrayHas($json, $imageRelationship)) {
            $relation = self::arrayGet($json, $imageRelationship);
            if (isset($relation['data']['type'])) {
                $validTypes = [FileRefSchema::TYPE, StockImageSchema::TYPE];
                if (!in_array($relation['data']['type'], $validTypes)) {
                    return 'Relationship `image` can only be of type ' . join(', ', $validTypes);
                }
            }
        }
    }

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

        return StructuralElement::find($parentId);
    }

    private function updateStructuralElement(\User $user, StructuralElement $resource, array $json): StructuralElement
    {
        return $this->updateLockedResource($user, $resource, function ($user, $resource) use ($json) {
            $attributes = [
                'copy-approval',
                'external-relations',
                'payload',
                'position',
                'public',
                'title',
                'permission-type',
                'visible',
                'writable',
                'visible-approval',
                'writable-approval',
                'content-approval',
            ];

            foreach ($attributes as $jsonKey) {
                $sormKey = strtr($jsonKey, '-', '_');
                if ($val = self::arrayGet($json, 'data.attributes.' . $jsonKey, '')) {
                    $resource->$sormKey = $val;
                }
            }
            if (self::arrayHas($json, 'data.attributes.purpose') && $resource->purpose !== 'task') {
                $resource->purpose = self::arrayGet($json, 'data.attributes.purpose');
            }
            if (self::arrayHas($json, 'data.attributes.visible-all')) {
                $resource->visible_all = self::arrayGet($json, 'data.attributes.visible-all');
            }
            if (self::arrayHas($json, 'data.attributes.writable-all')) {
                $resource->writable_all = self::arrayGet($json, 'data.attributes.writable-all');
            }
            if (self::arrayHas($json, 'data.attributes.visible-start-date')) {
                $visibleStartDate = self::arrayGet($json, 'data.attributes.visible-start-date');
                if ($visibleStartDate) {
                    $visibleStartDate = self::fromISO8601($visibleStartDate);
                    $visibleStartDate = $visibleStartDate->getTimestamp();
                }
                $resource->visible_start_date = $visibleStartDate;
            }
            if (self::arrayHas($json, 'data.attributes.visible-end-date')) {
                $visibleEndDate = self::arrayGet($json, 'data.attributes.visible-end-date');
                if ($visibleEndDate) {
                    $visibleEndDate = self::fromISO8601($visibleEndDate);
                    $visibleEndDate = $visibleEndDate->getTimestamp();
                }
                $resource->visible_end_date = $visibleEndDate;
            }
            if (self::arrayHas($json, 'data.attributes.writable-start-date')) {
                $writableStartDate = self::arrayGet($json, 'data.attributes.writable-start-date');
                if ($writableStartDate) {
                    $writableStartDate = self::fromISO8601($writableStartDate);
                    $writableStartDate = $writableStartDate->getTimestamp();
                }
                $resource->writable_start_date = $writableStartDate;
            }
            if (self::arrayHas($json, 'data.attributes.writable-end-date')) {
                $writableEndDate = self::arrayGet($json, 'data.attributes.writable-end-date');
                if ($writableEndDate) {
                    $writableEndDate = self::fromISO8601($writableEndDate);
                    $writableEndDate = $writableEndDate->getTimestamp();
                }
                $resource->writable_end_date = $writableEndDate;
            }

            if (isset($json['data']['attributes']['commentable'])) {
                $resource->commentable = $json['data']['attributes']['commentable'];
            }

            // update parent
            if (self::arrayHas($json, 'data.relationships.parent')) {
                $parent = $this->getParentFromJson($json);
                $resource->parent_id = $parent->id;
            }

            // update image
            $this->updateImage($resource, $json);

            $resource->editor_id = $user->id;
            $resource->store();

            return $resource;
        });
    }

    private function updateImage(StructuralElement $resource, array $json): void
    {
        if (!$this->imageNeedsUpdate($resource, $json)) {
            return;
        }

        $currentImage = $resource->image;
        list($imageType, $imageId) = $this->getImageRelationshipData($json);

        // remove current image
        if (!$imageType && !$imageId) {
            if (is_a($currentImage, \FileRef::class)) {
                $currentImage->getFileType()->delete();
            }
            $resource->image_id = null;
            $resource->image_type = null;
        } elseif ($imageType === StockImageSchema::TYPE) {
            $stockImageExists = \StockImage::countBySQL('id = ?', [$imageId]);
            if (!$stockImageExists) {
                throw new RecordNotFoundException('Could not find that stock image.');
            }
            $resource->image_id = $imageId;
            $resource->image_type = \StockImage::class;
        } elseif ($imageType === FileRefSchema::TYPE) {
            throw new \RuntimeException('Not yet implemented.');
        }
    }

    private function getImageRelationshipData(array $json): array
    {
        $imageRelationship = 'data.relationships.' . StructuralElementSchema::REL_IMAGE;
        if (!self::arrayHas($json, $imageRelationship)) {
            throw new \RuntimeException('Missing relationship `image`');
        }
        $relation = self::arrayGet($json, $imageRelationship);

        return [self::arrayGet($relation, 'data.type'), self::arrayGet($relation, 'data.id')];
    }

    private function imageNeedsUpdate(StructuralElement $resource, array $json): bool
    {
        $imageRelationship = 'data.relationships.' . StructuralElementSchema::REL_IMAGE;
        if (!self::arrayHas($json, $imageRelationship)) {
            return false;
        }

        $currentImage = $resource->image;
        list($imageType, $imageId) = $this->getImageRelationshipData($json);

        if (!$currentImage) {
            return (bool) $imageId;
        }

        $currentImageSchema = $this->getSchema($currentImage);

        return ($currentImage && !$imageId)
            || $currentImageSchema::TYPE !== $imageType
            || $currentImage->id != $imageId;
    }
}