Completed
Push — ezp28890-fix_in_context_transl... ( c620fe...b89572 )
by
unknown
22:17
created

Handler   F

Complexity

Total Complexity 48

Size/Duplication

Total Lines 767
Duplicated Lines 7.17 %

Coupling/Cohesion

Components 1
Dependencies 18

Importance

Changes 0
Metric Value
dl 55
loc 767
rs 3.862
c 0
b 0
f 0
wmc 48
lcom 1
cbo 18

27 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 4 1
B internalCreate() 8 39 3
B publish() 0 26 2
B createDraftFromVersion() 0 46 3
A load() 0 18 2
A loadContentInfo() 0 4 1
A loadContentInfoList() 0 13 2
A loadContentInfoByRemoteId() 0 6 1
A loadVersionInfo() 0 14 2
A loadDraftsForUser() 20 20 2
A setStatus() 0 4 1
A updateMetadata() 0 7 1
B updatePathIdentificationString() 0 26 4
A updateContent() 0 17 2
A deleteContent() 0 11 3
A removeRawContent() 0 4 1
A deleteVersion() 0 12 1
A listVersions() 0 4 1
B copy() 8 53 6
A addRelation() 0 8 1
A removeRelation() 0 4 1
A loadRelations() 0 6 1
A loadReverseRelations() 0 6 1
A removeTranslationFromContent() 0 8 1
A deleteTranslationFromContent() 0 9 1
B deleteTranslationFromDraft() 0 35 2
A __construct() 19 19 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Handler often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Handler, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * File containing the Content Handler 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\Persistence\Legacy\Content;
10
11
use eZ\Publish\Core\Persistence\Legacy\Content\Location\Gateway as LocationGateway;
12
use eZ\Publish\SPI\Persistence\Content\Handler as BaseContentHandler;
13
use eZ\Publish\SPI\Persistence\Content\Type\Handler as ContentTypeHandler;
14
use eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\SlugConverter;
15
use eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\Gateway as UrlAliasGateway;
16
use eZ\Publish\SPI\Persistence\Content;
17
use eZ\Publish\SPI\Persistence\Content\CreateStruct;
18
use eZ\Publish\SPI\Persistence\Content\UpdateStruct;
19
use eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct;
20
use eZ\Publish\SPI\Persistence\Content\VersionInfo;
21
use eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct as RelationCreateStruct;
22
use eZ\Publish\Core\Base\Exceptions\NotFoundException as NotFound;
23
24
/**
25
 * The Content Handler stores Content and ContentType objects.
26
 */
