Completed
Push — ezp-27864-rest-delete-transl-f... ( 998c0a...1a5b2c )
by
unknown
25:39
created

Content::deletePublishedVersionTranslation()   A

Complexity

Conditions 3
Paths 6

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 15
nc 6
nop 2
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * File containing the Content controller class.
5
 *
6
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
7
 * @license For full copyright and license information view LICENSE file distributed with this source code.
8
 */
9
namespace eZ\Publish\Core\REST\Server\Controller;
10
11
use eZ\Publish\Core\REST\Common\Message;
12
use eZ\Publish\Core\REST\Common\Exceptions;
13
use eZ\Publish\Core\REST\Server\Values;
14
use eZ\Publish\Core\REST\Server\Controller as RestController;
15
use eZ\Publish\API\Repository\Values\Content\Relation;
16
use eZ\Publish\API\Repository\Values\Content\VersionInfo;
17
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
18
use eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException;
19
use eZ\Publish\API\Repository\Exceptions\ContentValidationException;
20
use eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException;
21
use eZ\Publish\Core\REST\Server\Exceptions\BadRequestException;
22
use eZ\Publish\Core\REST\Server\Exceptions\ContentFieldValidationException as RESTContentFieldValidationException;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpKernel\HttpKernelInterface;
25
26
/**
27
 * Content controller.
28
 */
29
class Content extends RestController
30
{
31
    /**
32
     * Loads a content info by remote ID.
33
     *
34
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\BadRequestException
35
     *
36
     * @return \eZ\Publish\Core\REST\Server\Values\TemporaryRedirect
37
     */
38 View Code Duplication
    public function redirectContent(Request $request)
39
    {
40
        if (!$request->query->has('remoteId')) {
41
            throw new BadRequestException("'remoteId' parameter is required.");
42
        }
43
44
        $contentInfo = $this->repository->getContentService()->loadContentInfoByRemoteId(
45
            $request->query->get('remoteId')
46
        );
47
48
        return new Values\TemporaryRedirect(
49
            $this->router->generate(
50
                'ezpublish_rest_loadContent',
51
                array(
52
                    'contentId' => $contentInfo->id,
53
                )
54
            )
55
        );
56
    }
57
58
    /**
59
     * Loads a content info, potentially with the current version embedded.
60
     *
61
     * @param mixed $contentId
62
     * @param \Symfony\Component\HttpFoundation\Request $request
63
     *
64
     * @return \eZ\Publish\Core\REST\Server\Values\RestContent
65
     */
66
    public function loadContent($contentId, Request $request)
67
    {
68
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
69
70
        $mainLocation = null;
71
        if (!empty($contentInfo->mainLocationId)) {
72
            $mainLocation = $this->repository->getLocationService()->loadLocation($contentInfo->mainLocationId);
73
        }
74
75
        $contentType = $this->repository->getContentTypeService()->loadContentType($contentInfo->contentTypeId);
76
77
        $contentVersion = null;
78
        $relations = null;
79
        if ($this->getMediaType($request) === 'application/vnd.ez.api.content') {
80
            $languages = null;
81
            if ($request->query->has('languages')) {
82
                $languages = explode(',', $request->query->get('languages'));
83
            }
84
85
            $contentVersion = $this->repository->getContentService()->loadContent($contentId, $languages);
86
            $relations = $this->repository->getContentService()->loadRelations($contentVersion->getVersionInfo());
87
        }
88
89
        $restContent = new Values\RestContent(
90
            $contentInfo,
91
            $mainLocation,
92
            $contentVersion,
93
            $contentType,
94
            $relations,
95
            $request->getPathInfo()
96
        );
97
98
        if ($contentInfo->mainLocationId === null) {
99
            return $restContent;
100
        }
101
102
        return new Values\CachedValue(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \eZ\Publish\C...Info->mainLocationId)); (eZ\Publish\Core\REST\Server\Values\CachedValue) is incompatible with the return type documented by eZ\Publish\Core\REST\Ser...er\Content::loadContent of type eZ\Publish\Core\REST\Server\Values\RestContent.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
103
            $restContent,
104
            array('locationId' => $contentInfo->mainLocationId)
105
        );
