Completed
Push — master ( 2dca3b...5a27f3 )
by
unknown
16:48 queued 02:47
created

Handler::loadDraftListForUser()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20

Duplication

Lines 20
Ratio 100 %

Importance

Changes 0
Metric Value
dl 20
loc 20
c 0
b 0
f 0
cc 2
nc 2
nop 3
rs 9.6
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 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...
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
    public function publish($contentId, $versionNo, MetadataUpdateStruct $metaDataUpdateStruct)
215
    {
216
        // Archive currently published version
217
        $versionInfo = $this->loadVersionInfo($contentId, $versionNo);
218
        if ($versionInfo->contentInfo->currentVersionNo != $versionNo) {
219
            $this->setStatus(
220
                $contentId,
221
                VersionInfo::STATUS_ARCHIVED,
222
                $versionInfo->contentInfo->currentVersionNo
223
            );
224
        }
225
226
        // Set always available name for the content
227
        $metaDataUpdateStruct->name = $versionInfo->names[$versionInfo->contentInfo->mainLanguageCode];
228
229
        $this->contentGateway->updateContent($contentId, $metaDataUpdateStruct, $versionInfo);
230
        $this->locationGateway->createLocationsFromNodeAssignments(
231
            $contentId,
232
            $versionNo
233
        );
234
235
        $this->locationGateway->updateLocationsContentVersionNo($contentId, $versionNo);
236
        $this->setStatus($contentId, VersionInfo::STATUS_PUBLISHED, $versionNo);
237
238
        return $this->load($contentId, $versionNo);
239
    }
240
241
    /**
242
     * Creates a new draft version from $contentId in $version.
243
     *
244
     * Copies all fields from $contentId in $srcVersion and creates a new
245
     * version of the referred Content from it.
246
     *
247
     * Note: When creating a new draft in the old admin interface there will
248
     * also be an entry in the `eznode_assignment` created for the draft. This
249
     * is ignored in this implementation.
250
     *
251
     * @param mixed $contentId
252
     * @param mixed $srcVersion
253
     * @param mixed $userId
254
     *
255
     * @return \eZ\Publish\SPI\Persistence\Content
256
     */
257
    public function createDraftFromVersion($contentId, $srcVersion, $userId)
258
    {
259
        $content = $this->load($contentId, $srcVersion);
260
261
        // Create new version
262
        $content->versionInfo = $this->mapper->createVersionInfoForContent(
263
            $content,
264
            $this->contentGateway->getLastVersionNumber($contentId) + 1,
265
            $userId
266
        );
267
        $content->versionInfo->id = $this->contentGateway->insertVersion(
268
            $content->versionInfo,
269
            $content->fields
270
        );
271
272
        // Clone fields from previous version and append them to the new one
273
        $this->fieldHandler->createExistingFieldsInNewVersion($content);
274
275
        // Create relations for new version
276
        $relations = $this->contentGateway->loadRelations($contentId, $srcVersion);
277
        foreach ($relations as $relation) {
278
            $this->contentGateway->insertRelation(
279
                new RelationCreateStruct(
280
                    [
281
                        'sourceContentId' => $contentId,
282
                        'sourceContentVersionNo' => $content->versionInfo->versionNo,
283
                        'sourceFieldDefinitionId' => $relation['ezcontentobject_link_contentclassattribute_id'],
284
                        'destinationContentId' => $relation['ezcontentobject_link_to_contentobject_id'],
285
                        'type' => (int)$relation['ezcontentobject_link_relation_type'],
286
                    ]
287
                )
288
            );
289
        }
290
291
        // Create content names for new version
292
        foreach ($content->versionInfo->names as $language => $name) {
293
            $this->contentGateway->setName(
294
                $contentId,
295
                $content->versionInfo->versionNo,
296
                $name,
297
                $language
298
            );
299
        }
300
301
        return $content;
302
    }
303
304
    /**
305
     * {@inheritdoc}
306
     */
307
    public function load($id, $version = null, array $translations = null)
