Completed
Push — feature-EZP-25696 ( ab4954...fb76ba )
by André
330:59 queued 300:10
created

Content::loadContentVersions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 2
dl 0
loc 9
rs 9.6666
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
 * @version //autogentag//
10
 */
11
namespace eZ\Publish\Core\REST\Server\Controller;
12
13
use eZ\Publish\Core\REST\Common\Message;
14
use eZ\Publish\Core\REST\Common\Exceptions;
15
use eZ\Publish\Core\REST\Server\Values;
16
use eZ\Publish\Core\REST\Server\Controller as RestController;
17
use eZ\Publish\API\Repository\Values\Content\Relation;
18
use eZ\Publish\API\Repository\Values\Content\VersionInfo;
19
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
20
use eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException;
21
use eZ\Publish\API\Repository\Exceptions\ContentValidationException;
22
use eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException;
23
use eZ\Publish\Core\REST\Server\Exceptions\BadRequestException;
24
use eZ\Publish\Core\REST\Server\Exceptions\ContentFieldValidationException as RESTContentFieldValidationException;
25
use Symfony\Component\HttpFoundation\Request;
26
use Symfony\Component\HttpKernel\HttpKernelInterface;
27
28
/**
29
 * Content controller.
30
 */
31
class Content extends RestController
32
{
33
    /**
34
     * Loads a content info by remote ID.
35
     *
36
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\BadRequestException
37
     *
38
     * @return \eZ\Publish\Core\REST\Server\Values\TemporaryRedirect
39
     */
40 View Code Duplication
    public function redirectContent(Request $request)
41
    {
42
        if (!$request->query->has('remoteId')) {
43
            throw new BadRequestException("'remoteId' parameter is required.");
44
        }
45
46
        $contentInfo = $this->repository->getContentService()->loadContentInfoByRemoteId(
47
            $request->query->get('remoteId')
48
        );
49
50
        return new Values\TemporaryRedirect(
51
            $this->router->generate(
52
                'ezpublish_rest_loadContent',
53
                array(
54
                    'contentId' => $contentInfo->id,
55
                )
56
            )
57
        );
58
    }
59
60
    /**
61
     * Loads a content info, potentially with the current version embedded.
62
     *
63
     * @param mixed $contentId
64
     * @param \Symfony\Component\HttpFoundation\Request $request
65
     *
66
     * @return \eZ\Publish\Core\REST\Server\Values\RestContent
67
     */
68
    public function loadContent($contentId, Request $request)
69
    {
70
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
71
72
        $mainLocation = null;
73
        if (!empty($contentInfo->mainLocationId)) {
74
            $mainLocation = $this->repository->getLocationService()->loadLocation($contentInfo->mainLocationId);
75
        }
76
77
        $contentType = $this->repository->getContentTypeService()->loadContentType($contentInfo->contentTypeId);
78
79
        $contentVersion = null;
80
        $relations = null;
81
        if ($this->getMediaType($request) === 'application/vnd.ez.api.content') {
82
            $languages = null;
83
            if ($request->query->has('languages')) {
84
                $languages = explode(',', $request->query->get('languages'));
85
            }
86
87
            $contentVersion = $this->repository->getContentService()->loadContent($contentId, $languages);
88
            $relations = $this->repository->getContentService()->loadRelations($contentVersion->getVersionInfo());
89
        }
90
91
        $restContent = new Values\RestContent(
92
            $contentInfo,
93
            $mainLocation,
94
            $contentVersion,
95
            $contentType,
96
            $relations,
97
            $request->getPathInfo()
98
        );
99
100
        if ($contentInfo->mainLocationId === null) {
101
            return $restContent;
102
        }
103
104
        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...
105
            $restContent,
106
            array('locationId' => $contentInfo->mainLocationId)
107
        );
108
    }
109
110
    /**
111
     * Updates a content's metadata.
112
     *
113
     * @param mixed $contentId
114
     *
115
     * @return \eZ\Publish\Core\REST\Server\Values\RestContent
116
     */
