Completed
Push — ezp24853-enhance_rest_when_fai... ( cdb248...b5a686 )
by
unknown
55:41 queued 32:16
created

Content::updateVersion()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 55
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 34
c 1
b 0
f 0
nc 4
nop 3
dl 0
loc 55
rs 9.078

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Core\REST\Server\Exceptions\ForbiddenException;
22
use eZ\Publish\Core\REST\Server\Exceptions\BadRequestException;
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
    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) {
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 (ContentFieldValidationException $e) {
247
            throw new BadRequestException($e->getMessage());
248
        }
249
250
        $contentValue = null;
251
        $contentType = null;
252
        $relations = null;
253
        if ($this->getMediaType($request) === 'application/vnd.ez.api.content') {
254
            $contentValue = $content;
255
            $contentType = $this->repository->getContentTypeService()->loadContentType(
256
                $content->getVersionInfo()->getContentInfo()->contentTypeId
257
            );
258
            $relations = $this->repository->getContentService()->loadRelations($contentValue->getVersionInfo());
259
        }
260
261
        return new Values\CreatedContent(
262
            array(
263
                'content' => new Values\RestContent(
264
                    $content->contentInfo,
265
                    null,
266
                    $contentValue,
267
                    $contentType,
268
                    $relations
269
                ),
270
            )
271
        );
272
    }
273
274
    /**
275
     * The content is deleted. If the content has locations (which is required in 4.x)
276
     * on delete all locations assigned the content object are deleted via delete subtree.
277
     *
278
     * @param mixed $contentId
279
     *
280
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
281
     */
282
    public function deleteContent($contentId)
283
    {
284
        $this->repository->getContentService()->deleteContent(
285
            $this->repository->getContentService()->loadContentInfo($contentId)
286
        );
287
288
        return new Values\NoContent();
289
    }
290
291
    /**
292
     * Creates a new content object as copy under the given parent location given in the destination header.
293
     *
294
     * @param mixed $contentId
295
     *
296
     * @return \eZ\Publish\Core\REST\Server\Values\ResourceCreated
297
     */
298
    public function copyContent($contentId, Request $request)
299
    {
300
        $destination = $request->headers->get('Destination');
301
302
        $parentLocationParts = explode('/', $destination);
303
        $copiedContent = $this->repository->getContentService()->copyContent(
304
            $this->repository->getContentService()->loadContentInfo($contentId),
305
            $this->repository->getLocationService()->newLocationCreateStruct(array_pop($parentLocationParts))
306
        );
307
308
        return new Values\ResourceCreated(
309
            $this->router->generate(
310
                'ezpublish_rest_loadContent',
311
                array('contentId' => $copiedContent->id)
312
            )
313
        );
314
    }
315
316
    /**
317
     * Returns a list of all versions of the content. This method does not
318
     * include fields and relations in the Version elements of the response.
319
     *
320
     * @param mixed $contentId
321
     *
322
     * @return \eZ\Publish\Core\REST\Server\Values\VersionList
323
     */
324
    public function loadContentVersions($contentId, Request $request)
325
    {
326
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
327
328
        $versionList = new Values\VersionList(
329
            $this->repository->getContentService()->loadVersions($contentInfo),
330
            $request->getPathInfo()
331
        );
332
333
        if ($contentInfo->mainLocationId === null) {
334
            return $versionList;
335
        }
336
337
        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::loadContentVersions of type eZ\Publish\Core\REST\Server\Values\VersionList.

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...
338
            $versionList,
339
            array('locationId' => $contentInfo->mainLocationId)
340
        );
341
    }
342
343
    /**
344
     * The version is deleted.
345
     *
346
     * @param mixed $contentId
347
     * @param mixed $versionNumber
348
     *
349
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException
350
     *
351
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
352
     */
353 View Code Duplication
    public function deleteContentVersion($contentId, $versionNumber)
354
    {
355
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
356
            $this->repository->getContentService()->loadContentInfo($contentId),
357
            $versionNumber
358
        );
359
360
        if ($versionInfo->status === VersionInfo::STATUS_PUBLISHED) {
361
            throw new ForbiddenException('Version in status PUBLISHED cannot be deleted');
362
        }