106
    }
107
108
    /**
109
     * Updates a content's metadata.
110
     *
111
     * @param mixed $contentId
112
     *
113
     * @return \eZ\Publish\Core\REST\Server\Values\RestContent
114
     */
115
    public function updateContentMetadata($contentId, Request $request)
116
    {
117
        $updateStruct = $this->inputDispatcher->parse(
118
            new Message(
119
                array('Content-Type' => $request->headers->get('Content-Type')),
120
                $request->getContent()
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, eZ\Publish\Core\REST\Common\Message::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
121
            )
122
        );
123
124
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
125
126
        // update section
127
        if ($updateStruct->sectionId !== null) {
0 ignored issues
show
Documentation introduced by
The property sectionId does not exist on object<eZ\Publish\API\Re...ory\Values\ValueObject>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
128
            $section = $this->repository->getSectionService()->loadSection($updateStruct->sectionId);
0 ignored issues
show
Documentation introduced by
The property sectionId does not exist on object<eZ\Publish\API\Re...ory\Values\ValueObject>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
129
            $this->repository->getSectionService()->assignSection($contentInfo, $section);
130
            $updateStruct->sectionId = null;
0 ignored issues
show
Documentation introduced by
The property sectionId does not exist on object<eZ\Publish\API\Re...ory\Values\ValueObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
131
        }
132
133
        // @todo Consider refactoring! ContentService::updateContentMetadata throws the same exception
134
        // in case the updateStruct is empty and if remoteId already exists. Since REST version of update struct
135
        // includes section ID in addition to other fields, we cannot throw exception if only sectionId property
136
        // is set, so we must skip updating content in that case instead of allowing propagation of the exception.
137
        foreach ($updateStruct as $propertyName => $propertyValue) {
0 ignored issues
show
Bug introduced by
The expression $updateStruct of type object<eZ\Publish\API\Re...ory\Values\ValueObject> is not traversable.
Loading history...
138
            if ($propertyName !== 'sectionId' && $propertyValue !== null) {
139
                // update content
140
                $this->repository->getContentService()->updateContentMetadata($contentInfo, $updateStruct);
0 ignored issues
show
Compatibility introduced by
$updateStruct of type object<eZ\Publish\API\Re...ory\Values\ValueObject> is not a sub-type of object<eZ\Publish\API\Re...ntMetadataUpdateStruct>. It seems like you assume a child class of the class eZ\Publish\API\Repository\Values\ValueObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
141
                $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
142
                break;
143
            }
144
        }
145
146
        try {
147
            $locationInfo = $this->repository->getLocationService()->loadLocation($contentInfo->mainLocationId);
148
        } catch (NotFoundException $e) {
149
            $locationInfo = null;
150
        }
151
152
        return new Values\RestContent(
153
            $contentInfo,
154
            $locationInfo
155
        );
156
    }
157
158
    /**
159
     * Loads a specific version of a given content object.
160
     *
161
     * @param mixed $contentId
162
     *
163
     * @return \eZ\Publish\Core\REST\Server\Values\TemporaryRedirect
164
     */
165 View Code Duplication
    public function redirectCurrentVersion($contentId)
166
    {
167
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
168
169
        return new Values\TemporaryRedirect(
170
            $this->router->generate(
171
                'ezpublish_rest_loadContentInVersion',
172
                array(
173
                    'contentId' => $contentId,
174
                    'versionNumber' => $contentInfo->currentVersionNo,
175
                )
176
            )
177
        );
178
    }
179
180
    /**
181
     * Loads a specific version of a given content object.
182
     *
183
     * @param mixed $contentId
184
     * @param int $versionNumber
185
     *
186
     * @return \eZ\Publish\Core\REST\Server\Values\Version
187
     */
188
    public function loadContentInVersion($contentId, $versionNumber, Request $request)