117
    public function updateContentMetadata($contentId, Request $request)
118
    {
119
        $updateStruct = $this->inputDispatcher->parse(
120
            new Message(
121
                array('Content-Type' => $request->headers->get('Content-Type')),
122
                $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...
123
            )
124
        );
125
126
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
127
128
        // update section
129
        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...
130
            $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...
131
            $this->repository->getSectionService()->assignSection($contentInfo, $section);
132
            $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...
133
        }
134
135
        // @todo Consider refactoring! ContentService::updateContentMetadata throws the same exception
136
        // in case the updateStruct is empty and if remoteId already exists. Since REST version of update struct
137
        // includes section ID in addition to other fields, we cannot throw exception if only sectionId property
138
        // is set, so we must skip updating content in that case instead of allowing propagation of the exception.
139
        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...
140
            if ($propertyName !== 'sectionId' && $propertyValue !== null) {
141
                // update content
142
                $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...
143
                $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
144
                break;
145
            }
146
        }
147
148
        try {
149
            $locationInfo = $this->repository->getLocationService()->loadLocation($contentInfo->mainLocationId);
150
        } catch (NotFoundException $e) {
151
            $locationInfo = null;
152
        }
153
154
        return new Values\RestContent(
155
            $contentInfo,
156
            $locationInfo
157
        );
158
    }
159
160
    /**
161
     * Loads a specific version of a given content object.
162
     *
163
     * @param mixed $contentId
164
     *
165
     * @return \eZ\Publish\Core\REST\Server\Values\TemporaryRedirect
166
     */
167 View Code Duplication
    public function redirectCurrentVersion($contentId)
168
    {
169
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
170
171
        return new Values\TemporaryRedirect(
172
            $this->router->generate(
173
                'ezpublish_rest_loadContentInVersion',
174
                array(
175
                    'contentId' => $contentId,
176
                    'versionNumber' => $contentInfo->currentVersionNo,
177
                )
178
            )
179
        );
180
    }
181
182
    /**
183
     * Loads a specific version of a given content object.
184
     *
185
     * @param mixed $contentId
186
     * @param int $versionNumber
187
     *
188
     * @return \eZ\Publish\Core\REST\Server\Values\Version
189
     */
190
    public function loadContentInVersion($contentId, $versionNumber, Request $request)
191
    {
192
        $languages = null;
193
        if ($request->query->has('languages')) {
194
            $languages = explode(',', $request->query->get('languages'));
195
        }
196
197
        $content = $this->repository->getContentService()->loadContent(
198
            $contentId,
199
            $languages,
200
            $versionNumber
201
        );
202
        $contentType = $this->repository->getContentTypeService()->loadContentType(
203
            $content->getVersionInfo()->getContentInfo()->contentTypeId
204
        );
205
206
        $versionValue = new Values\Version(
207
            $content,
208
            $contentType,
209
            $this->repository->getContentService()->loadRelations($content->getVersionInfo()),
210
            $request->getPathInfo()
211
        );
212
213
        if ($content->contentInfo->mainLocationId === null || $content->versionInfo->status === VersionInfo::STATUS_DRAFT) {
214
            return $versionValue;
215
        }
216
217
        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...
218
            $versionValue,
219
            array('locationId' => $content->contentInfo->mainLocationId)
220
        );
221
    }
222
223
    /**
224
     * Creates a new content draft assigned to the authenticated user.
225
     * If a different userId is given in the input it is assigned to the
226
     * given user but this required special rights for the authenticated
227
     * user (this is useful for content staging where the transfer process
228
     * does not have to authenticate with the user which created the content
229
     * object in the source server). The user has to publish the content if
230
     * it should be visible.
231
     *
232
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedContent
233
     */
234
    public function createContent(Request $request)
