Completed
Push — ezp_30827 ( 031a3c...efb07b )
by
unknown
13:58
created

Handler::loadContentInfoByRemoteId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 6
rs 10
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\Field;
14
use eZ\Publish\SPI\Persistence\Content\Handler as BaseContentHandler;
15
use eZ\Publish\SPI\Persistence\Content\Type\Handler as ContentTypeHandler;
16
use eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\SlugConverter;
17
use eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\Gateway as UrlAliasGateway;
18
use eZ\Publish\SPI\Persistence\Content;
19
use eZ\Publish\SPI\Persistence\Content\CreateStruct;
20
use eZ\Publish\SPI\Persistence\Content\UpdateStruct;
21
use eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct;
22
use eZ\Publish\SPI\Persistence\Content\VersionInfo;
23
use eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct as RelationCreateStruct;
24
use eZ\Publish\Core\Base\Exceptions\NotFoundException as NotFound;
25
use Psr\Log\LoggerInterface;
26
use Psr\Log\NullLogger;
27
28
/**
29
 * The Content Handler stores Content and ContentType objects.
30
 */
31
class Handler implements BaseContentHandler
32
{
33
    /**
34
     * Content gateway.
35
     *
36
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\Gateway
37
     */
38
    protected $contentGateway;
39
40
    /**
41
     * Location gateway.
42
     *
43
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\Location\Gateway
44
     */
45
    protected $locationGateway;
46
47
    /**
48
     * Mapper.
49
     *
50
     * @var Mapper
51
     */
52
    protected $mapper;
53
54
    /**
55
     * FieldHandler.
56
     *
57
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\FieldHandler
58
     */
59
    protected $fieldHandler;
60
61
    /**
62
     * URL slug converter.
63
     *
64
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\SlugConverter
65
     */
66
    protected $slugConverter;
67
68
    /**
69
     * UrlAlias gateway.
70
     *
71
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\Gateway
72
     */
73
    protected $urlAliasGateway;
74
75
    /**
76
     * ContentType handler.
77
     *
78
     * @var \eZ\Publish\SPI\Persistence\Content\Type\Handler
79
     */
80
    protected $contentTypeHandler;
81
82
    /**
83
     * Tree handler.
84
     *
85
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\TreeHandler
86
     */
87
    protected $treeHandler;
88
89
    /** @var \Psr\Log\LoggerInterface */
90
    private $logger;
91
92
    /**
93
     * Creates a new content handler.
94
     *
95
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\Gateway $contentGateway
96
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\Location\Gateway $locationGateway
97
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\Mapper $mapper
98
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\FieldHandler $fieldHandler
99
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\SlugConverter $slugConverter
100
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\UrlAlias\Gateway $urlAliasGateway
101
     * @param \eZ\Publish\SPI\Persistence\Content\Type\Handler $contentTypeHandler
102
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\TreeHandler $treeHandler
103
     * @param \Psr\Log\LoggerInterface|null $logger
104
     */
105
    public function __construct(
106
        Gateway $contentGateway,
107
        LocationGateway $locationGateway,
108
        Mapper $mapper,
109
        FieldHandler $fieldHandler,
110
        SlugConverter $slugConverter,
111
        UrlAliasGateway $urlAliasGateway,
112
        ContentTypeHandler $contentTypeHandler,
113
        TreeHandler $treeHandler,
114
        LoggerInterface $logger = null
115
    ) {
116
        $this->contentGateway = $contentGateway;
117
        $this->locationGateway = $locationGateway;
118
        $this->mapper = $mapper;
119
        $this->fieldHandler = $fieldHandler;
120
        $this->slugConverter = $slugConverter;
121
        $this->urlAliasGateway = $urlAliasGateway;
122
        $this->contentTypeHandler = $contentTypeHandler;
123
        $this->treeHandler = $treeHandler;
124
        $this->logger = null !== $logger ? $logger : new NullLogger();
125
    }
126
127
    /**
128
     * Creates a new Content entity in the storage engine.
129
     *
130
     * The values contained inside the $content will form the basis of stored
131
     * entity.
132
     *
133
     * Will contain always a complete list of fields.
134
     *
135
     * @param \eZ\Publish\SPI\Persistence\Content\CreateStruct $struct Content creation struct.
136
     *
137
     * @return \eZ\Publish\SPI\Persistence\Content Content value object
138
     */
139
    public function create(CreateStruct $struct)
140
    {
141
        return $this->internalCreate($struct);
142
    }
143
144
    /**
145
     * Creates a new Content entity in the storage engine.
146
     *
147
     * The values contained inside the $content will form the basis of stored
148
     * entity.
149
     *
150
     * Will contain always a complete list of fields.
151
     *
152
     * @param \eZ\Publish\SPI\Persistence\Content\CreateStruct $struct Content creation struct.
153
     * @param mixed $versionNo Used by self::copy() to maintain version numbers
154
     *
155
     * @return \eZ\Publish\SPI\Persistence\Content Content value object
156
     */
157
    protected function internalCreate(CreateStruct $struct, $versionNo = 1)
158
    {
159
        $content = new Content();
160
161
        $content->fields = $struct->fields;
162
        $content->versionInfo = $this->mapper->createVersionInfoFromCreateStruct($struct, $versionNo);
163
164
        $content->versionInfo->contentInfo->id = $this->contentGateway->insertContentObject($struct, $versionNo);
165
        $content->versionInfo->id = $this->contentGateway->insertVersion(
166
            $content->versionInfo,
167
            $struct->fields
168
        );
169
170
        $contentType = $this->contentTypeHandler->load($struct->typeId);
171
        $this->fieldHandler->createNewFields($content, $contentType);
172
173
        // Create node assignments
174
        foreach ($struct->locations as $location) {
175
            $location->contentId = $content->versionInfo->contentInfo->id;
176
            $location->contentVersion = $content->versionInfo->versionNo;
177
            $this->locationGateway->createNodeAssignment(
178
                $location,
179
                $location->parentId,
180
                LocationGateway::NODE_ASSIGNMENT_OP_CODE_CREATE
181
            );
182
        }
183
184
        // Create names
185
        foreach ($content->versionInfo->names as $language => $name) {
186
            $this->contentGateway->setName(
187
                $content->versionInfo->contentInfo->id,
188
                $content->versionInfo->versionNo,
189
                $name,
190
                $language
191
            );
192
        }
193
194
        return $content;
195
    }
196
197
    /**
198
     * Performs the publishing operations required to set the version identified by $updateStruct->versionNo and
199
     * $updateStruct->id as the published one.
200
     *
201
     * The publish procedure will:
202
     * - Create location nodes based on the node assignments
203
     * - Update the content object using the provided metadata update struct
204
     * - Update the node assignments
205
     * - Update location nodes of the content with the new published version
206
     * - Set content and version status to published
207
     *
208
     * @param int $contentId
209
     * @param int $versionNo
210
     * @param \eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct $metaDataUpdateStruct
211
     *
212
     * @return \eZ\Publish\SPI\Persistence\Content The published Content
213
     *
214
     * @throws \eZ\Publish\API\Repository\Exceptions\BadStateException
215
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
216
     */
217
    public function publish($contentId, $versionNo, MetadataUpdateStruct $metaDataUpdateStruct)
218
    {
219
        // Archive currently published version
220
        $versionInfo = $this->loadVersionInfo($contentId, $versionNo);
221
        if ($versionInfo->contentInfo->currentVersionNo != $versionNo) {
222
            $this->setStatus(
223
                $contentId,
224
                VersionInfo::STATUS_ARCHIVED,
225
                $versionInfo->contentInfo->currentVersionNo
226
            );
227
        }
228
229
        // Set always available name for the content
230
        $metaDataUpdateStruct->name = $versionInfo->names[$versionInfo->contentInfo->mainLanguageCode];
231
232
        $this->contentGateway->updateContent($contentId, $metaDataUpdateStruct, $versionInfo);
233
        $this->locationGateway->createLocationsFromNodeAssignments(
234
            $contentId,
235
            $versionNo
236
        );
237
238
        $this->locationGateway->updateLocationsContentVersionNo($contentId, $versionNo);
239
        $this->contentGateway->setPublishedStatus($contentId, $versionNo);
240
241
        return $this->load($contentId, $versionNo);
242
    }
243
244
    /**
245
     * Creates a new draft version from $contentId in $version.
246
     *
247
     * Copies all fields from $contentId in $srcVersion and creates a new
248
     * version of the referred Content from it.
249
     *
250
     * Note: When creating a new draft in the old admin interface there will
251
     * also be an entry in the `eznode_assignment` created for the draft. This
252
     * is ignored in this implementation.
253
     *
254
     * @param mixed $contentId
255
     * @param mixed $srcVersion
256
     * @param mixed $userId
257
     *
258
     * @return \eZ\Publish\SPI\Persistence\Content
259
     */
260
    public function createDraftFromVersion($contentId, $srcVersion, $userId)
261
    {
262
        $content = $this->load($contentId, $srcVersion);
263
264
        // Create new version
265
        $content->versionInfo = $this->mapper->createVersionInfoForContent(
266
            $content,
267
            $this->contentGateway->getLastVersionNumber($contentId) + 1,
268
            $userId
269
        );
270
        $content->versionInfo->id = $this->contentGateway->insertVersion(
271
            $content->versionInfo,
272
            $content->fields
273
        );
274
275
        // Clone fields from previous version and append them to the new one
276
        $this->fieldHandler->createExistingFieldsInNewVersion($content);
277
278
        // Create relations for new version
279
        $relations = $this->contentGateway->loadRelations($contentId, $srcVersion);
280
        foreach ($relations as $relation) {
281
            $this->contentGateway->insertRelation(
282
                new RelationCreateStruct(
283
                    [
284
                        'sourceContentId' => $contentId,
285
                        'sourceContentVersionNo' => $content->versionInfo->versionNo,
286
                        'sourceFieldDefinitionId' => $relation['ezcontentobject_link_contentclassattribute_id'],
287
                        'destinationContentId' => $relation['ezcontentobject_link_to_contentobject_id'],
288
                        'type' => (int)$relation['ezcontentobject_link_relation_type'],
289
                    ]
290
                )
291
            );
292
        }
293
294
        // Create content names for new version
295
        foreach ($content->versionInfo->names as $language => $name) {
296
            $this->contentGateway->setName(
297
                $contentId,
298
                $content->versionInfo->versionNo,
299
                $name,
300
                $language
301
            );
302
        }
303
304
        return $content;
305
    }
306
307
    /**
308
     * {@inheritdoc}
309
     */
310
    public function load($id, $version = null, array $translations = null)
311
    {
312
        $rows = $this->contentGateway->load($id, $version, $translations);
0 ignored issues
show
Bug introduced by
It seems like $translations defined by parameter $translations on line 310 can also be of type array; however, eZ\Publish\Core\Persiste...Content\Gateway::load() 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...
313
314
        if (empty($rows)) {
315
            throw new NotFound('content', "contentId: $id, versionNo: $version");
316
        }
317
318
        $contentObjects = $this->mapper->extractContentFromRows(
319
            $rows,
320
            $this->contentGateway->loadVersionedNameData([[
321
                'id' => $id,
322
                'version' => $rows[0]['ezcontentobject_version_version'],
323
            ]])
324
        );
325
        $content = $contentObjects[0];
326
        unset($rows, $contentObjects);
327
328
        $this->fieldHandler->loadExternalFieldData($content);
329
330
        return $content;
331
    }
332
333
    /**
334
     * {@inheritdoc}
335
     */
336
    public function loadContentList(array $contentIds, array $translations = null): array
337
    {
338
        $rawList = $this->contentGateway->loadContentList($contentIds, $translations);
0 ignored issues
show
Bug introduced by
It seems like $translations defined by parameter $translations on line 336 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...
339
        if (empty($rawList)) {
340
            return [];
341
        }
342
343
        $idVersionPairs = [];
344
        foreach ($rawList as $row) {
345
            // As there is only one version per id, set id as key to avoid duplicates
346
            $idVersionPairs[$row['ezcontentobject_id']] = [
347
                'id' => $row['ezcontentobject_id'],
348
                'version' => $row['ezcontentobject_version_version'],
349
            ];
350
        }
351
352
        // group name data per Content Id
353
        $nameData = $this->contentGateway->loadVersionedNameData(array_values($idVersionPairs));
354
        $contentItemNameData = [];
355
        foreach ($nameData as $nameDataRow) {
356
            $contentId = $nameDataRow['ezcontentobject_name_contentobject_id'];
357
            $contentItemNameData[$contentId][] = $nameDataRow;
358
        }
359
360
        // group rows per Content Id be able to ignore Content items with erroneous data
361
        $contentItemsRows = [];
362
        foreach ($rawList as $row) {
363
            $contentId = $row['ezcontentobject_id'];
364
            $contentItemsRows[$contentId][] = $row;
365
        }
366
        unset($rawList, $idVersionPairs);
367
368
        // try to extract Content from each Content data
369
        $contentItems = [];
370
        foreach ($contentItemsRows as $contentId => $contentItemsRow) {
371
            try {
372
                $contentList = $this->mapper->extractContentFromRows(
373
                    $contentItemsRow,
374
                    $contentItemNameData[$contentId]
375
                );
376
                $contentItems[$contentId] = $contentList[0];
377
            } catch (Exception $e) {
378
                $this->logger->warning(
379
                    sprintf(
380
                        '%s: Content %d not loaded: %s',
381
                        __METHOD__,
382
                        $contentId,
383
                        $e->getMessage()
384
                    )
385
                );
386
            }
387
        }
388
389
        // try to load External Storage data for each Content, ignore Content items for which it failed
390
        foreach ($contentItems as $contentId => $content) {
391
            try {
392
                $this->fieldHandler->loadExternalFieldData($content);
393
            } catch (Exception $e) {
394
                unset($contentItems[$contentId]);
395
                $this->logger->warning(
396
                    sprintf(
397
                        '%s: Content %d not loaded: %s',
398
                        __METHOD__,
399
                        $contentId,
400
                        $e->getMessage()
401
                    )
402
                );
403
            }
404
        }
405
406
        return $contentItems;
407
    }
408
409
    /**
410
     * Returns the metadata object for a content identified by $contentId.
411
     *
412
     * @param int|string $contentId
413
     *
414
     * @return \eZ\Publish\SPI\Persistence\Content\ContentInfo
415
     */
416
    public function loadContentInfo($contentId)
417
    {
418
        return $this->treeHandler->loadContentInfo($contentId);
419
    }
420
421
    public function loadContentInfoList(array $contentIds)
422
    {
423
        $list = $this->mapper->extractContentInfoFromRows(
424
            $this->contentGateway->loadContentInfoList($contentIds)
425
        );
426
427
        $listByContentId = [];
428
        foreach ($list as $item) {
429
            $listByContentId[$item->id] = $item;
430
        }
431
432
        return $listByContentId;
433
    }
434
435
    /**
436
     * Returns the metadata object for a content identified by $remoteId.
437
     *
438
     * @param mixed $remoteId
439
     *
440
     * @return \eZ\Publish\SPI\Persistence\Content\ContentInfo
441
     */
442
    public function loadContentInfoByRemoteId($remoteId)
443
    {
444
        return $this->mapper->extractContentInfoFromRow(
445
            $this->contentGateway->loadContentInfoByRemoteId($remoteId)
446
        );
447
    }
448
449
    /**
450
     * {@inheritdoc}
451
     */
452
    public function loadVersionInfo($contentId, $versionNo = null)
453
    {
454
        $rows = $this->contentGateway->loadVersionInfo($contentId, $versionNo);
455
        if (empty($rows)) {
456
            throw new NotFound('content', $contentId);
457
        }
458
459
        $versionInfo = $this->mapper->extractVersionInfoListFromRows(
460
            $rows,
461
            $this->contentGateway->loadVersionedNameData([['id' => $contentId, 'version' => $rows[0]['ezcontentobject_version_version']]])
462
        );
463
464
        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 464 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...
465
    }
466
467
    public function countDraftsForUser(int $userId): int
468
    {
469
        return $this->contentGateway->countVersionsForUser($userId, VersionInfo::STATUS_DRAFT);
470
    }
471
472
    /**
473
     * Returns all versions with draft status created by the given $userId.
474
     *
475
     * @param int $userId
476
     *
477
     * @return \eZ\Publish\SPI\Persistence\Content\VersionInfo[]
478
     */
479
    public function loadDraftsForUser($userId)
480
    {
481
        $rows = $this->contentGateway->listVersionsForUser($userId, VersionInfo::STATUS_DRAFT);
482
        if (empty($rows)) {
483
            return [];
484
        }
485
486
        $idVersionPairs = array_map(
487
            function ($row) {
488
                return [
489
                    'id' => $row['ezcontentobject_version_contentobject_id'],
490
                    'version' => $row['ezcontentobject_version_version'],
491
                ];
492
            },
493
            $rows
494
        );
495
        $nameRows = $this->contentGateway->loadVersionedNameData($idVersionPairs);
496
497
        return $this->mapper->extractVersionInfoListFromRows($rows, $nameRows);
498
    }
499
500
    public function loadDraftListForUser(int $userId, int $offset = 0, int $limit = -1): array
501
    {
502
        $rows = $this->contentGateway->loadVersionsForUser($userId, VersionInfo::STATUS_DRAFT, $offset, $limit);
503
        if (empty($rows)) {
504
            return [];
505
        }
506
507
        $idVersionPairs = array_map(
508
            static function (array $row): array {
509
                return [
510
                    'id' => $row['ezcontentobject_version_contentobject_id'],
511
                    'version' => $row['ezcontentobject_version_version'],
512
                ];
513
            },
514
            $rows
515
        );
516
        $nameRows = $this->contentGateway->loadVersionedNameData($idVersionPairs);
517
518
        return $this->mapper->extractVersionInfoListFromRows($rows, $nameRows);
519
    }
520
521
    /**
522
     * Sets the status of object identified by $contentId and $version to $status.
523
     *
524
     * The $status can be one of VersionInfo::STATUS_DRAFT, VersionInfo::STATUS_PUBLISHED, VersionInfo::STATUS_ARCHIVED
525
     * When status is set to VersionInfo::STATUS_PUBLISHED content status is updated to ContentInfo::STATUS_PUBLISHED
526
     *
527
     * @param int $contentId
528
     * @param int $status
529
     * @param int $version
530
     *
531
     * @return bool
532
     */
533
    public function setStatus($contentId, $status, $version)
534
    {
535
        return $this->contentGateway->setStatus($contentId, $version, $status);
536
    }
537
538
    /**
539
     * Updates a content object meta data, identified by $contentId.
540
     *
541
     * @param int $contentId
542
     * @param \eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct $content
543
     *
544
     * @return \eZ\Publish\SPI\Persistence\Content\ContentInfo
545
     */
546
    public function updateMetadata($contentId, MetadataUpdateStruct $content)
547
    {
548
        $this->contentGateway->updateContent($contentId, $content);
549
        $this->updatePathIdentificationString($contentId, $content);
550
551
        return $this->loadContentInfo($contentId);
552
    }
553
554
    /**
555
     * Updates path identification string for locations of given $contentId if main language
556
     * is set in update struct.
557
     *
558
     * This is specific to the Legacy storage engine, as path identification string is deprecated.
559
     *
560
     * @param int $contentId
561
     * @param \eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct $content
562
     */
563
    protected function updatePathIdentificationString($contentId, MetadataUpdateStruct $content)
564
    {
565
        if (isset($content->mainLanguageId)) {
566
            $contentLocationsRows = $this->locationGateway->loadLocationDataByContent($contentId);
567
            foreach ($contentLocationsRows as $row) {
568
                $locationName = '';
569
                $urlAliasRows = $this->urlAliasGateway->loadLocationEntries(
570
                    $row['node_id'],
571
                    false,
572
                    $content->mainLanguageId
573
                );
574
                if (!empty($urlAliasRows)) {
575
                    $locationName = $urlAliasRows[0]['text'];
576
                }
577
                $this->locationGateway->updatePathIdentificationString(
578
                    $row['node_id'],
579
                    $row['parent_node_id'],
580
                    $this->slugConverter->convert(
581
                        $locationName,
582
                        'node_' . $row['node_id'],
583
                        'urlalias_compat'
584
                    )
585
                );
586
            }
587
        }
588
    }
589
590
    /**
591
     * Updates a content version, identified by $contentId and $versionNo.
592
     *
593
     * @param int $contentId
594
     * @param int $versionNo
595
     * @param \eZ\Publish\SPI\Persistence\Content\UpdateStruct $updateStruct
596
     *
597
     * @return \eZ\Publish\SPI\Persistence\Content
598
     */
599
    public function updateContent($contentId, $versionNo, UpdateStruct $updateStruct)
600
    {
601
        $content = $this->load($contentId, $versionNo);
602
        $this->contentGateway->updateVersion($contentId, $versionNo, $updateStruct);
603
        $contentType = $this->contentTypeHandler->load($content->versionInfo->contentInfo->contentTypeId);
604
        $this->fieldHandler->updateFields($content, $updateStruct, $contentType);
605
        foreach ($updateStruct->name as $language => $name) {
606
            $this->contentGateway->setName(
607
                $contentId,
608
                $versionNo,
609
                $name,
610
                $language
611
            );
612
        }
613
614
        return $this->load($contentId, $versionNo);
615
    }
616
617
    /**
618
     * Deletes all versions and fields, all locations (subtree), and all relations.
619
     *
620
     * Removes the relations, but not the related objects. All subtrees of the
621
     * assigned nodes of this content objects are removed (recursively).
622
     *
623
     * @param int $contentId
624
     *
625
     * @return bool
626
     */
627
    public function deleteContent($contentId)
628
    {
629
        $contentLocations = $this->contentGateway->getAllLocationIds($contentId);
630
        if (empty($contentLocations)) {
631
            $this->removeRawContent($contentId);
632
        } else {
633
            foreach ($contentLocations as $locationId) {
634
                $this->treeHandler->removeSubtree($locationId);
635
            }
636
        }
637
    }
638
639
    /**
640
     * Deletes raw content data.
641
     *
642
     * @param int $contentId
643
     */
644
    public function removeRawContent($contentId)
645
    {
646
        $this->treeHandler->removeRawContent($contentId);
647
    }
648
649
    /**
650
     * Deletes given version, its fields, node assignment, relations and names.
651
     *
652
     * Removes the relations, but not the related objects.
653
     *
654
     * @param int $contentId
655
     * @param int $versionNo
656
     *
657
     * @return bool
658
     */
659
    public function deleteVersion($contentId, $versionNo)
660
    {
661
        $versionInfo = $this->loadVersionInfo($contentId, $versionNo);
662
663
        $this->locationGateway->deleteNodeAssignment($contentId, $versionNo);
664
665
        $this->fieldHandler->deleteFields($contentId, $versionInfo);
666
667
        $this->contentGateway->deleteRelations($contentId, $versionNo);
668
        $this->contentGateway->deleteVersions($contentId, $versionNo);
669
        $this->contentGateway->deleteNames($contentId, $versionNo);
670
    }
671
672
    /**
673
     * Returns the versions for $contentId.
674
     *
675
     * Result is returned with oldest version first (sorted by created, alternatively version id if auto increment).
676
     *
677
     * @param int $contentId
678
     * @param mixed|null $status Optional argument to filter versions by status, like {@see VersionInfo::STATUS_ARCHIVED}.
679
     * @param int $limit Limit for items returned, -1 means none.
680
     *
681
     * @return \eZ\Publish\SPI\Persistence\Content\VersionInfo[]
682
     */
683
    public function listVersions($contentId, $status = null, $limit = -1)
684
    {
685
        return $this->treeHandler->listVersions($contentId, $status, $limit);
686
    }
687
688
    /**
689
     * Copy Content with Fields, Versions & Relations from $contentId in $version.
690
     *
691
     * {@inheritdoc}
692
     *
693
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException If content or version is not found
694
     *
695
     * @param mixed $contentId
696
     * @param mixed|null $versionNo Copy all versions if left null
697
     * @param int|null $newOwnerId
698
     *
699
     * @return \eZ\Publish\SPI\Persistence\Content
700
     */
701
    public function copy($contentId, $versionNo = null, $newOwnerId = null)
702
    {
703
        $currentVersionNo = isset($versionNo) ?
704
            $versionNo :
705
            $this->loadContentInfo($contentId)->currentVersionNo;
706
707
        // Copy content in given version or current version
708
        $createStruct = $this->mapper->createCreateStructFromContent(
709
            $this->load($contentId, $currentVersionNo)
710
        );
711
        if ($newOwnerId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $newOwnerId of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
712
            $createStruct->ownerId = $newOwnerId;
713
        }
714
        $content = $this->internalCreate($createStruct, $currentVersionNo);
715
716
        // If version was not passed also copy other versions
717
        if (!isset($versionNo)) {
718
            $contentType = $this->contentTypeHandler->load($createStruct->typeId);
719
720
            foreach ($this->listVersions($contentId) as $versionInfo) {
721
                if ($versionInfo->versionNo === $currentVersionNo) {
722
                    continue;
723
                }
724
725
                $versionContent = $this->load($contentId, $versionInfo->versionNo);
726
727
                $versionContent->versionInfo->contentInfo->id = $content->versionInfo->contentInfo->id;
728
                $versionContent->versionInfo->modificationDate = $createStruct->modified;
729
                $versionContent->versionInfo->creationDate = $createStruct->modified;
730
                $versionContent->versionInfo->id = $this->contentGateway->insertVersion(
731
                    $versionContent->versionInfo,
732
                    $versionContent->fields
733
                );
734
735
                $this->fieldHandler->createNewFields($versionContent, $contentType);
736
737
                // Create names
738
                foreach ($versionContent->versionInfo->names as $language => $name) {
739
                    $this->contentGateway->setName(
740
                        $content->versionInfo->contentInfo->id,
741
                        $versionInfo->versionNo,
742
                        $name,
743
                        $language
744
                    );
745
                }
746
            }
747
748
            // Batch copy relations for all versions
749
            $this->contentGateway->copyRelations($contentId, $content->versionInfo->contentInfo->id);
750
        } else {
751
            // Batch copy relations for published version
752
            $this->contentGateway->copyRelations($contentId, $content->versionInfo->contentInfo->id, $versionNo);
753
        }
754
755
        return $content;
756
    }
757
758
    /**
759
     * Creates a relation between $sourceContentId in $sourceContentVersionNo
760
     * and $destinationContentId with a specific $type.
761
     *
762
     * @todo Should the existence verifications happen here or is this supposed to be handled at a higher level?
763
     *
764
     * @param \eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct $createStruct
765
     *
766
     * @return \eZ\Publish\SPI\Persistence\Content\Relation
767
     */
768
    public function addRelation(RelationCreateStruct $createStruct)
769
    {
770
        $relation = $this->mapper->createRelationFromCreateStruct($createStruct);
771
772
        $relation->id = $this->contentGateway->insertRelation($createStruct);
773
774
        return $relation;
775
    }
776
777
    /**
778
     * Removes a relation by relation Id.
779
     *
780
     * @todo Should the existence verifications happen here or is this supposed to be handled at a higher level?
781
     *
782
     * @param mixed $relationId
783
     * @param int $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
    public function removeRelation($relationId, $type)
789
    {
790
        $this->contentGateway->deleteRelation($relationId, $type);
791
    }
792
793
    /**
794
     * Loads relations from $sourceContentId. Optionally, loads only those with $type and $sourceContentVersionNo.
795
     *
796
     * @param mixed $sourceContentId Source Content ID
797
     * @param mixed|null $sourceContentVersionNo Source Content Version, null if not specified
798
     * @param int|null $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
799
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
800
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
801
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
802
     *
803
     * @return \eZ\Publish\SPI\Persistence\Content\Relation[]
804
     */
805
    public function loadRelations($sourceContentId, $sourceContentVersionNo = null, $type = null)
806
    {
807
        return $this->mapper->extractRelationsFromRows(
808
            $this->contentGateway->loadRelations($sourceContentId, $sourceContentVersionNo, $type)
809
        );
810
    }
811
812
    /**
813
     * {@inheritdoc}
814
     */
815
    public function countReverseRelations(int $destinationContentId, ?int $type = null): int
816
    {
817
        return $this->contentGateway->countReverseRelations($destinationContentId, $type);
818
    }
819
820
    /**
821
     * Loads relations from $contentId. Optionally, loads only those with $type.
822
     *
823
     * Only loads relations against published versions.
824
     *
825
     * @param mixed $destinationContentId Destination Content ID
826
     * @param int|null $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
827
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
828
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
829
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
830
     *
831
     * @return \eZ\Publish\SPI\Persistence\Content\Relation[]
832
     */
833
    public function loadReverseRelations($destinationContentId, $type = null)
834
    {
835
        return $this->mapper->extractRelationsFromRows(
836
            $this->contentGateway->loadReverseRelations($destinationContentId, $type)
837
        );
838
    }
839
840
    /**
841
     * {@inheritdoc}
842
     */
843
    public function loadReverseRelationList(
844
        int $destinationContentId,
845
        int $offset = 0,
846
        int $limit = -1,
847
        ?int $type = null
848
    ): array {
849
        return $this->mapper->extractRelationsFromRows(
850
            $this->contentGateway->listReverseRelations($destinationContentId, $offset, $limit, $type)
851
        );
852
    }
853
854
    /**
855
     * {@inheritdoc}
856
     */
857
    public function removeTranslationFromContent($contentId, $languageCode)
858
    {
859
        @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...
860
            __METHOD__ . ' is deprecated, use deleteTranslationFromContent instead',
861
            E_USER_DEPRECATED
862
        );
863
        $this->deleteTranslationFromContent($contentId, $languageCode);
864
    }
