Completed
Push — 6.13 ( 878d09...f11ecd )
by
unknown
26:52
created

Handler::publish()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 3
dl 0
loc 26
rs 9.504
c 0
b 0
f 0
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 Exception;
12
use eZ\Publish\Core\Persistence\Legacy\Content\Location\Gateway as LocationGateway;
13
use eZ\Publish\SPI\Persistence\Content\Handler as BaseContentHandler;
14
use eZ\Publish\SPI\Persistence\Content\Type\Handler as ContentTypeHandler;
15
use eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\SlugConverter;
16
use eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\Gateway as UrlAliasGateway;
17
use eZ\Publish\SPI\Persistence\Content;
18
use eZ\Publish\SPI\Persistence\Content\CreateStruct;
19
use eZ\Publish\SPI\Persistence\Content\UpdateStruct;
20
use eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct;
21
use eZ\Publish\SPI\Persistence\Content\VersionInfo;
22
use eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct as RelationCreateStruct;
23
use eZ\Publish\Core\Base\Exceptions\NotFoundException as NotFound;
24
use Psr\Log\LoggerInterface;
25
use Psr\Log\NullLogger;
26
27
/**
28
 * The Content Handler stores Content and ContentType objects.
29
 */
30
class Handler implements BaseContentHandler
31
{
32
    /**
33
     * Content gateway.
34
     *
35
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\Gateway
36
     */
37
    protected $contentGateway;
38
39
    /**
40
     * Location gateway.
41
     *
42
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\Location\Gateway
43
     */
44
    protected $locationGateway;
45
46
    /**
47
     * Mapper.
48
     *
49
     * @var Mapper
50
     */
51
    protected $mapper;
52
53
    /**
54
     * FieldHandler.
55
     *
56
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\FieldHandler
57
     */
58
    protected $fieldHandler;
59
60
    /**
61
     * URL slug converter.
62
     *
63
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\SlugConverter
64
     */
65
    protected $slugConverter;
66
67
    /**
68
     * UrlAlias gateway.
69
     *
70
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\Gateway
71
     */
72
    protected $urlAliasGateway;
73
74
    /**
75
     * ContentType handler.
76
     *
77
     * @var \eZ\Publish\SPI\Persistence\Content\Type\Handler
78
     */
79
    protected $contentTypeHandler;
80
81
    /**
82
     * Tree handler.
83
     *
84
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\TreeHandler
85
     */
86
    protected $treeHandler;
87
88
    /**
89
     * @var \Psr\Log\LoggerInterface
90
     */
91
    private $logger;
92
93
    /**
94
     * Creates a new content handler.
95
     *
96
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\Gateway $contentGateway
97
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\Location\Gateway $locationGateway
98
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\Mapper $mapper
99
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\FieldHandler $fieldHandler
100
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\SlugConverter $slugConverter
101
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\Gateway $urlAliasGateway
102
     * @param \eZ\Publish\SPI\Persistence\Content\Type\Handler $contentTypeHandler
103
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\TreeHandler $treeHandler
104
     * @param \Psr\Log\LoggerInterface|null $logger
105
     */
106
    public function __construct(
107
        Gateway $contentGateway,
108
        LocationGateway $locationGateway,
109
        Mapper $mapper,
110
        FieldHandler $fieldHandler,
111
        SlugConverter $slugConverter,
112
        UrlAliasGateway $urlAliasGateway,
113
        ContentTypeHandler $contentTypeHandler,
114
        TreeHandler $treeHandler,
115
        LoggerInterface $logger = null
116
    ) {
117
        $this->contentGateway = $contentGateway;
118
        $this->locationGateway = $locationGateway;
119
        $this->mapper = $mapper;
120
        $this->fieldHandler = $fieldHandler;
121
        $this->slugConverter = $slugConverter;
122
        $this->urlAliasGateway = $urlAliasGateway;
123
        $this->contentTypeHandler = $contentTypeHandler;
124
        $this->treeHandler = $treeHandler;
125
        $this->logger = null !== $logger ? $logger : new NullLogger();
126
    }
127
128
    /**
129
     * Creates a new Content entity in the storage engine.
130
     *
131
     * The values contained inside the $content will form the basis of stored
132
     * entity.
133
     *
134
     * Will contain always a complete list of fields.
135
     *
136
     * @param \eZ\Publish\SPI\Persistence\Content\CreateStruct $struct Content creation struct.
137
     *
138
     * @return \eZ\Publish\SPI\Persistence\Content Content value object
139
     */
140
    public function create(CreateStruct $struct)
141
    {
142
        return $this->internalCreate($struct);
143
    }
144
145
    /**
146
     * Creates a new Content entity in the storage engine.
147
     *
148
     * The values contained inside the $content will form the basis of stored
149
     * entity.
150
     *
151
     * Will contain always a complete list of fields.
152
     *
153
     * @param \eZ\Publish\SPI\Persistence\Content\CreateStruct $struct Content creation struct.
154
     * @param mixed $versionNo Used by self::copy() to maintain version numbers
155
     *
156
     * @return \eZ\Publish\SPI\Persistence\Content Content value object
157
     */
158
    protected function internalCreate(CreateStruct $struct, $versionNo = 1)
159
    {
160
        $content = new Content();
161
162
        $content->fields = $struct->fields;
163
        $content->versionInfo = $this->mapper->createVersionInfoFromCreateStruct($struct, $versionNo);
164
165
        $content->versionInfo->contentInfo->id = $this->contentGateway->insertContentObject($struct, $versionNo);
166
        $content->versionInfo->id = $this->contentGateway->insertVersion(
167
            $content->versionInfo,
168
            $struct->fields
169
        );
170
171
        $contentType = $this->contentTypeHandler->load($struct->typeId);
172
        $this->fieldHandler->createNewFields($content, $contentType);
173
174
        // Create node assignments
175
        foreach ($struct->locations as $location) {
176
            $location->contentId = $content->versionInfo->contentInfo->id;
177
            $location->contentVersion = $content->versionInfo->versionNo;
178
            $this->locationGateway->createNodeAssignment(
179
                $location,
180
                $location->parentId,
181
                LocationGateway::NODE_ASSIGNMENT_OP_CODE_CREATE
182
            );
183
        }
184
185
        // Create names
186 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...
187
            $this->contentGateway->setName(
188
                $content->versionInfo->contentInfo->id,
189
                $content->versionInfo->versionNo,
190
                $name,
191
                $language
192
            );
193
        }
194
195
        return $content;
196
    }