27
class Handler implements BaseContentHandler
28
{
29
    /**
30
     * Content gateway.
31
     *
32
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\Gateway
33
     */
34
    protected $contentGateway;
35
36
    /**
37
     * Location gateway.
38
     *
39
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\Location\Gateway
40
     */
41
    protected $locationGateway;
42
43
    /**
44
     * Mapper.
45
     *
46
     * @var Mapper
47
     */
48
    protected $mapper;
49
50
    /**
51
     * FieldHandler.
52
     *
53
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\FieldHandler
54
     */
55
    protected $fieldHandler;
56
57
    /**
58
     * URL slug converter.
59
     *
60
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\SlugConverter
61
     */
62
    protected $slugConverter;
63
64
    /**
65
     * UrlAlias gateway.
66
     *
67
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\Gateway
68
     */
69
    protected $urlAliasGateway;
70
71
    /**
72
     * ContentType handler.
73
     *
74
     * @var \eZ\Publish\SPI\Persistence\Content\Type\Handler
75
     */
76
    protected $contentTypeHandler;
77
78
    /**
79
     * Tree handler.
80
     *
81
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\TreeHandler
82
     */
83
    protected $treeHandler;
84
85
    /**
86
     * Creates a new content handler.
87
     *
88
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\Gateway $contentGateway
89
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\Location\Gateway $locationGateway
90
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\Mapper $mapper
91
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\FieldHandler $fieldHandler
92
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\SlugConverter $slugConverter
93
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\Gateway $urlAliasGateway
94
     * @param \eZ\Publish\SPI\Persistence\Content\Type\Handler $contentTypeHandler
95
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\TreeHandler $treeHandler
96
     */
97 View Code Duplication
    public function __construct(
98
        Gateway $contentGateway,
99
        LocationGateway $locationGateway,
100
        Mapper $mapper,
101
        FieldHandler $fieldHandler,
102
        SlugConverter $slugConverter,
103
        UrlAliasGateway $urlAliasGateway,
104
        ContentTypeHandler $contentTypeHandler,
105
        TreeHandler $treeHandler
106
    ) {
107
        $this->contentGateway = $contentGateway;
108
        $this->locationGateway = $locationGateway;
109
        $this->mapper = $mapper;
110
        $this->fieldHandler = $fieldHandler;
111
        $this->slugConverter = $slugConverter;
112
        $this->urlAliasGateway = $urlAliasGateway;
113
        $this->contentTypeHandler = $contentTypeHandler;
114
        $this->treeHandler = $treeHandler;
115
    }
116
117
    /**
118
     * Creates a new Content entity in the storage engine.
119
     *
120
     * The values contained inside the $content will form the basis of stored
121
     * entity.
122
     *
123
     * Will contain always a complete list of fields.
124
     *
125
     * @param \eZ\Publish\SPI\Persistence\Content\CreateStruct $struct Content creation struct.
126
     *
127
     * @return \eZ\Publish\SPI\Persistence\Content Content value object
128
     */
129
    public function create(CreateStruct $struct)
130
    {
131
        return $this->internalCreate($struct);
132
    }
133
134
    /**
135
     * Creates a new Content entity in the storage engine.
136
     *
137
     * The values contained inside the $content will form the basis of stored
138
     * entity.
139
     *
140
     * Will contain always a complete list of fields.
141
     *
142
     * @param \eZ\Publish\SPI\Persistence\Content\CreateStruct $struct Content creation struct.
143
     * @param mixed $versionNo Used by self::copy() to maintain version numbers
144
     *
145
     * @return \eZ\Publish\SPI\Persistence\Content Content value object
146
     */
147
    protected function internalCreate(CreateStruct $struct, $versionNo = 1)
148
    {
149
        $content = new Content();
150
151
        $content->fields = $struct->fields;
152
        $content->versionInfo = $this->mapper->createVersionInfoFromCreateStruct($struct, $versionNo);
153
154
        $content->versionInfo->contentInfo->id = $this->contentGateway->insertContentObject($struct, $versionNo);
155
        $content->versionInfo->id = $this->contentGateway->insertVersion(
156
            $content->versionInfo,
157
            $struct->fields
158
        );
159
160
        $contentType = $this->contentTypeHandler->load($struct->typeId);
161
        $this->fieldHandler->createNewFields($content, $contentType);
162
163
        // Create node assignments
164
        foreach ($struct->locations as $location) {
165
            $location->contentId = $content->versionInfo->contentInfo->id;
166
            $location->contentVersion = $content->versionInfo->versionNo;
167
            $this->locationGateway->createNodeAssignment(
168
                $location,
169
                $location->parentId,
170
                LocationGateway::NODE_ASSIGNMENT_OP_CODE_CREATE
171
            );
172
        }
173
174
        // Create names
175 View Code Duplication
        foreach ($content->versionInfo->names as $language => $name) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
176
            $this->contentGateway->setName(
177
                $content->versionInfo->contentInfo->id,
178
                $content->versionInfo->versionNo,
179
                $name,
180
                $language
181
            );
182
        }
183
184
        return $content;
185
    }
186
187
    /**
188
     * Performs the publishing operations required to set the version identified by $updateStruct->versionNo and
189
     * $updateStruct->id as the published one.
190
     *
191
     * The publish procedure will:
192
     * - Create location nodes based on the node assignments
193
     * - Update the content object using the provided metadata update struct
194
     * - Update the node assignments
195
     * - Update location nodes of the content with the new published version
196
     * - Set content and version status to published
197
     *
198
     * @param int $contentId
199
     * @param int $versionNo
200
     * @param \eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct $metaDataUpdateStruct
201
     *
202
     * @return \eZ\Publish\SPI\Persistence\Content The published Content
203
     */
204
    public function publish($contentId, $versionNo, MetadataUpdateStruct $metaDataUpdateStruct)