308
    {
309
        $rows = $this->contentGateway->load($id, $version, $translations);
0 ignored issues
show
Bug introduced by
It seems like $translations defined by parameter $translations on line 307 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...
310
311
        if (empty($rows)) {
312
            throw new NotFound('content', "contentId: $id, versionNo: $version");
313
        }
314
315
        $contentObjects = $this->mapper->extractContentFromRows(
316
            $rows,
317
            $this->contentGateway->loadVersionedNameData([[
318
                'id' => $id,
319
                'version' => $rows[0]['ezcontentobject_version_version'],
320
            ]])
321
        );
322
        $content = $contentObjects[0];
323
        unset($rows, $contentObjects);
324
325
        $this->fieldHandler->loadExternalFieldData($content);
326
327
        return $content;
328
    }
329
330
    /**
331
     * {@inheritdoc}
332
     */
333
    public function loadContentList(array $contentIds, array $translations = null): array
334
    {
335
        $rawList = $this->contentGateway->loadContentList($contentIds, $translations);
0 ignored issues
show
Bug introduced by
It seems like $translations defined by parameter $translations on line 333 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...
336
        if (empty($rawList)) {
337
            return [];
338
        }
339
340
        $idVersionPairs = [];
341
        foreach ($rawList as $row) {
342
            // As there is only one version per id, set id as key to avoid duplicates
343
            $idVersionPairs[$row['ezcontentobject_id']] = [
344
                'id' => $row['ezcontentobject_id'],
345
                'version' => $row['ezcontentobject_version_version'],
346
            ];
347
        }
348
349
        // group name data per Content Id
350
        $nameData = $this->contentGateway->loadVersionedNameData(array_values($idVersionPairs));
351
        $contentItemNameData = [];
352
        foreach ($nameData as $nameDataRow) {
353
            $contentId = $nameDataRow['ezcontentobject_name_contentobject_id'];
354
            $contentItemNameData[$contentId][] = $nameDataRow;
355
        }
356
357
        // group rows per Content Id be able to ignore Content items with erroneous data
358
        $contentItemsRows = [];
359
        foreach ($rawList as $row) {
360
            $contentId = $row['ezcontentobject_id'];
361
            $contentItemsRows[$contentId][] = $row;
362
        }
363
        unset($rawList, $idVersionPairs);
364
365
        // try to extract Content from each Content data
366
        $contentItems = [];
367
        foreach ($contentItemsRows as $contentId => $contentItemsRow) {
368
            try {
369
                $contentList = $this->mapper->extractContentFromRows(
370
                    $contentItemsRow,
371
                    $contentItemNameData[$contentId]
372
                );
373
                $contentItems[$contentId] = $contentList[0];
374
            } catch (Exception $e) {
375
                $this->logger->warning(
376
                    sprintf(
377
                        '%s: Content %d not loaded: %s',
378
                        __METHOD__,
379
                        $contentId,
380
                        $e->getMessage()
381
                    )
382
                );
383
            }
384
        }
385
386
        // try to load External Storage data for each Content, ignore Content items for which it failed
387
        foreach ($contentItems as $contentId => $content) {
388
            try {
389
                $this->fieldHandler->loadExternalFieldData($content);
390
            } catch (Exception $e) {
391
                unset($contentItems[$contentId]);
392
                $this->logger->warning(
393
                    sprintf(
394
                        '%s: Content %d not loaded: %s',
395
                        __METHOD__,
396
                        $contentId,
397
                        $e->getMessage()
398
                    )
399
                );
400
            }
401
        }
402
403
        return $contentItems;
404
    }
405
406
    /**
407
     * Returns the metadata object for a content identified by $contentId.
408
     *
409
     * @param int|string $contentId
410
     *
411
     * @return \eZ\Publish\SPI\Persistence\Content\ContentInfo
412
     */
413
    public function loadContentInfo($contentId)
414
    {
415
        return $this->treeHandler->loadContentInfo($contentId);
416
    }
417
418
    public function loadContentInfoList(array $contentIds)
419
    {
420
        $list = $this->mapper->extractContentInfoFromRows(
421
            $this->contentGateway->loadContentInfoList($contentIds)
422
        );
423
424
        $listByContentId = [];
425
        foreach ($list as $item) {
426
            $listByContentId[$item->id] = $item;
427
        }
428
429
        return $listByContentId;
430
    }
