RelationProcessor::processFieldRelations()   F
last analyzed

Complexity

Conditions 25
Paths 1998

Size

Total Lines 100

Duplication

Lines 38
Ratio 38 %

Importance

Changes 0
Metric Value
cc 25
nc 1998
nop 5
dl 38
loc 100
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
5
 * @license For full copyright and license information view LICENSE file distributed with this source code.
6
 */
7
namespace eZ\Publish\Core\Repository\Helper;
8
9
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
10
use eZ\Publish\SPI\Persistence\Handler;
11
use eZ\Publish\API\Repository\Values\ContentType\ContentType;
12
use eZ\Publish\Core\Repository\Values\Content\Relation;
13
use eZ\Publish\SPI\FieldType\Value as BaseValue;
14
use eZ\Publish\SPI\FieldType\FieldType as SPIFieldType;
15
use eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct as SPIRelationCreateStruct;
16
use Psr\Log\LoggerAwareTrait;
17
use Psr\Log\NullLogger;
18
19
/**
20
 * RelationProcessor is an internal service used for handling field relations upon Content creation or update.
21
 *
22
 * @internal Meant for internal use by Repository.
23
 */
24
class RelationProcessor
25
{
26
    use LoggerAwareTrait;
27
28
    /** @var \eZ\Publish\SPI\Persistence\Handler */
29
    protected $persistenceHandler;
30
31
    /**
32
     * Setups service with reference to repository object that created it & corresponding handler.
33
     *
34
     * @param \eZ\Publish\SPI\Persistence\Handler $handler
35
     */
36
    public function __construct(Handler $handler)
37
    {
38
        $this->persistenceHandler = $handler;
39
        $this->logger = new NullLogger();
40
    }
41
42
    /**
43
     * Appends destination Content ids of given $fieldValue to the $relation array.
44
     *
45
     * If $fieldValue contains Location ids, the will be converted to the Content id that Location encapsulates.
46
     *
47
     * @param array $relations
48
     * @param array $locationIdToContentIdMapping An array with Location Ids as keys and corresponding Content Id as values
49
     * @param \eZ\Publish\SPI\FieldType\FieldType $fieldType
50
     * @param \eZ\Publish\SPI\FieldType\Value $fieldValue Accepted field value.
51
     * @param string $fieldDefinitionId
52
     */
53
    public function appendFieldRelations(
54
        array &$relations,
55
        array &$locationIdToContentIdMapping,
56
        SPIFieldType $fieldType,
57
        BaseValue $fieldValue,
58
        $fieldDefinitionId
59
    ) {
60
        foreach ($fieldType->getRelations($fieldValue) as $relationType => $destinationIds) {
61
            if ($relationType & (Relation::FIELD | Relation::ASSET)) {
62
                if (!isset($relations[$relationType][$fieldDefinitionId])) {
63
                    $relations[$relationType][$fieldDefinitionId] = [];
64
                }
65
                $relations[$relationType][$fieldDefinitionId] += array_flip($destinationIds);
66
            } elseif ($relationType & (Relation::LINK | Relation::EMBED)) {
67
                // Using bitwise operators as Legacy Stack stores COMMON, LINK and EMBED relation types
68
                // in the same entry using bitmask
69
                if (!isset($relations[$relationType])) {
70
                    $relations[$relationType] = [];
71
                }
72
73
                if (isset($destinationIds['locationIds'])) {
74
                    foreach ($destinationIds['locationIds'] as $locationId) {
75
                        try {
76
                            if (!isset($locationIdToContentIdMapping[$locationId])) {
77
                                $location = $this->persistenceHandler->locationHandler()->load($locationId);
78
                                $locationIdToContentIdMapping[$locationId] = $location->contentId;
79
                            }
80
81
                            $relations[$relationType][$locationIdToContentIdMapping[$locationId]] = true;
82
                        } catch (NotFoundException $e) {
83
                            $this->logger->error('Invalid relation: destination location not found', [
84
                                'fieldDefinitionId' => $fieldDefinitionId,
85
                                'locationId' => $locationId,
86
                            ]);
87
                        }
88
                    }
89
                }
90
91
                if (isset($destinationIds['contentIds'])) {
92
                    $relations[$relationType] += array_flip($destinationIds['contentIds']);
93
                }
94
            }
95
        }
96
    }
97
98
    /**
99
     * Persists relation data for a content version.
100
     *
101
     * This method creates new relations and deletes removed relations.
102
     *
103
     * @param array $inputRelations
104
     * @param mixed $sourceContentId
105
     * @param mixed $sourceContentVersionNo
106
     * @param \eZ\Publish\API\Repository\Values\ContentType\ContentType $contentType
107
     * @param \eZ\Publish\API\Repository\Values\Content\Relation[] $existingRelations An array of existing relations for Content version (empty when creating new content)
108
     */
109
    public function processFieldRelations(
110
        array $inputRelations,
111
        $sourceContentId,
112
        $sourceContentVersionNo,
113
        ContentType $contentType,
114
        array $existingRelations = []
115
    ) {
116
        // Map existing relations for easier handling
117
        $mappedRelations = [];
118
        foreach ($existingRelations as $relation) {
119 View Code Duplication
            if ($relation->type & Relation::FIELD) {
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...
120
                $fieldDefinition = $contentType->getFieldDefinition($relation->sourceFieldDefinitionIdentifier);
121
                if ($fieldDefinition !== null) {
122
                    $mappedRelations[Relation::FIELD][$fieldDefinition->id][$relation->destinationContentInfo->id] = $relation;
123
                }
124
            }
125
126 View Code Duplication
            if ($relation->type & Relation::ASSET) {
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...
127
                $fieldDefinition = $contentType->getFieldDefinition($relation->sourceFieldDefinitionIdentifier);
128
                if ($fieldDefinition !== null) {
129
                    $mappedRelations[Relation::ASSET][$fieldDefinition->id][$relation->destinationContentInfo->id] = $relation;
130
                }
131
            }
132
133
            // Using bitwise AND as Legacy Stack stores COMMON, LINK and EMBED relation types
134
            // in the same entry using bitmask
135
            if ($relation->type & Relation::LINK) {
136
                $mappedRelations[Relation::LINK][$relation->destinationContentInfo->id] = $relation;
137
            }
138
            if ($relation->type & Relation::EMBED) {
139
                $mappedRelations[Relation::EMBED][$relation->destinationContentInfo->id] = $relation;
140
            }
141
        }
142
143
        // Add new relations
144
        foreach ($inputRelations as $relationType => $relationData) {
145
            if ($relationType === Relation::FIELD || $relationType === Relation::ASSET) {
146
                foreach ($relationData as $fieldDefinitionId => $contentIds) {
147
                    foreach (array_keys($contentIds) as $destinationContentId) {
148
                        if (isset($mappedRelations[$relationType][$fieldDefinitionId][$destinationContentId])) {
149
                            unset($mappedRelations[$relationType][$fieldDefinitionId][$destinationContentId]);
150 View Code Duplication
                        } else {
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...
151
                            $this->persistenceHandler->contentHandler()->addRelation(
152
                                new SPIRelationCreateStruct(
153
                                    [
154
                                        'sourceContentId' => $sourceContentId,
155
                                        'sourceContentVersionNo' => $sourceContentVersionNo,
156
                                        'sourceFieldDefinitionId' => $fieldDefinitionId,
157
                                        'destinationContentId' => $destinationContentId,
158
                                        'type' => $relationType,
159
                                    ]
160
                                )
161
                            );
162
                        }
163
                    }
164
                }
165
            } elseif ($relationType === Relation::LINK || $relationType === Relation::EMBED) {
166
                foreach (array_keys($relationData) as $destinationContentId) {
167
                    if (isset($mappedRelations[$relationType][$destinationContentId])) {
168
                        unset($mappedRelations[$relationType][$destinationContentId]);
169 View Code Duplication
                    } else {
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...
170
                        $this->persistenceHandler->contentHandler()->addRelation(
171
                            new SPIRelationCreateStruct(
172
                                [
173
                                    'sourceContentId' => $sourceContentId,
174
                                    'sourceContentVersionNo' => $sourceContentVersionNo,
175
                                    'sourceFieldDefinitionId' => null,
176
                                    'destinationContentId' => $destinationContentId,
177
                                    'type' => $relationType,
178
                                ]
179
                            )
180
                        );
181
                    }
182
                }
183
            }
184
        }
185
186
        // Remove relations not present in input set
187
        foreach ($mappedRelations as $relationType => $relationData) {
188
            foreach ($relationData as $relationEntry) {
189
                switch ($relationType) {
190
                    case Relation::FIELD:
191
                    case Relation::ASSET:
192
                        foreach ($relationEntry as $relation) {
193
                            $this->persistenceHandler->contentHandler()->removeRelation(
194
                                $relation->id,
195
                                $relationType
196
                            );
197
                        }
198
                        break;
199
                    case Relation::LINK:
200
                    case Relation::EMBED:
201
                        $this->persistenceHandler->contentHandler()->removeRelation(
202
                            $relationEntry->id,
203
                            $relationType
204
                        );
205
                }
206
            }
207
        }
208
    }
209
}
210