205
    {
206
        // Archive currently published version
207
        $versionInfo = $this->loadVersionInfo($contentId, $versionNo);
208
        if ($versionInfo->contentInfo->currentVersionNo != $versionNo) {
209
            $this->setStatus(
210
                $contentId,
211
                VersionInfo::STATUS_ARCHIVED,
212
                $versionInfo->contentInfo->currentVersionNo
213
            );
214
        }
215
216
        // Set always available name for the content
217
        $metaDataUpdateStruct->name = $versionInfo->names[$versionInfo->contentInfo->mainLanguageCode];
218
219
        $this->contentGateway->updateContent($contentId, $metaDataUpdateStruct, $versionInfo);
220
        $this->locationGateway->createLocationsFromNodeAssignments(
221
            $contentId,
222
            $versionNo
223
        );
224
225
        $this->locationGateway->updateLocationsContentVersionNo($contentId, $versionNo);
226
        $this->setStatus($contentId, VersionInfo::STATUS_PUBLISHED, $versionNo);
227
228
        return $this->load($contentId, $versionNo);
229
    }
230
231
    /**
232
     * Creates a new draft version from $contentId in $version.
233
     *
234
     * Copies all fields from $contentId in $srcVersion and creates a new
235
     * version of the referred Content from it.
236
     *
237
     * Note: When creating a new draft in the old admin interface there will
238
     * also be an entry in the `eznode_assignment` created for the draft. This
239
     * is ignored in this implementation.
240
     *
241
     * @param mixed $contentId
242
     * @param mixed $srcVersion
243
     * @param mixed $userId
244
     *
245
     * @return \eZ\Publish\SPI\Persistence\Content
246
     */
247
    public function createDraftFromVersion($contentId, $srcVersion, $userId)
248
    {
249
        $content = $this->load($contentId, $srcVersion);
250
251
        // Create new version
252
        $content->versionInfo = $this->mapper->createVersionInfoForContent(
253
            $content,
254
            $this->contentGateway->getLastVersionNumber($contentId) + 1,
255
            $userId
256
        );
257
        $content->versionInfo->id = $this->contentGateway->insertVersion(
258
            $content->versionInfo,
259
            $content->fields
260
        );
261
262
        // Clone fields from previous version and append them to the new one
263
        $this->fieldHandler->createExistingFieldsInNewVersion($content);
264
265
        // Create relations for new version
266
        $relations = $this->contentGateway->loadRelations($contentId, $srcVersion);
267
        foreach ($relations as $relation) {
268
            $this->contentGateway->insertRelation(
269
                new RelationCreateStruct(
270
                    array(
271
                        'sourceContentId' => $contentId,
272
                        'sourceContentVersionNo' => $content->versionInfo->versionNo,
273
                        'sourceFieldDefinitionId' => $relation['ezcontentobject_link_contentclassattribute_id'],
274
                        'destinationContentId' => $relation['ezcontentobject_link_to_contentobject_id'],
275
                        'type' => (int)$relation['ezcontentobject_link_relation_type'],
276
                    )
277
                )
278
            );
279
        }
280
281
        // Create content names for new version
282
        foreach ($content->versionInfo->names as $language => $name) {
283
            $this->contentGateway->setName(
284
                $contentId,
285
                $content->versionInfo->versionNo,
286
                $name,
287
                $language
288
            );
289
        }
290
291
        return $content;
292
    }
293
294
    /**
295
     * Returns the raw data of a content object identified by $id, in a struct.
296
     *
297
     * A version to load must be specified. If you want to load the current
298
     * version of a content object use SearchHandler::findSingle() with the
299
     * ContentId criterion.
300
     *
301
     * Optionally a translation filter may be specified. If specified only the
302
     * translations with the listed language codes will be retrieved. If not,
303
     * all translations will be retrieved.
304
     *
305
     * @param int|string $id
306
     * @param int|string $version
307
     * @param string[] $translations
308
     *
309
     * @return \eZ\Publish\SPI\Persistence\Content Content value object
310
     */
311
    public function load($id, $version, array $translations = null)