235
    {
236
        $contentCreate = $this->inputDispatcher->parse(
237
            new Message(
238
                array('Content-Type' => $request->headers->get('Content-Type')),
239
                $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...
240
            )
241
        );
242
243
        try {
244
            $content = $this->repository->getContentService()->createContent(
245
                $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...
246
                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...
247
            );
248
        } catch (ContentValidationException $e) {
249
            throw new BadRequestException($e->getMessage());
250
        } catch (ContentFieldValidationException $e) {
251
            throw new RESTContentFieldValidationException($e);
252
        }
253
254
        $contentValue = null;
255
        $contentType = null;
256
        $relations = null;
257
        if ($this->getMediaType($request) === 'application/vnd.ez.api.content') {
258
            $contentValue = $content;
259
            $contentType = $this->repository->getContentTypeService()->loadContentType(
260
                $content->getVersionInfo()->getContentInfo()->contentTypeId
261
            );
262
            $relations = $this->repository->getContentService()->loadRelations($contentValue->getVersionInfo());
263
        }
264
265
        return new Values\CreatedContent(
266
            array(
267
                'content' => new Values\RestContent(
268
                    $content->contentInfo,
269
                    null,
270
                    $contentValue,
271
                    $contentType,
272
                    $relations
273
                ),
274
            )
275
        );
276
    }
277
278
    /**
279
     * The content is deleted. If the content has locations (which is required in 4.x)
280
     * on delete all locations assigned the content object are deleted via delete subtree.
281
     *
282
     * @param mixed $contentId
283
     *
284
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
285
     */
286
    public function deleteContent($contentId)
287
    {
288
        $this->repository->getContentService()->deleteContent(
289
            $this->repository->getContentService()->loadContentInfo($contentId)
290
        );
291
292
        return new Values\NoContent();
293
    }
294
295
    /**
296
     * Creates a new content object as copy under the given parent location given in the destination header.
297
     *
298
     * @param mixed $contentId
299
     *
300
     * @return \eZ\Publish\Core\REST\Server\Values\ResourceCreated
301
     */
302
    public function copyContent($contentId, Request $request)
303
    {
304
        $destination = $request->headers->get('Destination');
305
306
        $parentLocationParts = explode('/', $destination);
307
        $copiedContent = $this->repository->getContentService()->copyContent(
308
            $this->repository->getContentService()->loadContentInfo($contentId),
309
            $this->repository->getLocationService()->newLocationCreateStruct(array_pop($parentLocationParts))
310
        );
311
312
        return new Values\ResourceCreated(
313
            $this->router->generate(
314
                'ezpublish_rest_loadContent',
315
                array('contentId' => $copiedContent->id)
316
            )
317
        );
318
    }
319
320
    /**
321
     * Returns a list of all versions of the content. This method does not
322
     * include fields and relations in the Version elements of the response.
323
     *
324
     * @param mixed $contentId
325
     *
326
     * @return \eZ\Publish\Core\REST\Server\Values\VersionList
327
     */
328
    public function loadContentVersions($contentId, Request $request)
329
    {
330
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
331
332
        return new Values\VersionList(
333
            $this->repository->getContentService()->loadVersions($contentInfo),
334
            $request->getPathInfo()
335
        );
336
    }
337
338
    /**
339
     * The version is deleted.
340
     *
341
     * @param mixed $contentId
342
     * @param mixed $versionNumber
343
     *
344
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException
345
     *
346
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
347
     */
348 View Code Duplication
    public function deleteContentVersion($contentId, $versionNumber)
349
    {
350
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
351
            $this->repository->getContentService()->loadContentInfo($contentId),
352
            $versionNumber
353
        );
354
355
        if ($versionInfo->status === VersionInfo::STATUS_PUBLISHED) {
356
            throw new ForbiddenException('Version in status PUBLISHED cannot be deleted');
357
        }
358
359
        $this->repository->getContentService()->deleteVersion(
360
            $versionInfo
361
        );
362
363
        return new Values\NoContent();
364
    }
365
366
    /**
367
     * The system creates a new draft version as a copy from the given version.
368
     *
369
     * @param mixed $contentId
370
     * @param mixed $versionNumber
371
     *
372
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedVersion
373
     */