189
    {
190
        $languages = null;
191
        if ($request->query->has('languages')) {
192
            $languages = explode(',', $request->query->get('languages'));
193
        }
194
195
        $content = $this->repository->getContentService()->loadContent(
196
            $contentId,
197
            $languages,
198
            $versionNumber
199
        );
200
        $contentType = $this->repository->getContentTypeService()->loadContentType(
201
            $content->getVersionInfo()->getContentInfo()->contentTypeId
202
        );
203
204
        $versionValue = new Values\Version(
205
            $content,
206
            $contentType,
207
            $this->repository->getContentService()->loadRelations($content->getVersionInfo()),
208
            $request->getPathInfo()
209
        );
210
211
        if ($content->contentInfo->mainLocationId === null || $content->versionInfo->status === VersionInfo::STATUS_DRAFT) {
212
            return $versionValue;
213
        }
214
215
        return new Values\CachedValue(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \eZ\Publish\C...Info->mainLocationId)); (eZ\Publish\Core\REST\Server\Values\CachedValue) is incompatible with the return type documented by eZ\Publish\Core\REST\Ser...t::loadContentInVersion of type eZ\Publish\Core\REST\Server\Values\Version.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
216
            $versionValue,
217
            array('locationId' => $content->contentInfo->mainLocationId)
218
        );
219
    }
220
221
    /**
222
     * Creates a new content draft assigned to the authenticated user.
223
     * If a different userId is given in the input it is assigned to the
224
     * given user but this required special rights for the authenticated
225
     * user (this is useful for content staging where the transfer process
226
     * does not have to authenticate with the user which created the content
227
     * object in the source server). The user has to publish the content if
228
     * it should be visible.
229
     *
230
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedContent
231
     */
232
    public function createContent(Request $request)
233
    {
234
        $contentCreate = $this->inputDispatcher->parse(
235
            new Message(
236
                array('Content-Type' => $request->headers->get('Content-Type')),
237
                $request->getContent()
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, eZ\Publish\Core\REST\Common\Message::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
238
            )
239
        );
240
241
        try {
242
            $content = $this->repository->getContentService()->createContent(
243
                $contentCreate->contentCreateStruct,
0 ignored issues
show
Documentation introduced by
The property contentCreateStruct does not exist on object<eZ\Publish\API\Re...ory\Values\ValueObject>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
244
                array($contentCreate->locationCreateStruct)
0 ignored issues
show
Documentation introduced by
The property locationCreateStruct does not exist on object<eZ\Publish\API\Re...ory\Values\ValueObject>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
245
            );
246
        } catch (ContentValidationException $e) {
247
            throw new BadRequestException($e->getMessage());
248
        } catch (ContentFieldValidationException $e) {
249
            throw new RESTContentFieldValidationException($e);
250
        }
251
252
        $contentValue = null;
253
        $contentType = null;
254
        $relations = null;
255
        if ($this->getMediaType($request) === 'application/vnd.ez.api.content') {
256
            $contentValue = $content;
257
            $contentType = $this->repository->getContentTypeService()->loadContentType(
258
                $content->getVersionInfo()->getContentInfo()->contentTypeId
259
            );
260
            $relations = $this->repository->getContentService()->loadRelations($contentValue->getVersionInfo());
261
        }
262
263
        return new Values\CreatedContent(
264
            array(
265
                'content' => new Values\RestContent(
266
                    $content->contentInfo,
267
                    null,
268
                    $contentValue,
269
                    $contentType,
270
                    $relations
271
                ),
272
            )
273
        );
274
    }
275
276
    /**
277
     * The content is deleted. If the content has locations (which is required in 4.x)
278
     * on delete all locations assigned the content object are deleted via delete subtree.
279
     *
280
     * @param mixed $contentId
281
     *
282
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
283
     */
284
    public function deleteContent($contentId)
285
    {
286
        $this->repository->getContentService()->deleteContent(
287
            $this->repository->getContentService()->loadContentInfo($contentId)
288
        );
289
290
        return new Values\NoContent();
291
    }
292
293
    /**
294
     * Creates a new content object as copy under the given parent location given in the destination header.
295
     *
296
     * @param mixed $contentId
297
     *
298
     * @return \eZ\Publish\Core\REST\Server\Values\ResourceCreated
299
     */
300
    public function copyContent($contentId, Request $request)