312
    {
313
        $rows = $this->contentGateway->load($id, $version, $translations);
314
315
        if (empty($rows)) {
316
            throw new NotFound('content', "contentId: $id, versionNo: $version");
317
        }
318
319
        $contentObjects = $this->mapper->extractContentFromRows(
320
            $rows,
321
            $this->contentGateway->loadVersionedNameData(array(array('id' => $id, 'version' => $version)))
322
        );
323
        $content = $contentObjects[0];
324
325
        $this->fieldHandler->loadExternalFieldData($content);
326
327
        return $content;
328
    }
329
330
    /**
331
     * Returns the metadata object for a content identified by $contentId.
332
     *
333
     * @param int|string $contentId
334
     *
335
     * @return \eZ\Publish\SPI\Persistence\Content\ContentInfo
336
     */
337
    public function loadContentInfo($contentId)
338
    {
339
        return $this->treeHandler->loadContentInfo($contentId);
340
    }
341
342
    public function loadContentInfoList(array $contentIds)
343
    {
344
        $list = $this->mapper->extractContentInfoFromRows(
345
            $this->contentGateway->loadContentInfoList($contentIds)
346
        );
347
348
        $listByContentId = [];
349
        foreach ($list as $item) {
350
            $listByContentId[$item->id] = $item;
351
        }
352
353
        return $listByContentId;
354
    }
355
356
    /**
357
     * Returns the metadata object for a content identified by $remoteId.
358
     *
359
     * @param mixed $remoteId
360
     *
361
     * @return \eZ\Publish\SPI\Persistence\Content\ContentInfo
362
     */
363
    public function loadContentInfoByRemoteId($remoteId)
364
    {
365
        return $this->mapper->extractContentInfoFromRow(
366
            $this->contentGateway->loadContentInfoByRemoteId($remoteId)
367
        );
368
    }
369
370
    /**
371
     * Returns the version object for a content/version identified by $contentId and $versionNo.
372
     *
373
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException If version is not found
374
     *
375
     * @param int|string $contentId
376
     * @param int $versionNo Version number to load
377
     *
378
     * @return \eZ\Publish\SPI\Persistence\Content\VersionInfo
379
     */
380
    public function loadVersionInfo($contentId, $versionNo)
381
    {
382
        $rows = $this->contentGateway->loadVersionInfo($contentId, $versionNo);
383
        if (empty($rows)) {
384
            throw new NotFound('content', $contentId);
385
        }
386
387
        $versionInfo = $this->mapper->extractVersionInfoListFromRows(
388
            $rows,
389
            $this->contentGateway->loadVersionedNameData(array(array('id' => $contentId, 'version' => $versionNo)))
390
        );
391
392
        return reset($versionInfo);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression reset($versionInfo); of type eZ\Publish\SPI\Persisten...ntent\VersionInfo|false adds false to the return on line 392 which is incompatible with the return type declared by the interface eZ\Publish\SPI\Persisten...andler::loadVersionInfo of type eZ\Publish\SPI\Persistence\Content\VersionInfo. It seems like you forgot to handle an error condition.
Loading history...
393
    }
394
395
    /**
396
     * Returns all versions with draft status created by the given $userId.
397
     *
398
     * @param int $userId
399
     *
400
     * @return \eZ\Publish\SPI\Persistence\Content\VersionInfo[]
401
     */
402 View Code Duplication
    public function loadDraftsForUser($userId)
403
    {
404
        $rows = $this->contentGateway->listVersionsForUser($userId, VersionInfo::STATUS_DRAFT);
405
        if (empty($rows)) {
406
            return array();
407
        }
408
409
        $idVersionPairs = array_map(
410
            function ($row) {
411
                return array(
412
                    'id' => $row['ezcontentobject_version_contentobject_id'],
413
                    'version' => $row['ezcontentobject_version_version'],
414
                );
415
            },
416
            $rows
417
        );
418
        $nameRows = $this->contentGateway->loadVersionedNameData($idVersionPairs);
419
420
        return $this->mapper->extractVersionInfoListFromRows($rows, $nameRows);
421
    }
422
423
    /**
424
     * Sets the status of object identified by $contentId and $version to $status.
425
     *
426
     * The $status can be one of VersionInfo::STATUS_DRAFT, VersionInfo::STATUS_PUBLISHED, VersionInfo::STATUS_ARCHIVED
427
     * When status is set to VersionInfo::STATUS_PUBLISHED content status is updated to ContentInfo::STATUS_PUBLISHED
428
     *
429
     * @param int $contentId
430
     * @param int $status
431
     * @param int $version
432
     *
433
     * @return bool
434
     */