363
364
        $this->repository->getContentService()->deleteVersion(
365
            $versionInfo
366
        );
367
368
        return new Values\NoContent();
369
    }
370
371
    /**
372
     * The system creates a new draft version as a copy from the given version.
373
     *
374
     * @param mixed $contentId
375
     * @param mixed $versionNumber
376
     *
377
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedVersion
378
     */
379
    public function createDraftFromVersion($contentId, $versionNumber)
380
    {
381
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
382
        $contentType = $this->repository->getContentTypeService()->loadContentType($contentInfo->contentTypeId);
383
        $contentDraft = $this->repository->getContentService()->createContentDraft(
384
            $contentInfo,
385
            $this->repository->getContentService()->loadVersionInfo($contentInfo, $versionNumber)
386
        );
387
388
        return new Values\CreatedVersion(
389
            array(
390
                'version' => new Values\Version(
391
                    $contentDraft,
392
                    $contentType,
393
                    $this->repository->getContentService()->loadRelations($contentDraft->getVersionInfo())
394
                ),
395
            )
396
        );
397
    }
398
399
    /**
400
     * The system creates a new draft version as a copy from the current version.
401
     *
402
     * @param mixed $contentId
403
     *
404
     * @throws ForbiddenException if the current version is already a draft
405
     *
406
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedVersion
407
     */
408
    public function createDraftFromCurrentVersion($contentId)
409
    {
410
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
411
        $contentType = $this->repository->getContentTypeService()->loadContentType($contentInfo->contentTypeId);
412
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
413
            $contentInfo
414
        );
415
416
        if ($versionInfo->status === VersionInfo::STATUS_DRAFT) {
417
            throw new ForbiddenException('Current version is already in status DRAFT');
418
        }
419
420
        $contentDraft = $this->repository->getContentService()->createContentDraft($contentInfo);
421
422
        return new Values\CreatedVersion(
423
            array(
424
                'version' => new Values\Version(
425
                    $contentDraft,
426
                    $contentType,
427
                    $this->repository->getContentService()->loadRelations($contentDraft->getVersionInfo())
428
                ),
429
            )
430
        );
431
    }
432
433
    /**
434
     * A specific draft is updated.
435
     *
436
     * @param mixed $contentId
437
     * @param mixed $versionNumber
438
     *
439
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException
440
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\BadRequestException
441
     *
442
     * @return \eZ\Publish\Core\REST\Server\Values\Version
443
     */
444
    public function updateVersion($contentId, $versionNumber, Request $request)
445
    {
446
        $contentUpdateStruct = $this->inputDispatcher->parse(
447
            new Message(
448
                array(
449
                    'Content-Type' => $request->headers->get('Content-Type'),
450
                    'Url' => $this->router->generate(
451
                        'ezpublish_rest_updateVersion',
452
                        array(
453
                            'contentId' => $contentId,
454
                            'versionNumber' => $versionNumber,
455
                        )
456
                    ),
457
                ),
458
                $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...
459
            )
460
        );
461
462
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
463
            $this->repository->getContentService()->loadContentInfo($contentId),
464
            $versionNumber
465
        );
466
467
        if ($versionInfo->status !== VersionInfo::STATUS_DRAFT) {
468
            throw new ForbiddenException('Only version in status DRAFT can be updated');
469
        }
470
471
        try {
472
            $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...
473
        } catch (ContentFieldValidationException $e) {
474
            throw new BadRequestException($e->getMessage());
475
        }
476
477
        $languages = null;
478
        if ($request->query->has('languages')) {
479
            $languages = explode(',', $request->query->get('languages'));
480
        }
481
482
        // Reload the content to handle languages GET parameter
483
        $content = $this->repository->getContentService()->loadContent(
484
            $contentId,
485
            $languages,
486
            $versionInfo->versionNo
487
        );
488
        $contentType = $this->repository->getContentTypeService()->loadContentType(
489
            $content->getVersionInfo()->getContentInfo()->contentTypeId
490
        );