374
    public function createDraftFromVersion($contentId, $versionNumber)
375
    {
376
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
377
        $contentType = $this->repository->getContentTypeService()->loadContentType($contentInfo->contentTypeId);
378
        $contentDraft = $this->repository->getContentService()->createContentDraft(
379
            $contentInfo,
380
            $this->repository->getContentService()->loadVersionInfo($contentInfo, $versionNumber)
381
        );
382
383
        return new Values\CreatedVersion(
384
            array(
385
                'version' => new Values\Version(
386
                    $contentDraft,
387
                    $contentType,
388
                    $this->repository->getContentService()->loadRelations($contentDraft->getVersionInfo())
389
                ),
390
            )
391
        );
392
    }
393
394
    /**
395
     * The system creates a new draft version as a copy from the current version.
396
     *
397
     * @param mixed $contentId
398
     *
399
     * @throws ForbiddenException if the current version is already a draft
400
     *
401
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedVersion
402
     */
403
    public function createDraftFromCurrentVersion($contentId)
404
    {
405
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
406
        $contentType = $this->repository->getContentTypeService()->loadContentType($contentInfo->contentTypeId);
407
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
408
            $contentInfo
409
        );
410
411
        if ($versionInfo->status === VersionInfo::STATUS_DRAFT) {
412
            throw new ForbiddenException('Current version is already in status DRAFT');
413
        }
414
415
        $contentDraft = $this->repository->getContentService()->createContentDraft($contentInfo);
416
417
        return new Values\CreatedVersion(
418
            array(
419
                'version' => new Values\Version(
420
                    $contentDraft,
421
                    $contentType,
422
                    $this->repository->getContentService()->loadRelations($contentDraft->getVersionInfo())
423
                ),
424
            )
425
        );
426
    }
427
428
    /**
429
     * A specific draft is updated.
430
     *
431
     * @param mixed $contentId
432
     * @param mixed $versionNumber
433
     *
434
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException
435
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\BadRequestException
436
     *
437
     * @return \eZ\Publish\Core\REST\Server\Values\Version
438
     */
439
    public function updateVersion($contentId, $versionNumber, Request $request)
440
    {
441
        $contentUpdateStruct = $this->inputDispatcher->parse(
442
            new Message(
443
                array(
444
                    'Content-Type' => $request->headers->get('Content-Type'),
445
                    'Url' => $this->router->generate(
446
                        'ezpublish_rest_updateVersion',
447
                        array(
448
                            'contentId' => $contentId,
449
                            'versionNumber' => $versionNumber,
450
                        )
451
                    ),
452
                ),
453
                $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...
454
            )
455
        );
456
457
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
458
            $this->repository->getContentService()->loadContentInfo($contentId),
459
            $versionNumber
460
        );
461
462
        if ($versionInfo->status !== VersionInfo::STATUS_DRAFT) {
463
            throw new ForbiddenException('Only version in status DRAFT can be updated');
464
        }
465
466
        try {
467
            $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...
468
        } catch (ContentValidationException $e) {
469
            throw new BadRequestException($e->getMessage());
470
        } catch (ContentFieldValidationException $e) {
471
            throw new RESTContentFieldValidationException($e);
472
        }
473
474
        $languages = null;
475
        if ($request->query->has('languages')) {
476
            $languages = explode(',', $request->query->get('languages'));
477
        }
478
479
        // Reload the content to handle languages GET parameter
480
        $content = $this->repository->getContentService()->loadContent(
481
            $contentId,
482
            $languages,
483
            $versionInfo->versionNo
484
        );
485
        $contentType = $this->repository->getContentTypeService()->loadContentType(
486
            $content->getVersionInfo()->getContentInfo()->contentTypeId
487
        );
488
489
        return new Values\Version(
490
            $content,
491
            $contentType,
492
            $this->repository->getContentService()->loadRelations($content->getVersionInfo()),
493
            $request->getPathInfo()
494
        );
495
    }