435
    public function setStatus($contentId, $status, $version)
436
    {
437
        return $this->contentGateway->setStatus($contentId, $version, $status);
438
    }
439
440
    /**
441
     * Updates a content object meta data, identified by $contentId.
442
     *
443
     * @param int $contentId
444
     * @param \eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct $content
445
     *
446
     * @return \eZ\Publish\SPI\Persistence\Content\ContentInfo
447
     */
448
    public function updateMetadata($contentId, MetadataUpdateStruct $content)
449
    {
450
        $this->contentGateway->updateContent($contentId, $content);
451
        $this->updatePathIdentificationString($contentId, $content);
452
453
        return $this->loadContentInfo($contentId);
454
    }
455
456
    /**
457
     * Updates path identification string for locations of given $contentId if main language
458
     * is set in update struct.
459
     *
460
     * This is specific to the Legacy storage engine, as path identification string is deprecated.
461
     *
462
     * @param int $contentId
463
     * @param \eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct $content
464
     */
465
    protected function updatePathIdentificationString($contentId, MetadataUpdateStruct $content)
466
    {
467
        if (isset($content->mainLanguageId)) {
468
            $contentLocationsRows = $this->locationGateway->loadLocationDataByContent($contentId);
469
            foreach ($contentLocationsRows as $row) {
470
                $locationName = '';
471
                $urlAliasRows = $this->urlAliasGateway->loadLocationEntries(
472
                    $row['node_id'],
473
                    false,
474
                    $content->mainLanguageId
475
                );
476
                if (!empty($urlAliasRows)) {
477
                    $locationName = $urlAliasRows[0]['text'];
478
                }
479
                $this->locationGateway->updatePathIdentificationString(
480
                    $row['node_id'],
481
                    $row['parent_node_id'],
482
                    $this->slugConverter->convert(
483
                        $locationName,
484
                        'node_' . $row['node_id'],
485
                        'urlalias_compat'
486
                    )
487
                );
488
            }
489
        }
490
    }
491
492
    /**
493
     * Updates a content version, identified by $contentId and $versionNo.
494
     *
495
     * @param int $contentId
496
     * @param int $versionNo
497
     * @param \eZ\Publish\SPI\Persistence\Content\UpdateStruct $updateStruct
498
     *
499
     * @return \eZ\Publish\SPI\Persistence\Content
500
     */
501
    public function updateContent($contentId, $versionNo, UpdateStruct $updateStruct)
502
    {
503
        $content = $this->load($contentId, $versionNo);
504
        $this->contentGateway->updateVersion($contentId, $versionNo, $updateStruct);
505
        $contentType = $this->contentTypeHandler->load($content->versionInfo->contentInfo->contentTypeId);
506
        $this->fieldHandler->updateFields($content, $updateStruct, $contentType);
507
        foreach ($updateStruct->name as $language => $name) {
508
            $this->contentGateway->setName(
509
                $contentId,
510
                $versionNo,
511
                $name,
512
                $language
513
            );
514
        }
515
516
        return $this->load($contentId, $versionNo);
517
    }
518
519
    /**
520
     * Deletes all versions and fields, all locations (subtree), and all relations.
521
     *
522
     * Removes the relations, but not the related objects. All subtrees of the
523
     * assigned nodes of this content objects are removed (recursively).
524
     *
525
     * @param int $contentId
526
     *
527
     * @return bool
528
     */
529
    public function deleteContent($contentId)
530
    {
531
        $contentLocations = $this->contentGateway->getAllLocationIds($contentId);
532
        if (empty($contentLocations)) {
533
            $this->removeRawContent($contentId);
534
        } else {
535
            foreach ($contentLocations as $locationId) {
536
                $this->treeHandler->removeSubtree($locationId);
537
            }
538
        }
539
    }
540
541
    /**
542
     * Deletes raw content data.
543
     *
544
     * @param int $contentId
545
     */
546
    public function removeRawContent($contentId)
547
    {
548
        $this->treeHandler->removeRawContent($contentId);
549
    }