491
492
        return new Values\Version(
493
            $content,
494
            $contentType,
495
            $this->repository->getContentService()->loadRelations($content->getVersionInfo()),
496
            $request->getPathInfo()
497
        );
498
    }
499
500
    /**
501
     * The content version is published.
502
     *
503
     * @param mixed $contentId
504
     * @param mixed $versionNumber
505
     *
506
     * @throws ForbiddenException if version $versionNumber isn't a draft
507
     *
508
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
509
     */
510 View Code Duplication
    public function publishVersion($contentId, $versionNumber)
511
    {
512
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
513
            $this->repository->getContentService()->loadContentInfo($contentId),
514
            $versionNumber
515
        );
516
517
        if ($versionInfo->status !== VersionInfo::STATUS_DRAFT) {
518
            throw new ForbiddenException('Only version in status DRAFT can be published');
519
        }
520
521
        $this->repository->getContentService()->publishVersion(
522
            $versionInfo
523
        );
524
525
        return new Values\NoContent();
526
    }
527
528
    /**
529
     * Redirects to the relations of the current version.
530
     *
531
     * @param mixed $contentId
532
     *
533
     * @return \eZ\Publish\Core\REST\Server\Values\TemporaryRedirect
534
     */
535 View Code Duplication
    public function redirectCurrentVersionRelations($contentId)
536
    {
537
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
538
539
        return new Values\TemporaryRedirect(
540
            $this->router->generate(
541
                'ezpublish_rest_redirectCurrentVersionRelations',
542
                array(
543
                    'contentId' => $contentId,
544
                    'versionNumber' => $contentInfo->currentVersionNo,
545
                )
546
            )
547
        );
548
    }
549
550
    /**
551
     * Loads the relations of the given version.
552
     *
553
     * @param mixed $contentId
554
     * @param mixed $versionNumber
555
     *
556
     * @return \eZ\Publish\Core\REST\Server\Values\RelationList
557
     */
558
    public function loadVersionRelations($contentId, $versionNumber, Request $request)
559
    {
560
        $offset = $request->query->has('offset') ? (int)$request->query->get('offset') : 0;
561
        $limit = $request->query->has('limit') ? (int)$request->query->get('limit') : -1;
562
563
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
564
        $relationList = $this->repository->getContentService()->loadRelations(
565
            $this->repository->getContentService()->loadVersionInfo($contentInfo, $versionNumber)
566
        );
567
568
        $relationList = array_slice(
569
            $relationList,
570
            $offset >= 0 ? $offset : 0,
571
            $limit >= 0 ? $limit : null
572
        );
573
574
        $relationListValue = new Values\RelationList(
575
            $relationList,
576
            $contentId,
577
            $versionNumber,
578
            $request->getPathInfo()
579
        );
580
581
        if ($contentInfo->mainLocationId === null) {
582
            return $relationListValue;
583
        }
584
585
        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...
586
            $relationListValue,
587
            array('locationId' => $contentInfo->mainLocationId)
588
        );
589
    }
590
591
    /**
592
     * Loads a relation for the given content object and version.
593
     *
594
     * @param mixed $contentId
595
     * @param int $versionNumber
596
     * @param mixed $relationId
597
     *
598
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
599
     *
600
     * @return \eZ\Publish\Core\REST\Server\Values\RestRelation
601
     */
602
    public function loadVersionRelation($contentId, $versionNumber, $relationId, Request $request)
603
    {
604
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
605
        $relationList = $this->repository->getContentService()->loadRelations(
606
            $this->repository->getContentService()->loadVersionInfo($contentInfo, $versionNumber)
607
        );
608
609
        foreach ($relationList as $relation) {
610
            if ($relation->id == $relationId) {
611
                $relation = new Values\RestRelation($relation, $contentId, $versionNumber);
612
613
                if ($contentInfo->mainLocationId === null) {
614
                    return $relation;
615
                }
616
617
                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...
618
                    $relation,
619
                    array('locationId' => $contentInfo->mainLocationId)
620
                );
621
            }
622
        }
623
624
        throw new Exceptions\NotFoundException("Relation not found: '{$request->getPathInfo()}'.");
625
    }