197
198
    /**
199
     * Performs the publishing operations required to set the version identified by $updateStruct->versionNo and
200
     * $updateStruct->id as the published one.
201
     *
202
     * The publish procedure will:
203
     * - Create location nodes based on the node assignments
204
     * - Update the content object using the provided metadata update struct
205
     * - Update the node assignments
206
     * - Update location nodes of the content with the new published version
207
     * - Set content and version status to published
208
     *
209
     * @param int $contentId
210
     * @param int $versionNo
211
     * @param \eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct $metaDataUpdateStruct
212
     *
213
     * @return \eZ\Publish\SPI\Persistence\Content The published Content
214
     */
215
    public function publish($contentId, $versionNo, MetadataUpdateStruct $metaDataUpdateStruct)
216
    {
217
        // Archive currently published version
218
        $versionInfo = $this->loadVersionInfo($contentId, $versionNo);
219
        if ($versionInfo->contentInfo->currentVersionNo != $versionNo) {
220
            $this->setStatus(
221
                $contentId,
222
                VersionInfo::STATUS_ARCHIVED,
223
                $versionInfo->contentInfo->currentVersionNo
224
            );
225
        }
226
227
        // Set always available name for the content
228
        $metaDataUpdateStruct->name = $versionInfo->names[$versionInfo->contentInfo->mainLanguageCode];
229
230
        $this->contentGateway->updateContent($contentId, $metaDataUpdateStruct, $versionInfo);
231
        $this->locationGateway->createLocationsFromNodeAssignments(
232
            $contentId,
233
            $versionNo
234
        );
235
236
        $this->locationGateway->updateLocationsContentVersionNo($contentId, $versionNo);
237
        $this->setStatus($contentId, VersionInfo::STATUS_PUBLISHED, $versionNo);
238
239
        return $this->load($contentId, $versionNo);
240
    }