301
    {
302
        $destination = $request->headers->get('Destination');
303
304
        $parentLocationParts = explode('/', $destination);
305
        $copiedContent = $this->repository->getContentService()->copyContent(
306
            $this->repository->getContentService()->loadContentInfo($contentId),
307
            $this->repository->getLocationService()->newLocationCreateStruct(array_pop($parentLocationParts))
308
        );
309
310
        return new Values\ResourceCreated(
311
            $this->router->generate(
312
                'ezpublish_rest_loadContent',
313
                array('contentId' => $copiedContent->id)
314
            )
315
        );
316
    }
317
318
    /**
319
     * Returns a list of all versions of the content. This method does not
320
     * include fields and relations in the Version elements of the response.
321
     *
322
     * @param mixed $contentId
323
     *
324
     * @return \eZ\Publish\Core\REST\Server\Values\VersionList
325
     */
326
    public function loadContentVersions($contentId, Request $request)
327
    {
328
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
329
330
        return new Values\VersionList(
331
            $this->repository->getContentService()->loadVersions($contentInfo),
332
            $request->getPathInfo()
333
        );
334
    }
335
336
    /**
337
     * The version is deleted.
338
     *
339
     * @param mixed $contentId
340
     * @param mixed $versionNumber
341
     *
342
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException
343
     *
344
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
345
     */
346 View Code Duplication
    public function deleteContentVersion($contentId, $versionNumber)
347
    {
348
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
349
            $this->repository->getContentService()->loadContentInfo($contentId),
350
            $versionNumber
351
        );
352
353
        if ($versionInfo->isPublished()) {
354
            throw new ForbiddenException('Version in status PUBLISHED cannot be deleted');
355
        }
356
357
        $this->repository->getContentService()->deleteVersion(
358
            $versionInfo
359
        );
360
361
        return new Values\NoContent();
362
    }
363
364
    /**
365
     * Remove the given Translation of the given published Version and publish new one.
366
     *
367
     * @param int $contentId
368
     * @param string $languageCode
369
     *
370
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
371
     *
372
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException
373
     * @throws \Exception
374
     */
375
    public function deletePublishedVersionTranslation($contentId, $languageCode)
376
    {
377
        $contentService = $this->repository->getContentService();
378
        $versionInfo = $this->repository->getContentService()->loadVersionInfoById($contentId);
379
380
        if (!$versionInfo->isPublished()) {
381
            throw new ForbiddenException('Translation can be deleted from PUBLISHED Version only');
382
        }
383
384
        $this->repository->beginTransaction();
385
        try {
386
            $draft = $contentService->createContentDraft($versionInfo->contentInfo);
387
            $draft = $contentService->deleteTranslation($draft->versionInfo, $languageCode);
388
            $contentService->publishVersion($draft->versionInfo);
389
390
            $this->repository->commit();
391
        } catch (\Exception $e) {
392
            $this->repository->rollback();
393
            throw $e;
394
        }
395
396
        return new Values\NoContent();
397
    }
398
399
    /**
400
     * The system creates a new draft version as a copy from the given version.
401
     *
402
     * @param mixed $contentId
403
     * @param mixed $versionNumber
404
     *
405
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedVersion
406
     */
407 View Code Duplication
    public function createDraftFromVersion($contentId, $versionNumber)
408
    {
409
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
410
        $contentType = $this->repository->getContentTypeService()->loadContentType($contentInfo->contentTypeId);
411
        $contentDraft = $this->repository->getContentService()->createContentDraft(
412
            $contentInfo,
413
            $this->repository->getContentService()->loadVersionInfo($contentInfo, $versionNumber)
414
        );
415
416
        return new Values\CreatedVersion(
417
            array(
418
                'version' => new Values\Version(
419
                    $contentDraft,
420
                    $contentType,
421
                    $this->repository->getContentService()->loadRelations($contentDraft->getVersionInfo())
422
                ),
423
            )
424
        );
425
    }
426
427
    /**
428
     * The system creates a new draft version as a copy from the current version.
429
     *
430
     * @param mixed $contentId
431
     *
432
     * @throws ForbiddenException if the current version is already a draft
433
     *
434
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedVersion
435
     */
