aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Courseware/StructuralElementsUpdate.php
blob: 455aacc3c06bc2a4e14aacc910e6b4b7b9126bda (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
<?php

namespace JsonApi\Routes\Courseware;

use Courseware\StructuralElement;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\JsonApiController;
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 ValidationTrait;

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function __invoke(Request $request, Response $response, $args)
    {
        if (!($resource = StructuralElement::find($args['id']))) {
            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 \Courseware\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',
                'purpose',
                'read-approval',
                'release-date',
                'title',
                'withdraw-date',
                'write-approval',
            ];

            foreach ($attributes as $jsonKey) {
                $sormKey = strtr($jsonKey, '-', '_');
                if ($val = self::arrayGet($json, 'data.attributes.' . $jsonKey, '')) {
                    $resource->$sormKey = $val;
                }
            }

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

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

            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;
    }
}