241
242
    /**
243
     * Creates a new draft version from $contentId in $version.
244
     *
245
     * Copies all fields from $contentId in $srcVersion and creates a new
246
     * version of the referred Content from it.
247
     *
248
     * Note: When creating a new draft in the old admin interface there will
249
     * also be an entry in the `eznode_assignment` created for the draft. This
250
     * is ignored in this implementation.
251
     *
252
     * @param mixed $contentId
253
     * @param mixed $srcVersion
254
     * @param mixed $userId
255
     *
256
     * @return \eZ\Publish\SPI\Persistence\Content
257
     */
258
    public function createDraftFromVersion($contentId, $srcVersion, $userId)
259
    {
260
        $content = $this->load($contentId, $srcVersion);
261
262
        // Create new version
263
        $content->versionInfo = $this->mapper->createVersionInfoForContent(
264
            $content,
265
            $this->contentGateway->getLastVersionNumber($contentId) + 1,
266
            $userId
267
        );
268
        $content->versionInfo->id = $this->contentGateway->insertVersion(
269
            $content->versionInfo,
270
            $content->fields
271
        );
272
273
        // Clone fields from previous version and append them to the new one
274
        $this->fieldHandler->createExistingFieldsInNewVersion($content);
275
276
        // Create relations for new version
277
        $relations = $this->contentGateway->loadRelations($contentId, $srcVersion);
278
        foreach ($relations as $relation) {
279
            $this->contentGateway->insertRelation(
280
                new RelationCreateStruct(
281
                    array(
282
                        'sourceContentId' => $contentId,
283
                        'sourceContentVersionNo' => $content->versionInfo->versionNo,
284
                        'sourceFieldDefinitionId' => $relation['ezcontentobject_link_contentclassattribute_id'],
285
                        'destinationContentId' => $relation['ezcontentobject_link_to_contentobject_id'],
286
                        'type' => (int)$relation['ezcontentobject_link_relation_type'],
287
                    )
288
                )
289
            );
290
        }
291
292
        // Create content names for new version
293
        foreach ($content->versionInfo->names as $language => $name) {
294
            $this->contentGateway->setName(
295
                $contentId,
296
                $content->versionInfo->versionNo,
297
                $name,
298
                $language
299
            );
300
        }
301
302
        return $content;
303
    }
304
305
    /**
306
     * Returns the raw data of a content object identified by $id, in a struct.
307
     *
308
     * A version to load must be specified. If you want to load the current
309
     * version of a content object use SearchHandler::findSingle() with the
310
     * ContentId criterion.
311
     *
312
     * Optionally a translation filter may be specified. If specified only the
313
     * translations with the listed language codes will be retrieved. If not,
314
     * all translations will be retrieved.
315
     *
316
     * @param int|string $id
317
     * @param int|string $version
318
     * @param string[] $translations
319
     *
320
     * @return \eZ\Publish\SPI\Persistence\Content Content value object
321
     */
322
    public function load($id, $version, array $translations = null)