436 View Code Duplication
    public function createDraftFromCurrentVersion($contentId)
437
    {
438
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
439
        $contentType = $this->repository->getContentTypeService()->loadContentType($contentInfo->contentTypeId);
440
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
441
            $contentInfo
442
        );
443
444
        if ($versionInfo->isDraft()) {
445
            throw new ForbiddenException('Current version is already in status DRAFT');
446
        }
447
448
        $contentDraft = $this->repository->getContentService()->createContentDraft($contentInfo);
449
450
        return new Values\CreatedVersion(
451
            array(
452
                'version' => new Values\Version(
453
                    $contentDraft,
454
                    $contentType,
455
                    $this->repository->getContentService()->loadRelations($contentDraft->getVersionInfo())
456
                ),
457
            )
458
        );
459
    }
460
461
    /**
462
     * A specific draft is updated.
463
     *
464
     * @param mixed $contentId
465
     * @param mixed $versionNumber
466
     *
467
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException
468
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\BadRequestException
469
     *
470
     * @return \eZ\Publish\Core\REST\Server\Values\Version
471
     */
472
    public function updateVersion($contentId, $versionNumber, Request $request)
473
    {
474
        $contentUpdateStruct = $this->inputDispatcher->parse(
475
            new Message(
476
                array(
477
                    'Content-Type' => $request->headers->get('Content-Type'),
478
                    'Url' => $this->router->generate(
479
                        'ezpublish_rest_updateVersion',
480
                        array(
481
                            'contentId' => $contentId,
482
                            'versionNumber' => $versionNumber,
483
                        )
484
                    ),
485
                ),
486
                $request->getContent()
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, eZ\Publish\Core\REST\Common\Message::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
487
            )
488
        );
489
490
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
491
            $this->repository->getContentService()->loadContentInfo($contentId),
492
            $versionNumber
493
        );
494
495
        if (!$versionInfo->isDraft()) {
496
            throw new ForbiddenException('Only version in status DRAFT can be updated');
497
        }
498
499
        try {
500
            $this->repository->getContentService()->updateContent($versionInfo, $contentUpdateStruct);
0 ignored issues
show
Compatibility introduced by
$contentUpdateStruct of type object<eZ\Publish\API\Re...ory\Values\ValueObject> is not a sub-type of object<eZ\Publish\API\Re...nt\ContentUpdateStruct>. It seems like you assume a child class of the class eZ\Publish\API\Repository\Values\ValueObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
501
        } catch (ContentValidationException $e) {
502
            throw new BadRequestException($e->getMessage());
503
        } catch (ContentFieldValidationException $e) {
504
            throw new RESTContentFieldValidationException($e);
505
        }
506
507
        $languages = null;
508
        if ($request->query->has('languages')) {
509
            $languages = explode(',', $request->query->get('languages'));
510
        }
511
512
        // Reload the content to handle languages GET parameter
513
        $content = $this->repository->getContentService()->loadContent(
514
            $contentId,
515
            $languages,
516
            $versionInfo->versionNo
517
        );
518
        $contentType = $this->repository->getContentTypeService()->loadContentType(
519
            $content->getVersionInfo()->getContentInfo()->contentTypeId
520
        );
521
522
        return new Values\Version(
523
            $content,
524
            $contentType,
525
            $this->repository->getContentService()->loadRelations($content->getVersionInfo()),
526
            $request->getPathInfo()
527
        );
528
    }
529
530
    /**
531
     * The content version is published.
532
     *
533
     * @param mixed $contentId
534
     * @param mixed $versionNumber
535
     *
536
     * @throws ForbiddenException if version $versionNumber isn't a draft
537
     *
538
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
539
     */
540 View Code Duplication
    public function publishVersion($contentId, $versionNumber)
541
    {
542
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
543
            $this->repository->getContentService()->loadContentInfo($contentId),
544
            $versionNumber
545
        );
546
547
        if (!$versionInfo->isDraft()) {
548
            throw new ForbiddenException('Only version in status DRAFT can be published');
549
        }
550
551
        $this->repository->getContentService()->publishVersion(
552
            $versionInfo
553
        );