865
866
    /**
867
     * {@inheritdoc}
868
     */
869
    public function deleteTranslationFromContent($contentId, $languageCode)
870
    {
871
        $this->fieldHandler->deleteTranslationFromContentFields(
872
            $contentId,
873
            $this->listVersions($contentId),
874
            $languageCode
875
        );
876
        $this->contentGateway->deleteTranslationFromContent($contentId, $languageCode);
877
    }
878
879
    /**
880
     * {@inheritdoc}
881
     */
882
    public function deleteTranslationFromDraft($contentId, $versionNo, $languageCode)
883
    {
884
        $versionInfo = $this->loadVersionInfo($contentId, $versionNo);
885
886
        $this->fieldHandler->deleteTranslationFromVersionFields(
887
            $versionInfo,
888
            $languageCode
889
        );
890
        $this->contentGateway->deleteTranslationFromVersion(
891
            $contentId,
892
            $versionNo,
893
            $languageCode
894
        );
895
896
        // get all [languageCode => name] entries except the removed Translation
897
        $names = array_filter(
898
            $versionInfo->names,
899
            function ($lang) use ($languageCode) {
900
                return $lang !== $languageCode;
901
            },
902
            ARRAY_FILTER_USE_KEY
903
        );
904
        // set new Content name
905
        foreach ($names as $language => $name) {
906
            $this->contentGateway->setName(
907
                $contentId,
908
                $versionNo,
909
                $name,
910
                $language
911
            );
912
        }
913
914
        // reload entire Version w/o removed Translation
915
        return $this->load($contentId, $versionNo);
916
    }
917
}
918