323
    {
324
        $rows = $this->contentGateway->load($id, $version, $translations);
325
326
        if (empty($rows)) {
327
            throw new NotFound('content', "contentId: $id, versionNo: $version");
328
        }
329
330
        $contentObjects = $this->mapper->extractContentFromRows(
331
            $rows,
332
            $this->contentGateway->loadVersionedNameData(array(array('id' => $id, 'version' => $version)))
333
        );
334
        $content = $contentObjects[0];
335
336
        $this->fieldHandler->loadExternalFieldData($content);
337
338
        return $content;
339
    }
340
341
    /**
342
     * {@inheritdoc}
343
     */
344
    public function loadContentList(array $contentIds, array $translations = null)
345
    {
346
        $rawList = $this->contentGateway->loadContentList($contentIds, $translations);
0 ignored issues
show
Bug introduced by
It seems like $translations defined by parameter $translations on line 344 can also be of type array; however, eZ\Publish\Core\Persiste...eway::loadContentList() does only seem to accept null|array<integer,string>, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and 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...
347
        if (empty($rawList)) {
348
            return [];
349
        }
350
351
        $idVersionPairs = [];
352
        foreach ($rawList as $row) {
353
            // As there is only one version per id, set id as key to avoid duplicates
354
            $idVersionPairs[$row['ezcontentobject_id']] = [
355
                'id' => $row['ezcontentobject_id'],
356
                'version' => $row['ezcontentobject_version_version'],
357
            ];
358
        }
359
360
        // group name data per Content Id
361
        $nameData = $this->contentGateway->loadVersionedNameData(array_values($idVersionPairs));
362
        $contentItemNameData = [];
363
        foreach ($nameData as $nameDataRow) {
364
            $contentId = $nameDataRow['ezcontentobject_name_contentobject_id'];
365
            $contentItemNameData[$contentId][] = $nameDataRow;
366
        }
367
368
        // group rows per Content Id be able to ignore Content items with erroneous data
369
        $contentItemsRows = [];
370
        foreach ($rawList as $row) {
371
            $contentId = $row['ezcontentobject_id'];
372
            $contentItemsRows[$contentId][] = $row;
373
        }
374
        unset($rawList, $idVersionPairs);
375
376
        // try to extract Content from each Content data
377
        $contentItems = [];
378
        foreach ($contentItemsRows as $contentId => $contentItemsRow) {
379
            try {
380
                $contentList = $this->mapper->extractContentFromRows(
381
                    $contentItemsRow,
382
                    $contentItemNameData[$contentId]
383
                );
384
                $contentItems[$contentId] = $contentList[0];
385
            } catch (Exception $e) {
386
                $this->logger->warning(
387
                    sprintf(
388
                        '%s: Content %d not loaded: %s',
389
                        __METHOD__,
390
                        $contentId,
391
                        $e->getMessage()
392
                    )
393
                );
394
            }
395
        }
396
397
        // try to load External Storage data for each Content, ignore Content items for which it failed
398
        foreach ($contentItems as $contentId => $content) {
399
            try {
400
                $this->fieldHandler->loadExternalFieldData($content);
401
            } catch (Exception $e) {
402
                unset($contentItems[$contentId]);
403
                $this->logger->warning(
404
                    sprintf(
405
                        '%s: Content %d not loaded: %s',
406
                        __METHOD__,
407
                        $contentId,
408
                        $e->getMessage()
409
                    )
410
                );
411
            }
412
        }
413
414
        return $contentItems;
415
    }
416
417
    /**
418
     * Returns the metadata object for a content identified by $contentId.
419
     *
420
     * @param int|string $contentId
421
     *
422
     * @return \eZ\Publish\SPI\Persistence\Content\ContentInfo
423
     */
424
    public function loadContentInfo($contentId)
425
    {
426
        return $this->treeHandler->loadContentInfo($contentId);
427
    }
428
429
    public function loadContentInfoList(array $contentIds)
430
    {
431
        $list = $this->mapper->extractContentInfoFromRows(
432
            $this->contentGateway->loadContentInfoList($contentIds)
433
        );
434
435
        $listByContentId = [];
436
        foreach ($list as $item) {
437
            $listByContentId[$item->id] = $item;
438
        }
439
440
        return $listByContentId;
441
    }