554
555
        return new Values\NoContent();
556
    }
557
558
    /**
559
     * Redirects to the relations of the current version.
560
     *
561
     * @param mixed $contentId
562
     *
563
     * @return \eZ\Publish\Core\REST\Server\Values\TemporaryRedirect
564
     */
565 View Code Duplication
    public function redirectCurrentVersionRelations($contentId)
566
    {
567
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
568
569
        return new Values\TemporaryRedirect(
570
            $this->router->generate(
571
                'ezpublish_rest_redirectCurrentVersionRelations',
572
                array(
573
                    'contentId' => $contentId,
574
                    'versionNumber' => $contentInfo->currentVersionNo,
575
                )
576
            )
577
        );
578
    }
579
580
    /**
581
     * Loads the relations of the given version.
582
     *
583
     * @param mixed $contentId
584
     * @param mixed $versionNumber
585
     *
586
     * @return \eZ\Publish\Core\REST\Server\Values\RelationList
587
     */
588
    public function loadVersionRelations($contentId, $versionNumber, Request $request)
589
    {
590
        $offset = $request->query->has('offset') ? (int)$request->query->get('offset') : 0;
591
        $limit = $request->query->has('limit') ? (int)$request->query->get('limit') : -1;
592
593
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
594
        $relationList = $this->repository->getContentService()->loadRelations(
595
            $this->repository->getContentService()->loadVersionInfo($contentInfo, $versionNumber)
596
        );
597
598
        $relationList = array_slice(
599
            $relationList,
600
            $offset >= 0 ? $offset : 0,
601
            $limit >= 0 ? $limit : null
602
        );
603
604
        $relationListValue = new Values\RelationList(
605
            $relationList,
606
            $contentId,
607
            $versionNumber,
608
            $request->getPathInfo()
609
        );
610
611
        if ($contentInfo->mainLocationId === null) {
612
            return $relationListValue;
613
        }
614
615
        return new Values\CachedValue(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \eZ\Publish\C...Info->mainLocationId)); (eZ\Publish\Core\REST\Server\Values\CachedValue) is incompatible with the return type documented by eZ\Publish\Core\REST\Ser...t::loadVersionRelations of type eZ\Publish\Core\REST\Server\Values\RelationList.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
616
            $relationListValue,
617
            array('locationId' => $contentInfo->mainLocationId)
618
        );
619
    }
620
621
    /**
622
     * Loads a relation for the given content object and version.
623
     *
624
     * @param mixed $contentId
625
     * @param int $versionNumber
626
     * @param mixed $relationId
627
     *
628
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
629
     *
630
     * @return \eZ\Publish\Core\REST\Server\Values\RestRelation
631
     */
632
    public function loadVersionRelation($contentId, $versionNumber, $relationId, Request $request)
633
    {
634
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
635
        $relationList = $this->repository->getContentService()->loadRelations(
636
            $this->repository->getContentService()->loadVersionInfo($contentInfo, $versionNumber)
637
        );
638
639
        foreach ($relationList as $relation) {
640
            if ($relation->id == $relationId) {
641
                $relation = new Values\RestRelation($relation, $contentId, $versionNumber);
642
643
                if ($contentInfo->mainLocationId === null) {
644
                    return $relation;
645
                }
646
647
                return new Values\CachedValue(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \eZ\Publish\C...Info->mainLocationId)); (eZ\Publish\Core\REST\Server\Values\CachedValue) is incompatible with the return type documented by eZ\Publish\Core\REST\Ser...nt::loadVersionRelation of type eZ\Publish\Core\REST\Server\Values\RestRelation.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
648
                    $relation,
649
                    array('locationId' => $contentInfo->mainLocationId)
650
                );
651
            }
652
        }
653
654
        throw new Exceptions\NotFoundException("Relation not found: '{$request->getPathInfo()}'.");
655
    }
656
657
    /**
658
     * Deletes a relation of the given draft.
659
     *
660
     * @param mixed $contentId
661
     * @param int   $versionNumber
662
     * @param mixed $relationId
663
     *
664
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException
665
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
666
     *
667
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
668
     */
