Completed
Push — 6.7 ( 5086f9...12a1f3 )
by André
59:40 queued 37:43
created

Content::doCreateContent()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 36
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

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