550
551
    /**
552
     * Deletes given version, its fields, node assignment, relations and names.
553
     *
554
     * Removes the relations, but not the related objects.
555
     *
556
     * @param int $contentId
557
     * @param int $versionNo
558
     *
559
     * @return bool
560
     */
561
    public function deleteVersion($contentId, $versionNo)
562
    {
563
        $versionInfo = $this->loadVersionInfo($contentId, $versionNo);
564
565
        $this->locationGateway->deleteNodeAssignment($contentId, $versionNo);
566
567
        $this->fieldHandler->deleteFields($contentId, $versionInfo);
568
569
        $this->contentGateway->deleteRelations($contentId, $versionNo);
570
        $this->contentGateway->deleteVersions($contentId, $versionNo);
571
        $this->contentGateway->deleteNames($contentId, $versionNo);
572
    }
573
574
    /**
575
     * Returns the versions for $contentId.
576
     *
577
     * Result is returned with oldest version first (sorted by created, alternatively version id if auto increment).
578
     *
579
     * @param int $contentId
580
     * @param mixed|null $status Optional argument to filter versions by status, like {@see VersionInfo::STATUS_ARCHIVED}.
581
     * @param int $limit Limit for items returned, -1 means none.
582
     *
583
     * @return \eZ\Publish\SPI\Persistence\Content\VersionInfo[]
584
     */
585
    public function listVersions($contentId, $status = null, $limit = -1)
586
    {
587
        return $this->treeHandler->listVersions($contentId, $status, $limit);
588
    }
589
590
    /**
591
     * Copy Content with Fields, Versions & Relations from $contentId in $version.
592
     *
593
     * {@inheritdoc}
594
     *
595
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException If content or version is not found
596
     *
597
     * @param mixed $contentId
598
     * @param mixed|null $versionNo Copy all versions if left null
599
     *
600
     * @return \eZ\Publish\SPI\Persistence\Content
601
     */
602
    public function copy($contentId, $versionNo = null)
603
    {
604
        $currentVersionNo = isset($versionNo) ?
605
            $versionNo :
606
            $this->loadContentInfo($contentId)->currentVersionNo;
607
608
        // Copy content in given version or current version
609
        $createStruct = $this->mapper->createCreateStructFromContent(
610
            $this->load($contentId, $currentVersionNo)
611
        );
612
        $content = $this->internalCreate($createStruct, $currentVersionNo);
613
614
        // If version was not passed also copy other versions
615
        if (!isset($versionNo)) {
616
            $contentType = $this->contentTypeHandler->load($createStruct->typeId);
617
618
            foreach ($this->listVersions($contentId) as $versionInfo) {
619
                if ($versionInfo->versionNo === $currentVersionNo) {
620
                    continue;
621
                }
622
623
                $versionContent = $this->load($contentId, $versionInfo->versionNo);
624
625
                $versionContent->versionInfo->contentInfo->id = $content->versionInfo->contentInfo->id;
626
                $versionContent->versionInfo->modificationDate = $createStruct->modified;
627
                $versionContent->versionInfo->creationDate = $createStruct->modified;
628
                $versionContent->versionInfo->id = $this->contentGateway->insertVersion(
629
                    $versionContent->versionInfo,
630
                    $versionContent->fields
631
                );
632
633
                $this->fieldHandler->createNewFields($versionContent, $contentType);
634
635
                // Create names
636 View Code Duplication
                foreach ($versionContent->versionInfo->names as $language => $name) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
637
                    $this->contentGateway->setName(
638
                        $content->versionInfo->contentInfo->id,
639
                        $versionInfo->versionNo,
640
                        $name,
641
                        $language
642
                    );
643
                }
644
            }
645
646
            // Batch copy relations for all versions
647
            $this->contentGateway->copyRelations($contentId, $content->versionInfo->contentInfo->id);
648
        } else {
649
            // Batch copy relations for published version
650
            $this->contentGateway->copyRelations($contentId, $content->versionInfo->contentInfo->id, $versionNo);
651
        }
652
653
        return $content;
654
    }
655
656
    /**
657
     * Creates a relation between $sourceContentId in $sourceContentVersionNo
658
     * and $destinationContentId with a specific $type.
659
     *
660
     * @todo Should the existence verifications happen here or is this supposed to be handled at a higher level?
661
     *
662
     * @param \eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct $createStruct
663
     *
664
     * @return \eZ\Publish\SPI\Persistence\Content\Relation
665
     */