669
    public function removeRelation($contentId, $versionNumber, $relationId, Request $request)
670
    {
671
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
672
            $this->repository->getContentService()->loadContentInfo($contentId),
673
            $versionNumber
674
        );
675
676
        $versionRelations = $this->repository->getContentService()->loadRelations($versionInfo);
677
        foreach ($versionRelations as $relation) {
678
            if ($relation->id == $relationId) {
679
                if ($relation->type !== Relation::COMMON) {
680
                    throw new ForbiddenException('Relation is not of type COMMON');
681
                }
682
683
                if (!$versionInfo->isDraft()) {
684
                    throw new ForbiddenException('Relation of type COMMON can only be removed from drafts');
685
                }
686
687
                $this->repository->getContentService()->deleteRelation($versionInfo, $relation->getDestinationContentInfo());
688
689
                return new Values\NoContent();
690
            }
691
        }
692
693
        throw new Exceptions\NotFoundException("Relation not found: '{$request->getPathInfo()}'.");
694
    }
695
696
    /**
697
     * Creates a new relation of type COMMON for the given draft.
698
     *
699
     * @param mixed $contentId
700
     * @param int $versionNumber
701
     *
702
     * @throws ForbiddenException if version $versionNumber isn't a draft
703
     * @throws ForbiddenException if a relation to the same content already exists
704
     *
705
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedRelation
706
     */
707
    public function createRelation($contentId, $versionNumber, Request $request)
708
    {
709
        $destinationContentId = $this->inputDispatcher->parse(
710
            new Message(
711
                array('Content-Type' => $request->headers->get('Content-Type')),
712
                $request->getContent()
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, eZ\Publish\Core\REST\Common\Message::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
713
            )
714
        );
715
716
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
717
        $versionInfo = $this->repository->getContentService()->loadVersionInfo($contentInfo, $versionNumber);
718
        if (!$versionInfo->isDraft()) {
719
            throw new ForbiddenException('Relation of type COMMON can only be added to drafts');
720
        }
721
722
        try {
723
            $destinationContentInfo = $this->repository->getContentService()->loadContentInfo($destinationContentId);
0 ignored issues
show
Documentation introduced by
$destinationContentId is of type object<eZ\Publish\API\Re...ory\Values\ValueObject>, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
724
        } catch (NotFoundException $e) {
725
            throw new ForbiddenException($e->getMessage());
726
        }
727
728
        $existingRelations = $this->repository->getContentService()->loadRelations($versionInfo);
729
        foreach ($existingRelations as $existingRelation) {
730
            if ($existingRelation->getDestinationContentInfo()->id == $destinationContentId) {
731
                throw new ForbiddenException('Relation of type COMMON to selected destination content ID already exists');
732
            }
733
        }
734
735
        $relation = $this->repository->getContentService()->addRelation($versionInfo, $destinationContentInfo);
736
737
        return new Values\CreatedRelation(
738
            array(
739
                'relation' => new Values\RestRelation($relation, $contentId, $versionNumber),
740
            )
741
        );
742
    }
743
744
    /**
745
     * Creates and executes a content view.
746
     *
747
     * @deprecated Since platform 1.0. Forwards the request to the new /views location, but returns a 301.
748
     *
749
     * @return \eZ\Publish\Core\REST\Server\Values\RestExecutedView
750
     */
751
    public function createView()
752
    {
753
        $response = $this->forward('ezpublish_rest.controller.views:createView');
754
755
        // Add 301 status code and location href
756
        $response->setStatusCode(301);
757
        $response->headers->set('Location', $this->router->generate('ezpublish_rest_views_create'));
758
759
        return $response;
760
    }
761
762
    /**
763
     * @param string $controller
764
     *
765
     * @return \Symfony\Component\HttpFoundation\Response
766
     */
767
    protected function forward($controller)
768
    {
769
        $path['_controller'] = $controller;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$path was never initialized. Although not strictly required by PHP, it is generally a good practice to add $path = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
770
        $subRequest = $this->container->get('request_stack')->getCurrentRequest()->duplicate(null, null, $path);
771
772
        return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
773
    }
774
}
775