496
497
    /**
498
     * The content version is published.
499
     *
500
     * @param mixed $contentId
501
     * @param mixed $versionNumber
502
     *
503
     * @throws ForbiddenException if version $versionNumber isn't a draft
504
     *
505
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
506
     */
507 View Code Duplication
    public function publishVersion($contentId, $versionNumber)
508
    {
509
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
510
            $this->repository->getContentService()->loadContentInfo($contentId),
511
            $versionNumber
512
        );
513
514
        if ($versionInfo->status !== VersionInfo::STATUS_DRAFT) {
515
            throw new ForbiddenException('Only version in status DRAFT can be published');
516
        }
517
518
        $this->repository->getContentService()->publishVersion(
519
            $versionInfo
520
        );
521
522
        return new Values\NoContent();
523
    }
524
525
    /**
526
     * Redirects to the relations of the current version.
527
     *
528
     * @param mixed $contentId
529
     *
530
     * @return \eZ\Publish\Core\REST\Server\Values\TemporaryRedirect
531
     */
532 View Code Duplication
    public function redirectCurrentVersionRelations($contentId)
533
    {
534
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
535
536
        return new Values\TemporaryRedirect(
537
            $this->router->generate(
538
                'ezpublish_rest_redirectCurrentVersionRelations',
539
                array(
540
                    'contentId' => $contentId,
541
                    'versionNumber' => $contentInfo->currentVersionNo,
542
                )
543
            )
544
        );
545
    }
546
547
    /**
548
     * Loads the relations of the given version.
549
     *
550
     * @param mixed $contentId
551
     * @param mixed $versionNumber
552
     *
553
     * @return \eZ\Publish\Core\REST\Server\Values\RelationList
554
     */
555
    public function loadVersionRelations($contentId, $versionNumber, Request $request)
556
    {
557
        $offset = $request->query->has('offset') ? (int)$request->query->get('offset') : 0;
558
        $limit = $request->query->has('limit') ? (int)$request->query->get('limit') : -1;
559
560
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
561
        $relationList = $this->repository->getContentService()->loadRelations(
562
            $this->repository->getContentService()->loadVersionInfo($contentInfo, $versionNumber)
563
        );
564
565
        $relationList = array_slice(
566
            $relationList,
567
            $offset >= 0 ? $offset : 0,
568
            $limit >= 0 ? $limit : null
569
        );
570
571
        $relationListValue = new Values\RelationList(
572
            $relationList,
573
            $contentId,
574
            $versionNumber,
575
            $request->getPathInfo()
576
        );
577
578
        if ($contentInfo->mainLocationId === null) {
579
            return $relationListValue;
580
        }
581
582
        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...
583
            $relationListValue,
584
            array('locationId' => $contentInfo->mainLocationId)
585
        );
586
    }
587
588
    /**
589
     * Loads a relation for the given content object and version.
590
     *
591
     * @param mixed $contentId
592
     * @param int $versionNumber
593
     * @param mixed $relationId
594
     *
595
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
596
     *
597
     * @return \eZ\Publish\Core\REST\Server\Values\RestRelation
598
     */
599
    public function loadVersionRelation($contentId, $versionNumber, $relationId, Request $request)
600
    {
601
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
602
        $relationList = $this->repository->getContentService()->loadRelations(
603
            $this->repository->getContentService()->loadVersionInfo($contentInfo, $versionNumber)
604
        );
605
606
        foreach ($relationList as $relation) {
607
            if ($relation->id == $relationId) {
608
                $relation = new Values\RestRelation($relation, $contentId, $versionNumber);
609
610
                if ($contentInfo->mainLocationId === null) {
611
                    return $relation;
612
                }
613
614
                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...
615
                    $relation,
616
                    array('locationId' => $contentInfo->mainLocationId)
617
                );
618
            }
619
        }
620
621
        throw new Exceptions\NotFoundException("Relation not found: '{$request->getPathInfo()}'.");
622
    }