442
443
    /**
444
     * Returns the metadata object for a content identified by $remoteId.
445
     *
446
     * @param mixed $remoteId
447
     *
448
     * @return \eZ\Publish\SPI\Persistence\Content\ContentInfo
449
     */
450
    public function loadContentInfoByRemoteId($remoteId)
451
    {
452
        return $this->mapper->extractContentInfoFromRow(
453
            $this->contentGateway->loadContentInfoByRemoteId($remoteId)
454
        );
455
    }
456
457
    /**
458
     * Returns the version object for a content/version identified by $contentId and $versionNo.
459
     *
460
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException If version is not found
461
     *
462
     * @param int|string $contentId
463
     * @param int $versionNo Version number to load
464
     *
465
     * @return \eZ\Publish\SPI\Persistence\Content\VersionInfo
466
     */
467
    public function loadVersionInfo($contentId, $versionNo)
468
    {
469
        $rows = $this->contentGateway->loadVersionInfo($contentId, $versionNo);
470
        if (empty($rows)) {
471
            throw new NotFound('content', $contentId);
472
        }
473
474
        $versionInfo = $this->mapper->extractVersionInfoListFromRows(
475
            $rows,
476
            $this->contentGateway->loadVersionedNameData(array(array('id' => $contentId, 'version' => $versionNo)))
477
        );
478
479
        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 479 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...
480
    }
481
482
    /**
483
     * Returns all versions with draft status created by the given $userId.
484
     *
485
     * @param int $userId
486
     *
487
     * @return \eZ\Publish\SPI\Persistence\Content\VersionInfo[]
488
     */
489 View Code Duplication
    public function loadDraftsForUser($userId)
490
    {
491
        $rows = $this->contentGateway->listVersionsForUser($userId, VersionInfo::STATUS_DRAFT);
492
        if (empty($rows)) {
493
            return array();
494
        }
495
496
        $idVersionPairs = array_map(
497
            function ($row) {
498
                return array(
499
                    'id' => $row['ezcontentobject_version_contentobject_id'],
500
                    'version' => $row['ezcontentobject_version_version'],
501
                );
502
            },
503
            $rows
504
        );
505
        $nameRows = $this->contentGateway->loadVersionedNameData($idVersionPairs);
506
507
        return $this->mapper->extractVersionInfoListFromRows($rows, $nameRows);
508
    }
509
510
    /**
511
     * Sets the status of object identified by $contentId and $version to $status.
512
     *
513
     * The $status can be one of VersionInfo::STATUS_DRAFT, VersionInfo::STATUS_PUBLISHED, VersionInfo::STATUS_ARCHIVED
514
     * When status is set to VersionInfo::STATUS_PUBLISHED content status is updated to ContentInfo::STATUS_PUBLISHED
515
     *
516
     * @param int $contentId
517
     * @param int $status
518
     * @param int $version
519
     *
520
     * @return bool
521
     */
522
    public function setStatus($contentId, $status, $version)
523
    {
524
        return $this->contentGateway->setStatus($contentId, $version, $status);
525
    }
526
527
    /**
528
     * Updates a content object meta data, identified by $contentId.
529
     *
530
     * @param int $contentId
531
     * @param \eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct $content
532
     *
533
     * @return \eZ\Publish\SPI\Persistence\Content\ContentInfo
534
     */
535
    public function updateMetadata($contentId, MetadataUpdateStruct $content)
536
    {
537
        $this->contentGateway->updateContent($contentId, $content);
538
        $this->updatePathIdentificationString($contentId, $content);
539
540
        return $this->loadContentInfo($contentId);
541
    }