626
627
    /**
628
     * Deletes a relation of the given draft.
629
     *
630
     * @param mixed $contentId
631
     * @param int   $versionNumber
632
     * @param mixed $relationId
633
     *
634
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException
635
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
636
     *
637
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
638
     */
639
    public function removeRelation($contentId, $versionNumber, $relationId, Request $request)
640
    {
641
        $versionInfo = $this->repository->getContentService()->loadVersionInfo(
642
            $this->repository->getContentService()->loadContentInfo($contentId),
643
            $versionNumber
644
        );
645
646
        $versionRelations = $this->repository->getContentService()->loadRelations($versionInfo);
647
        foreach ($versionRelations as $relation) {
648
            if ($relation->id == $relationId) {
649
                if ($relation->type !== Relation::COMMON) {
650
                    throw new ForbiddenException('Relation is not of type COMMON');
651
                }
652
653
                if ($versionInfo->status !== VersionInfo::STATUS_DRAFT) {
654
                    throw new ForbiddenException('Relation of type COMMON can only be removed from drafts');
655
                }
656
657
                $this->repository->getContentService()->deleteRelation($versionInfo, $relation->getDestinationContentInfo());
658
659
                return new Values\NoContent();
660
            }
661
        }
662
663
        throw new Exceptions\NotFoundException("Relation not found: '{$request->getPathInfo()}'.");
664
    }
665
666
    /**
667
     * Creates a new relation of type COMMON for the given draft.
668
     *
669
     * @param mixed $contentId
670
     * @param int $versionNumber
671
     *
672
     * @throws ForbiddenException if version $versionNumber isn't a draft
673
     * @throws ForbiddenException if a relation to the same content already exists
674
     *
675
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedRelation
676
     */
677
    public function createRelation($contentId, $versionNumber, Request $request)
678
    {
679
        $destinationContentId = $this->inputDispatcher->parse(
680
            new Message(
681
                array('Content-Type' => $request->headers->get('Content-Type')),
682
                $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...
683
            )
684
        );
685
686
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
687
        $versionInfo = $this->repository->getContentService()->loadVersionInfo($contentInfo, $versionNumber);
688
        if ($versionInfo->status !== VersionInfo::STATUS_DRAFT) {
689
            throw new ForbiddenException('Relation of type COMMON can only be added to drafts');
690
        }
691
692
        try {
693
            $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...
694
        } catch (NotFoundException $e) {
695
            throw new ForbiddenException($e->getMessage());
696
        }
697
698
        $existingRelations = $this->repository->getContentService()->loadRelations($versionInfo);
699
        foreach ($existingRelations as $existingRelation) {
700
            if ($existingRelation->getDestinationContentInfo()->id == $destinationContentId) {
701
                throw new ForbiddenException('Relation of type COMMON to selected destination content ID already exists');
702
            }
703
        }
704
705
        $relation = $this->repository->getContentService()->addRelation($versionInfo, $destinationContentInfo);
706
707
        return new Values\CreatedRelation(
708
            array(
709
                'relation' => new Values\RestRelation($relation, $contentId, $versionNumber),
710
            )
711
        );
712
    }
713
714
    /**
715
     * Creates and executes a content view.
716
     *
717
     * @deprecated Since platform 1.0. Forwards the request to the new /views location, but returns a 301.
718
     *
719
     * @return \eZ\Publish\Core\REST\Server\Values\RestExecutedView
720
     */
721
    public function createView()
722
    {
723
        $response = $this->forward('ezpublish_rest.controller.views:createView');
724
725
        // Add 301 status code and location href
726
        $response->setStatusCode(301);
727
        $response->headers->set('Location', $this->router->generate('ezpublish_rest_views_create'));
728
729
        return $response;
730
    }
731
732
    /**
733
     * @param string $controller
734
     *
735
     * @return \Symfony\Component\HttpFoundation\Response
736
     */
737
    protected function forward($controller)
738
    {
739
        $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...
740
        $subRequest = $this->container->get('request_stack')->getCurrentRequest()->duplicate(null, null, $path);
741
742
        return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
743
    }
744
}
745