431
432
    /**
433
     * Returns the metadata object for a content identified by $remoteId.
434
     *
435
     * @param mixed $remoteId
436
     *
437
     * @return \eZ\Publish\SPI\Persistence\Content\ContentInfo
438
     */
439
    public function loadContentInfoByRemoteId($remoteId)
440
    {
441
        return $this->mapper->extractContentInfoFromRow(
442
            $this->contentGateway->loadContentInfoByRemoteId($remoteId)
443
        );
444
    }
445
446
    /**
447
     * {@inheritdoc}
448
     */
449
    public function loadVersionInfo($contentId, $versionNo = null)
450
    {
451
        $rows = $this->contentGateway->loadVersionInfo($contentId, $versionNo);
452
        if (empty($rows)) {
453
            throw new NotFound('content', $contentId);
454
        }
455
456
        $versionInfo = $this->mapper->extractVersionInfoListFromRows(
457
            $rows,
458
            $this->contentGateway->loadVersionedNameData([['id' => $contentId, 'version' => $rows[0]['ezcontentobject_version_version']]])
459
        );
460
461
        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 461 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...
462
    }
463
464
    public function countDraftsForUser(int $userId): int
465
    {
466
        return $this->contentGateway->countVersionsForUser($userId, VersionInfo::STATUS_DRAFT);
467
    }
468
469
    /**
470
     * Returns all versions with draft status created by the given $userId.
471
     *
472
     * @param int $userId
473
     *
474
     * @return \eZ\Publish\SPI\Persistence\Content\VersionInfo[]
475
     */
476 View Code Duplication
    public function loadDraftsForUser($userId)
477
    {
478
        $rows = $this->contentGateway->listVersionsForUser($userId, VersionInfo::STATUS_DRAFT);
479
        if (empty($rows)) {
480
            return [];
481
        }
482
483
        $idVersionPairs = array_map(
484
            function ($row) {
485
                return [
486
                    'id' => $row['ezcontentobject_version_contentobject_id'],
487
                    'version' => $row['ezcontentobject_version_version'],
488
                ];
489
            },
490
            $rows
491
        );
492
        $nameRows = $this->contentGateway->loadVersionedNameData($idVersionPairs);
493
494
        return $this->mapper->extractVersionInfoListFromRows($rows, $nameRows);
495
    }
496
497 View Code Duplication
    public function loadDraftListForUser(int $userId, int $offset = 0, int $limit = -1): array
498
    {
499
        $rows = $this->contentGateway->loadVersionsForUser($userId, VersionInfo::STATUS_DRAFT, $offset, $limit);
500
        if (empty($rows)) {
501
            return [];
502
        }
503
504
        $idVersionPairs = array_map(
505
            static function (array $row): array {
506
                return [
507
                    'id' => $row['ezcontentobject_version_contentobject_id'],
508
                    'version' => $row['ezcontentobject_version_version'],
509
                ];
510
            },
511
            $rows
512
        );
513
        $nameRows = $this->contentGateway->loadVersionedNameData($idVersionPairs);
514
515
        return $this->mapper->extractVersionInfoListFromRows($rows, $nameRows);
516
    }
517
518
    /**
519
     * Sets the status of object identified by $contentId and $version to $status.
520
     *
521
     * The $status can be one of VersionInfo::STATUS_DRAFT, VersionInfo::STATUS_PUBLISHED, VersionInfo::STATUS_ARCHIVED
522
     * When status is set to VersionInfo::STATUS_PUBLISHED content status is updated to ContentInfo::STATUS_PUBLISHED
523
     *
524
     * @param int $contentId
525
     * @param int $status
526
     * @param int $version
527
     *
528
     * @return bool
529
     */
530
    public function setStatus($contentId, $status, $version)
531
    {
532
        return $this->contentGateway->setStatus($contentId, $version, $status);
533
    }
534
535
    /**
536
     * Updates a content object meta data, identified by $contentId.
537
     *
538
     * @param int $contentId
539
     * @param \eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct $content
540
     *
541
     * @return \eZ\Publish\SPI\Persistence\Content\ContentInfo
542
     */