542
543
    /**
544
     * Updates path identification string for locations of given $contentId if main language
545
     * is set in update struct.
546
     *
547
     * This is specific to the Legacy storage engine, as path identification string is deprecated.
548
     *
549
     * @param int $contentId
550
     * @param \eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct $content
551
     */
552
    protected function updatePathIdentificationString($contentId, MetadataUpdateStruct $content)
553
    {
554
        if (isset($content->mainLanguageId)) {
555
            $contentLocationsRows = $this->locationGateway->loadLocationDataByContent($contentId);
556
            foreach ($contentLocationsRows as $row) {
557
                $locationName = '';
558
                $urlAliasRows = $this->urlAliasGateway->loadLocationEntries(
559
                    $row['node_id'],
560
                    false,
561
                    $content->mainLanguageId
562
                );
563
                if (!empty($urlAliasRows)) {
564
                    $locationName = $urlAliasRows[0]['text'];
565
                }
566
                $this->locationGateway->updatePathIdentificationString(
567
                    $row['node_id'],
568
                    $row['parent_node_id'],
569
                    $this->slugConverter->convert(
570
                        $locationName,
571
                        'node_' . $row['node_id'],
572
                        'urlalias_compat'
573
                    )
574
                );
575
            }
576
        }
577
    }
578
579
    /**
580
     * Updates a content version, identified by $contentId and $versionNo.
581
     *
582
     * @param int $contentId
583
     * @param int $versionNo
584
     * @param \eZ\Publish\SPI\Persistence\Content\UpdateStruct $updateStruct
585
     *
586
     * @return \eZ\Publish\SPI\Persistence\Content
587
     */
588
    public function updateContent($contentId, $versionNo, UpdateStruct $updateStruct)
589
    {
590
        $content = $this->load($contentId, $versionNo);
591
        $this->contentGateway->updateVersion($contentId, $versionNo, $updateStruct);
592
        $contentType = $this->contentTypeHandler->load($content->versionInfo->contentInfo->contentTypeId);
593
        $this->fieldHandler->updateFields($content, $updateStruct, $contentType);
594
        foreach ($updateStruct->name as $language => $name) {
595
            $this->contentGateway->setName(
596
                $contentId,
597
                $versionNo,
598
                $name,
599
                $language
600
            );
601
        }
602
603
        return $this->load($contentId, $versionNo);
604
    }
605
606
    /**
607
     * Deletes all versions and fields, all locations (subtree), and all relations.
608
     *
609
     * Removes the relations, but not the related objects. All subtrees of the
610
     * assigned nodes of this content objects are removed (recursively).
611
     *
612
     * @param int $contentId
613
     *
614
     * @return bool
615
     */
616
    public function deleteContent($contentId)
617
    {
618
        $contentLocations = $this->contentGateway->getAllLocationIds($contentId);
619
        if (empty($contentLocations)) {
620
            $this->removeRawContent($contentId);
621
        } else {
622
            foreach ($contentLocations as $locationId) {
623
                $this->treeHandler->removeSubtree($locationId);
624
            }
625
        }
626
    }
627
628
    /**
629
     * Deletes raw content data.
630
     *
631
     * @param int $contentId
632
     */
633
    public function removeRawContent($contentId)
634
    {
635
        $this->treeHandler->removeRawContent($contentId);
636
    }
637
638
    /**
639
     * Deletes given version, its fields, node assignment, relations and names.
640
     *
641
     * Removes the relations, but not the related objects.
642
     *
643
     * @param int $contentId
644
     * @param int $versionNo
645
     *
646
     * @return bool
647
     */
648
    public function deleteVersion($contentId, $versionNo)
649
    {
650
        $versionInfo = $this->loadVersionInfo($contentId, $versionNo);
651
652
        $this->locationGateway->deleteNodeAssignment($contentId, $versionNo);
653
654
        $this->fieldHandler->deleteFields($contentId, $versionInfo);
655
656
        $this->contentGateway->deleteRelations($contentId, $versionNo);
657
        $this->contentGateway->deleteVersions($contentId, $versionNo);
658
        $this->contentGateway->deleteNames($contentId, $versionNo);
659
    }