666
    public function addRelation(RelationCreateStruct $createStruct)
667
    {
668
        $relation = $this->mapper->createRelationFromCreateStruct($createStruct);
669
670
        $relation->id = $this->contentGateway->insertRelation($createStruct);
671
672
        return $relation;
673
    }
674
675
    /**
676
     * Removes a relation by relation Id.
677
     *
678
     * @todo Should the existence verifications happen here or is this supposed to be handled at a higher level?
679
     *
680
     * @param mixed $relationId
681
     * @param int $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
682
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
683
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
684
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
685
     */
686
    public function removeRelation($relationId, $type)
687
    {
688
        $this->contentGateway->deleteRelation($relationId, $type);
689
    }
690
691
    /**
692
     * Loads relations from $sourceContentId. Optionally, loads only those with $type and $sourceContentVersionNo.
693
     *
694
     * @param mixed $sourceContentId Source Content ID
695
     * @param mixed|null $sourceContentVersionNo Source Content Version, null if not specified
696
     * @param int|null $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
697
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
698
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
699
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
700
     *
701
     * @return \eZ\Publish\SPI\Persistence\Content\Relation[]
702
     */
703
    public function loadRelations($sourceContentId, $sourceContentVersionNo = null, $type = null)
704
    {
705
        return $this->mapper->extractRelationsFromRows(
706
            $this->contentGateway->loadRelations($sourceContentId, $sourceContentVersionNo, $type)
707
        );
708
    }
709
710
    /**
711
     * Loads relations from $contentId. Optionally, loads only those with $type.
712
     *
713
     * Only loads relations against published versions.
714
     *
715
     * @param mixed $destinationContentId Destination Content ID
716
     * @param int|null $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
717
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
718
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
719
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
720
     *
721
     * @return \eZ\Publish\SPI\Persistence\Content\Relation[]
722
     */
723
    public function loadReverseRelations($destinationContentId, $type = null)
724
    {
725
        return $this->mapper->extractRelationsFromRows(
726
            $this->contentGateway->loadReverseRelations($destinationContentId, $type)
727
        );
728
    }
729
730
    /**
731
     * {@inheritdoc}
732
     */
733
    public function removeTranslationFromContent($contentId, $languageCode)
734
    {
735
        @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
736
            __METHOD__ . ' is deprecated, use deleteTranslationFromContent instead',
737
            E_USER_DEPRECATED
738
        );
739
        $this->deleteTranslationFromContent($contentId, $languageCode);
740
    }
741
742
    /**
743
     * {@inheritdoc}
744
     */
745
    public function deleteTranslationFromContent($contentId, $languageCode)
746
    {
747
        $this->fieldHandler->deleteTranslationFromContentFields(
748
            $contentId,
749
            $this->listVersions($contentId),
750
            $languageCode
751
        );
752
        $this->contentGateway->deleteTranslationFromContent($contentId, $languageCode);
753
    }
754
755
    /**
756
     * {@inheritdoc}
757
     */
758
    public function deleteTranslationFromDraft($contentId, $versionNo, $languageCode)
759
    {
760
        $versionInfo = $this->loadVersionInfo($contentId, $versionNo);
761
762
        $this->fieldHandler->deleteTranslationFromVersionFields(
763
            $versionInfo,
764
            $languageCode
765
        );
766
        $this->contentGateway->deleteTranslationFromVersion(
767
            $contentId,
768
            $versionNo,
769
            $languageCode
770
        );
771
772
        // get all [languageCode => name] entries except the removed Translation
773
        $names = array_filter(
774
            $versionInfo->names,
775
            function ($lang) use ($languageCode) {
776
                return $lang !== $languageCode;
777
            },
778
            ARRAY_FILTER_USE_KEY
779
        );
780
        // set new Content name
781
        foreach ($names as $language => $name) {
782
            $this->contentGateway->setName(
783
                $contentId,
784
                $versionNo,
785
                $name,
786
                $language
787
            );
788
        }
789
790
        // reload entire Version w/o removed Translation
791
        return $this->load($contentId, $versionNo);
792
    }
793
}
794