543
    public function updateMetadata($contentId, MetadataUpdateStruct $content)
544
    {
545
        $this->contentGateway->updateContent($contentId, $content);
546
        $this->updatePathIdentificationString($contentId, $content);
547
548
        return $this->loadContentInfo($contentId);
549
    }
550
551
    /**
552
     * Updates path identification string for locations of given $contentId if main language
553
     * is set in update struct.
554
     *
555
     * This is specific to the Legacy storage engine, as path identification string is deprecated.
556
     *
557
     * @param int $contentId
558
     * @param \eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct $content
559
     */
560
    protected function updatePathIdentificationString($contentId, MetadataUpdateStruct $content)
561
    {
562
        if (isset($content->mainLanguageId)) {
563
            $contentLocationsRows = $this->locationGateway->loadLocationDataByContent($contentId);
564
            foreach ($contentLocationsRows as $row) {
565
                $locationName = '';
566
                $urlAliasRows = $this->urlAliasGateway->loadLocationEntries(
567
                    $row['node_id'],
568
                    false,
569
                    $content->mainLanguageId
570
                );
571
                if (!empty($urlAliasRows)) {
572
                    $locationName = $urlAliasRows[0]['text'];
573
                }
574
                $this->locationGateway->updatePathIdentificationString(
575
                    $row['node_id'],
576
                    $row['parent_node_id'],
577
                    $this->slugConverter->convert(
578
                        $locationName,
579
                        'node_' . $row['node_id'],
580
                        'urlalias_compat'
581
                    )
582
                );
583
            }
584
        }
585
    }
586
587
    /**
588
     * Updates a content version, identified by $contentId and $versionNo.
589
     *
590
     * @param int $contentId
591
     * @param int $versionNo
592
     * @param \eZ\Publish\SPI\Persistence\Content\UpdateStruct $updateStruct
593
     *
594
     * @return \eZ\Publish\SPI\Persistence\Content
595
     */
596
    public function updateContent($contentId, $versionNo, UpdateStruct $updateStruct)
597
    {
598
        $content = $this->load($contentId, $versionNo);
599
        $this->contentGateway->updateVersion($contentId, $versionNo, $updateStruct);
600
        $contentType = $this->contentTypeHandler->load($content->versionInfo->contentInfo->contentTypeId);
601
        $this->fieldHandler->updateFields($content, $updateStruct, $contentType);
602
        foreach ($updateStruct->name as $language => $name) {
603
            $this->contentGateway->setName(
604
                $contentId,
605
                $versionNo,
606
                $name,
607
                $language
608
            );
609
        }
610
611
        return $this->load($contentId, $versionNo);
612
    }
613
614
    /**
615
     * Deletes all versions and fields, all locations (subtree), and all relations.
616
     *
617
     * Removes the relations, but not the related objects. All subtrees of the
618
     * assigned nodes of this content objects are removed (recursively).
619
     *
620
     * @param int $contentId
621
     *
622
     * @return bool
623
     */
624
    public function deleteContent($contentId)
625
    {
626
        $contentLocations = $this->contentGateway->getAllLocationIds($contentId);
627
        if (empty($contentLocations)) {
628
            $this->removeRawContent($contentId);
629
        } else {
630
            foreach ($contentLocations as $locationId) {
631
                $this->treeHandler->removeSubtree($locationId);
632
            }
633
        }
634
    }
635
636
    /**
637
     * Deletes raw content data.
638
     *
639
     * @param int $contentId
640
     */
641
    public function removeRawContent($contentId)
642
    {
643
        $this->treeHandler->removeRawContent($contentId);
644
    }
645
646
    /**
647
     * Deletes given version, its fields, node assignment, relations and names.
648
     *
649
     * Removes the relations, but not the related objects.
650
     *
651
     * @param int $contentId
652
     * @param int $versionNo
653
     *
654
     * @return bool
655
     */
656
    public function deleteVersion($contentId, $versionNo)