660
661
    /**
662
     * Returns the versions for $contentId.
663
     *
664
     * Result is returned with oldest version first (sorted by created, alternatively version id if auto increment).
665
     *
666
     * @param int $contentId
667
     * @param mixed|null $status Optional argument to filter versions by status, like {@see VersionInfo::STATUS_ARCHIVED}.
668
     * @param int $limit Limit for items returned, -1 means none.
669
     *
670
     * @return \eZ\Publish\SPI\Persistence\Content\VersionInfo[]
671
     */
672
    public function listVersions($contentId, $status = null, $limit = -1)
673
    {
674
        return $this->treeHandler->listVersions($contentId, $status, $limit);
675
    }
676
677
    /**
678
     * Copy Content with Fields, Versions & Relations from $contentId in $version.
679
     *
680
     * {@inheritdoc}
681
     *
682
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException If content or version is not found
683
     *
684
     * @param mixed $contentId
685
     * @param mixed|null $versionNo Copy all versions if left null
686
     *
687
     * @return \eZ\Publish\SPI\Persistence\Content
688
     */
689
    public function copy($contentId, $versionNo = null)
690
    {
691
        $currentVersionNo = isset($versionNo) ?
692
            $versionNo :
693
            $this->loadContentInfo($contentId)->currentVersionNo;
694
695
        // Copy content in given version or current version
696
        $createStruct = $this->mapper->createCreateStructFromContent(
697
            $this->load($contentId, $currentVersionNo)
698
        );
699
        $content = $this->internalCreate($createStruct, $currentVersionNo);
700
701
        // If version was not passed also copy other versions
702
        if (!isset($versionNo)) {
703
            $contentType = $this->contentTypeHandler->load($createStruct->typeId);
704
705
            foreach ($this->listVersions($contentId) as $versionInfo) {
706
                if ($versionInfo->versionNo === $currentVersionNo) {
707
                    continue;
708
                }
709
710
                $versionContent = $this->load($contentId, $versionInfo->versionNo);
711
712
                $versionContent->versionInfo->contentInfo->id = $content->versionInfo->contentInfo->id;
713
                $versionContent->versionInfo->modificationDate = $createStruct->modified;
714
                $versionContent->versionInfo->creationDate = $createStruct->modified;
715
                $versionContent->versionInfo->id = $this->contentGateway->insertVersion(
716
                    $versionContent->versionInfo,
717
                    $versionContent->fields
718
                );
719
720
                $this->fieldHandler->createNewFields($versionContent, $contentType);
721
722
                // Create names
723 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...
724
                    $this->contentGateway->setName(
725
                        $content->versionInfo->contentInfo->id,
726
                        $versionInfo->versionNo,
727
                        $name,
728
                        $language
729
                    );
730
                }
731
            }
732
733
            // Batch copy relations for all versions
734
            $this->contentGateway->copyRelations($contentId, $content->versionInfo->contentInfo->id);
735
        } else {
736
            // Batch copy relations for published version
737
            $this->contentGateway->copyRelations($contentId, $content->versionInfo->contentInfo->id, $versionNo);
738
        }
739
740
        return $content;
741
    }
742
743
    /**
744
     * Creates a relation between $sourceContentId in $sourceContentVersionNo
745
     * and $destinationContentId with a specific $type.
746
     *
747
     * @todo Should the existence verifications happen here or is this supposed to be handled at a higher level?
748
     *
749
     * @param \eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct $createStruct
750
     *
751
     * @return \eZ\Publish\SPI\Persistence\Content\Relation
752
     */
753
    public function addRelation(RelationCreateStruct $createStruct)
754
    {
755
        $relation = $this->mapper->createRelationFromCreateStruct($createStruct);
756
757
        $relation->id = $this->contentGateway->insertRelation($createStruct);
758
759
        return $relation;
760
    }