623
624
    /**
625
     * Deletes a relation of the given draft.
626
     *
627
     * @param mixed $contentId
628
     * @param int   $versionNumber
629
     * @param mixed $relationId
630
     *
631
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException
632
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
633
     *
634
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
635
     */
636
    public function removeRelation($contentId, $versionNumber, $relationId, Request $request)
637
    {
638
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
639
            $this->repository->getContentService()->loadContentInfo($contentId),
640
            $versionNumber
641
        );
642
643
        $versionRelations = $this->repository->getContentService()->loadRelations($versionInfo);
644
        foreach ($versionRelations as $relation) {
645
            if ($relation->id == $relationId) {
646
                if ($relation->type !== Relation::COMMON) {
647
                    throw new ForbiddenException('Relation is not of type COMMON');
648
                }
649
650
                if ($versionInfo->status !== VersionInfo::STATUS_DRAFT) {
651
                    throw new ForbiddenException('Relation of type COMMON can only be removed from drafts');
652
                }
653
654
                $this->repository->getContentService()->deleteRelation($versionInfo, $relation->getDestinationContentInfo());
655
656
                return new Values\NoContent();
657
            }
658
        }
659
660
        throw new Exceptions\NotFoundException("Relation not found: '{$request->getPathInfo()}'.");
661
    }
662
663
    /**
664
     * Creates a new relation of type COMMON for the given draft.
665
     *
666
     * @param mixed $contentId
667
     * @param int $versionNumber
668
     *
669
     * @throws ForbiddenException if version $versionNumber isn't a draft
670
     * @throws ForbiddenException if a relation to the same content already exists
671
     *
672
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedRelation
673
     */
674
    public function createRelation($contentId, $versionNumber, Request $request)
675
    {
676
        $destinationContentId = $this->inputDispatcher->parse(
677
            new Message(
678
                array('Content-Type' => $request->headers->get('Content-Type')),
679
                $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...
680
            )
681
        );
682
683
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
684
        $versionInfo = $this->repository->getContentService()->loadVersionInfo($contentInfo, $versionNumber);
685
        if ($versionInfo->status !== VersionInfo::STATUS_DRAFT) {
686
            throw new ForbiddenException('Relation of type COMMON can only be added to drafts');
687
        }
688
689
        try {
690
            $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...
691
        } catch (NotFoundException $e) {
692
            throw new ForbiddenException($e->getMessage());
693
        }
694
695
        $existingRelations = $this->repository->getContentService()->loadRelations($versionInfo);
696
        foreach ($existingRelations as $existingRelation) {
697
            if ($existingRelation->getDestinationContentInfo()->id == $destinationContentId) {
698
                throw new ForbiddenException('Relation of type COMMON to selected destination content ID already exists');
699
            }
700
        }
701
702
        $relation = $this->repository->getContentService()->addRelation($versionInfo, $destinationContentInfo);
703
704
        return new Values\CreatedRelation(
705
            array(
706
                'relation' => new Values\RestRelation($relation, $contentId, $versionNumber),
707
            )
708
        );
709
    }
710
711
    /**
712
     * Creates and executes a content view.
713
     *
714
     * @deprecated Since platform 1.0. Forwards the request to the new /views location, but returns a 301.
715
     *
716
     * @return \eZ\Publish\Core\REST\Server\Values\RestExecutedView
717
     */
718
    public function createView()
719
    {
720
        $response = $this->forward('ezpublish_rest.controller.views:createView');
721
722
        // Add 301 status code and location href
723
        $response->setStatusCode(301);
724
        $response->headers->set('Location', $this->router->generate('ezpublish_rest_views_create'));
725
726
        return $response;
727
    }
728
729
    /**
730
     * @param string $controller
731
     *
732
     * @return \Symfony\Component\HttpFoundation\Response
733
     */
734
    protected function forward($controller)
735
    {
736
        $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...
737
        $subRequest = $this->container->get('request_stack')->getCurrentRequest()->duplicate(null, null, $path);
738
739
        return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
740
    }
741
}
742