657
    {
658
        $versionInfo = $this->loadVersionInfo($contentId, $versionNo);
659
660
        $this->locationGateway->deleteNodeAssignment($contentId, $versionNo);
661
662
        $this->fieldHandler->deleteFields($contentId, $versionInfo);
663
664
        $this->contentGateway->deleteRelations($contentId, $versionNo);
665
        $this->contentGateway->deleteVersions($contentId, $versionNo);
666
        $this->contentGateway->deleteNames($contentId, $versionNo);
667
    }
668
669
    /**
670
     * Returns the versions for $contentId.
671
     *
672
     * Result is returned with oldest version first (sorted by created, alternatively version id if auto increment).
673
     *
674
     * @param int $contentId
675
     * @param mixed|null $status Optional argument to filter versions by status, like {@see VersionInfo::STATUS_ARCHIVED}.
676
     * @param int $limit Limit for items returned, -1 means none.
677
     *
678
     * @return \eZ\Publish\SPI\Persistence\Content\VersionInfo[]
679
     */
680
    public function listVersions($contentId, $status = null, $limit = -1)
681
    {
682
        return $this->treeHandler->listVersions($contentId, $status, $limit);
683
    }
684
685
    /**
686
     * Copy Content with Fields, Versions & Relations from $contentId in $version.
687
     *
688
     * {@inheritdoc}
689
     *
690
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException If content or version is not found
691
     *
692
     * @param mixed $contentId
693
     * @param mixed|null $versionNo Copy all versions if left null
694
     * @param int|null $newOwnerId
695
     *
696
     * @return \eZ\Publish\SPI\Persistence\Content
697
     */
698
    public function copy($contentId, $versionNo = null, $newOwnerId = null)
699
    {
700
        $currentVersionNo = isset($versionNo) ?
701
            $versionNo :
702
            $this->loadContentInfo($contentId)->currentVersionNo;
703
704
        // Copy content in given version or current version
705
        $createStruct = $this->mapper->createCreateStructFromContent(
706
            $this->load($contentId, $currentVersionNo)
707
        );
708
        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...
709
            $createStruct->ownerId = $newOwnerId;
710
        }
711
        $content = $this->internalCreate($createStruct, $currentVersionNo);
712
713
        // If version was not passed also copy other versions
714
        if (!isset($versionNo)) {
715
            $contentType = $this->contentTypeHandler->load($createStruct->typeId);
716
717
            foreach ($this->listVersions($contentId) as $versionInfo) {
718
                if ($versionInfo->versionNo === $currentVersionNo) {
719
                    continue;
720
                }
721
722
                $versionContent = $this->load($contentId, $versionInfo->versionNo);
723
724
                $versionContent->versionInfo->contentInfo->id = $content->versionInfo->contentInfo->id;
725
                $versionContent->versionInfo->modificationDate = $createStruct->modified;
726
                $versionContent->versionInfo->creationDate = $createStruct->modified;
727
                $versionContent->versionInfo->id = $this->contentGateway->insertVersion(
728
                    $versionContent->versionInfo,
729
                    $versionContent->fields
730
                );
731
732
                $this->fieldHandler->createNewFields($versionContent, $contentType);
733
734
                // Create names
735 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...
736
                    $this->contentGateway->setName(
737
                        $content->versionInfo->contentInfo->id,
738
                        $versionInfo->versionNo,
739
                        $name,
740
                        $language
741
                    );
742
                }
743
            }
744
745
            // Batch copy relations for all versions
746
            $this->contentGateway->copyRelations($contentId, $content->versionInfo->contentInfo->id);
747
        } else {
748
            // Batch copy relations for published version
749
            $this->contentGateway->copyRelations($contentId, $content->versionInfo->contentInfo->id, $versionNo);
750
        }
751
752
        return $content;
753
    }
754
755
    /**
756
     * Creates a relation between $sourceContentId in $sourceContentVersionNo
757
     * and $destinationContentId with a specific $type.
758
     *
759
     * @todo Should the existence verifications happen here or is this supposed to be handled at a higher level?
760
     *
761
     * @param \eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct $createStruct
762
     *
763
     * @return \eZ\Publish\SPI\Persistence\Content\Relation
764
     */