761
762
    /**
763
     * Removes a relation by relation Id.
764
     *
765
     * @todo Should the existence verifications happen here or is this supposed to be handled at a higher level?
766
     *
767
     * @param mixed $relationId
768
     * @param int $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
769
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
770
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
771
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
772
     */
773
    public function removeRelation($relationId, $type)
774
    {
775
        $this->contentGateway->deleteRelation($relationId, $type);
776
    }
777
778
    /**
779
     * Loads relations from $sourceContentId. Optionally, loads only those with $type and $sourceContentVersionNo.
780
     *
781
     * @param mixed $sourceContentId Source Content ID
782
     * @param mixed|null $sourceContentVersionNo Source Content Version, null if not specified
783
     * @param int|null $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
784
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
785
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
786
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
787
     *
788
     * @return \eZ\Publish\SPI\Persistence\Content\Relation[]
789
     */
790
    public function loadRelations($sourceContentId, $sourceContentVersionNo = null, $type = null)
791
    {
792
        return $this->mapper->extractRelationsFromRows(
793
            $this->contentGateway->loadRelations($sourceContentId, $sourceContentVersionNo, $type)
794
        );
795
    }
796
797
    /**
798
     * Loads relations from $contentId. Optionally, loads only those with $type.
799
     *
800
     * Only loads relations against published versions.
801
     *
802
     * @param mixed $destinationContentId Destination Content ID
803
     * @param int|null $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
804
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
805
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
806
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
807
     *
808
     * @return \eZ\Publish\SPI\Persistence\Content\Relation[]
809
     */
810
    public function loadReverseRelations($destinationContentId, $type = null)
811
    {
812
        return $this->mapper->extractRelationsFromRows(
813
            $this->contentGateway->loadReverseRelations($destinationContentId, $type)
814
        );
815
    }
816
817
    /**
818
     * {@inheritdoc}
819
     */
820
    public function removeTranslationFromContent($contentId, $languageCode)
821
    {
822
        @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...
823
            __METHOD__ . ' is deprecated, use deleteTranslationFromContent instead',
824
            E_USER_DEPRECATED
825
        );
826
        $this->deleteTranslationFromContent($contentId, $languageCode);
827
    }
828
829
    /**
830
     * {@inheritdoc}
831
     */
832
    public function deleteTranslationFromContent($contentId, $languageCode)
833
    {
834
        $this->fieldHandler->deleteTranslationFromContentFields(
835
            $contentId,
836
            $this->listVersions($contentId),
837
            $languageCode
838
        );
839
        $this->contentGateway->deleteTranslationFromContent($contentId, $languageCode);
840
    }
841
842
    /**
843
     * {@inheritdoc}
844
     */
845
    public function deleteTranslationFromDraft($contentId, $versionNo, $languageCode)
846
    {
847
        $versionInfo = $this->loadVersionInfo($contentId, $versionNo);
848
849
        $this->fieldHandler->deleteTranslationFromVersionFields(
850
            $versionInfo,
851
            $languageCode
852
        );
853
        $this->contentGateway->deleteTranslationFromVersion(
854
            $contentId,
855
            $versionNo,
856
            $languageCode
857
        );
858
859
        // get all [languageCode => name] entries except the removed Translation
860
        $names = array_filter(
861
            $versionInfo->names,
862
            function ($lang) use ($languageCode) {
863
                return $lang !== $languageCode;
864
            },
865
            ARRAY_FILTER_USE_KEY
866
        );
867
        // set new Content name
868
        foreach ($names as $language => $name) {
869
            $this->contentGateway->setName(
870
                $contentId,
871
                $versionNo,
872
                $name,
873
                $language
874
            );
875
        }
876
877
        // reload entire Version w/o removed Translation
878
        return $this->load($contentId, $versionNo);
879
    }
880
}
881