765
    public function addRelation(RelationCreateStruct $createStruct)
766
    {
767
        $relation = $this->mapper->createRelationFromCreateStruct($createStruct);
768
769
        $relation->id = $this->contentGateway->insertRelation($createStruct);
770
771
        return $relation;
772
    }
773
774
    /**
775
     * Removes a relation by relation Id.
776
     *
777
     * @todo Should the existence verifications happen here or is this supposed to be handled at a higher level?
778
     *
779
     * @param mixed $relationId
780
     * @param int $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
781
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
782
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
783
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
784
     */
785
    public function removeRelation($relationId, $type)
786
    {
787
        $this->contentGateway->deleteRelation($relationId, $type);
788
    }
789
790
    /**
791
     * Loads relations from $sourceContentId. Optionally, loads only those with $type and $sourceContentVersionNo.
792
     *
793
     * @param mixed $sourceContentId Source Content ID
794
     * @param mixed|null $sourceContentVersionNo Source Content Version, null if not specified
795
     * @param int|null $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
796
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
797
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
798
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
799
     *
800
     * @return \eZ\Publish\SPI\Persistence\Content\Relation[]
801
     */
802
    public function loadRelations($sourceContentId, $sourceContentVersionNo = null, $type = null)
803
    {
804
        return $this->mapper->extractRelationsFromRows(
805
            $this->contentGateway->loadRelations($sourceContentId, $sourceContentVersionNo, $type)
806
        );
807
    }
808
809
    /**
810
     * Loads relations from $contentId. Optionally, loads only those with $type.
811
     *
812
     * Only loads relations against published versions.
813
     *
814
     * @param mixed $destinationContentId Destination Content ID
815
     * @param int|null $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
816
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
817
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
818
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
819
     *
820
     * @return \eZ\Publish\SPI\Persistence\Content\Relation[]
821
     */
822
    public function loadReverseRelations($destinationContentId, $type = null)
823
    {
824
        return $this->mapper->extractRelationsFromRows(
825
            $this->contentGateway->loadReverseRelations($destinationContentId, $type)
826
        );
827
    }
828
829
    /**
830
     * {@inheritdoc}
831
     */
832
    public function removeTranslationFromContent($contentId, $languageCode)
833
    {
834
        @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...
835
            __METHOD__ . ' is deprecated, use deleteTranslationFromContent instead',
836
            E_USER_DEPRECATED
837
        );
838
        $this->deleteTranslationFromContent($contentId, $languageCode);
839
    }
840
841
    /**
842
     * {@inheritdoc}
843
     */
844
    public function deleteTranslationFromContent($contentId, $languageCode)
845
    {
846
        $this->fieldHandler->deleteTranslationFromContentFields(
847
            $contentId,
848
            $this->listVersions($contentId),
849
            $languageCode
850
        );
851
        $this->contentGateway->deleteTranslationFromContent($contentId, $languageCode);
852
    }
853
854
    /**
855
     * {@inheritdoc}
856
     */
857
    public function deleteTranslationFromDraft($contentId, $versionNo, $languageCode)
858
    {
859
        $versionInfo = $this->loadVersionInfo($contentId, $versionNo);
860
861
        $this->fieldHandler->deleteTranslationFromVersionFields(
862
            $versionInfo,
863
            $languageCode
864
        );
865
        $this->contentGateway->deleteTranslationFromVersion(
866
            $contentId,
867
            $versionNo,
868
            $languageCode
869
        );
870
871
        // get all [languageCode => name] entries except the removed Translation
872
        $names = array_filter(
873
            $versionInfo->names,
874
            function ($lang) use ($languageCode) {
875
                return $lang !== $languageCode;
876
            },
877
            ARRAY_FILTER_USE_KEY
878
        );
879
        // set new Content name
880
        foreach ($names as $language => $name) {
881
            $this->contentGateway->setName(
882
                $contentId,
883
                $versionNo,
884
                $name,
885
                $language
886
            );
887
        }
888
889
        // reload entire Version w/o removed Translation
890
        return $this->load($contentId, $versionNo);
891
    }
892
}
893