Completed
Push — master ( 09cee1...75eab4 )
by Gaetano
06:21
created

SectionManager::getReferencesValues()   C

Complexity

Conditions 8
Paths 8

Size

Total Lines 27
Code Lines 20

Duplication

Lines 20
Ratio 74.07 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
dl 20
loc 27
ccs 0
cts 17
cp 0
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 20
nc 8
nop 2
crap 72
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use eZ\Publish\API\Repository\Values\Content\Section;
6
use Kaliop\eZMigrationBundle\API\Collection\SectionCollection;
7
use Kaliop\eZMigrationBundle\API\MigrationGeneratorInterface;
8
use Kaliop\eZMigrationBundle\Core\Matcher\SectionMatcher;
9
10
/**
11
 * Handles section migrations.
12
 */
13
class SectionManager extends RepositoryExecutor implements MigrationGeneratorInterface
14
{
15
    protected $supportedStepTypes = array('section');
16
17
    /** @var SectionMatcher $sectionMatcher */
18
    protected $sectionMatcher;
19
20
    /**
21
     * @param SectionMatcher $sectionMatcher
22
     */
23
    public function __construct(SectionMatcher $sectionMatcher)
24
    {
25
        $this->sectionMatcher = $sectionMatcher;
26
    }
27
28
    /**
29
     * Handles the section create migration action
30
     */
31
    protected function create($step)
32
    {
33 View Code Duplication
        foreach (array('name', 'identifier') as $key) {
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...
34
            if (!isset($step->dsl[$key])) {
35
                throw new \Exception("The '$key' key is missing in a section creation definition");
36
            }
37
        }
38
39
        $sectionService = $this->repository->getSectionService();
40
41
        $sectionCreateStruct = $sectionService->newSectionCreateStruct();
42
43
        $sectionIdentifier = $this->referenceResolver->resolveReference($step->dsl['identifier']);
44
        $sectionCreateStruct->identifier = $sectionIdentifier;
45
        $sectionCreateStruct->name = $step->dsl['name'];
46
47
        $section = $sectionService->createSection($sectionCreateStruct);
48
49
        $this->setReferences($section, $step);
50
51
        return $section;
52
    }
53
54
    /**
55
     * Handles the section update migration action
56
     */
57
    protected function update($step)
58
    {
59
        $sectionCollection = $this->matchSections('update', $step);
60
61
        if (count($sectionCollection) > 1 && array_key_exists('references', $step->dsl)) {
62
            throw new \Exception("Can not execute Section update because multiple types match, and a references section is specified in the dsl. References can be set when only 1 section matches");
63
        }
64
65
        $sectionService = $this->repository->getSectionService();
66
        foreach ($sectionCollection as $key => $section) {
0 ignored issues
show
Bug introduced by
The expression $sectionCollection of type object<Kaliop\eZMigratio...SectionCollection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
67
            $sectionUpdateStruct = $sectionService->newSectionUpdateStruct();
68
69
            if (isset($step->dsl['identifier'])) {
70
                $sectionUpdateStruct->identifier = $this->referenceResolver->resolveReference($step->dsl['identifier']);
71
            }
72
            if (isset($step->dsl['name'])) {
73
                $sectionUpdateStruct->name = $step->dsl['name'];
74
            }
75
76
            $section = $sectionService->updateSection($section, $sectionUpdateStruct);
77
78
            $sectionCollection[$key] = $section;
79
        }
80
81
        $this->setReferences($sectionCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $sectionCollection defined by $this->matchSections('update', $step) on line 59 can be null; however, Kaliop\eZMigrationBundle...anager::setReferences() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
82
83
        return $sectionCollection;
84
    }
85
86
    /**
87
     * Handles the section delete migration action
88
     */
89
    protected function delete($step)
90
    {
91
        $sectionCollection = $this->matchSections('delete', $step);
92
93
        $this->setReferences($sectionCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $sectionCollection defined by $this->matchSections('delete', $step) on line 91 can be null; however, Kaliop\eZMigrationBundle...anager::setReferences() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
94
95
        $sectionService = $this->repository->getSectionService();
96
97
        foreach ($sectionCollection as $section) {
0 ignored issues
show
Bug introduced by
The expression $sectionCollection of type object<Kaliop\eZMigratio...SectionCollection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
98
            $sectionService->deleteSection($section);
99
        }
100
101
        return $sectionCollection;
102
    }
103
104
    /**
105
     * @param string $action
106
     * @return SectionCollection
107
     * @throws \Exception
108
     */
109 View Code Duplication
    protected function matchSections($action, $step)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
110
    {
111
        if (!isset($step->dsl['match'])) {
112
            throw new \Exception("A match condition is required to $action a section");
113
        }
114
115
        // convert the references passed in the match
116
        $match = $this->resolveReferencesRecursively($step->dsl['match']);
117
118
        return $this->sectionMatcher->match($match);
119
    }
120
121
    /**
122
     * Sets references to certain section attributes.
123
     *
124
     * @param \eZ\Publish\API\Repository\Values\Content\Section|SectionCollection $section
125
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
126
     * @return boolean
127
     */
128 View Code Duplication
    protected function setReferences($section, $step)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
129
    {
130
        if (!array_key_exists('references', $step->dsl)) {
131
            return false;
132
        }
133
134
        $references = $this->setReferencesCommon($section, $step->dsl['references']);
135
        $section = $this->insureSingleEntity($section, $references);
0 ignored issues
show
Unused Code introduced by
$section is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
136
    }
137
138
    /**
139
     * @param Section $section
140
     * @param array $references the definitions of the references to set
141
     * @throws \InvalidArgumentException When trying to assign a reference to an unsupported attribute
142
     * @return array key: the reference names, values: the reference values
143
     */
144
    protected function getReferencesValues(Section $section, array $references)
145
    {
146
        $refs = array();
147
148 View Code Duplication
        foreach ($references as $reference) {
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...
149
            switch ($reference['attribute']) {
150
                case 'section_id':
151
                case 'id':
152
                    $value = $section->id;
153
                    break;
154
                case 'section_identifier':
155
                case 'identifier':
156
                    $value = $section->identifier;
157
                    break;
158
                case 'section_name':
159
                case 'name':
160
                    $value = $section->name;
161
                    break;
162
                default:
163
                    throw new \InvalidArgumentException('Section Manager does not support setting references for attribute ' . $reference['attribute']);
164
            }
165
166
            $refs[$reference['identifier']] = $value;
167
        }
168
169
        return $refs;
170
    }
171
172
    /**
173
     * @param array $matchCondition
174
     * @param string $mode
175
     * @param array $context
176
     * @throws \Exception
177
     * @return array
178
     */
179 View Code Duplication
    public function generateMigration(array $matchCondition, $mode, array $context = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
180
    {
181
        $previousUserId = $this->loginUser($this->getAdminUserIdentifierFromContext($context));
182
        $sectionCollection = $this->sectionMatcher->match($matchCondition);
183
        $data = array();
184
185
        /** @var \eZ\Publish\API\Repository\Values\Content\Section $section */
186
        foreach ($sectionCollection as $section) {
0 ignored issues
show
Bug introduced by
The expression $sectionCollection of type object<Kaliop\eZMigratio...SectionCollection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
187
188
            $sectionData = array(
189
                'type' => reset($this->supportedStepTypes),
190
                'mode' => $mode,
191
            );
192
193
            switch ($mode) {
194
                case 'create':
195
                    $sectionData = array_merge(
196
                        $sectionData,
197
                        array(
198
                            'identifier' => $section->identifier,
199
                            'name' => $section->name,
200
                        )
201
                    );
202
                    break;
203
                case 'update':
204
                    $sectionData = array_merge(
205
                        $sectionData,
206
                        array(
207
                            'match' => array(
208
                                SectionMatcher::MATCH_SECTION_ID => $section->id
209
                            ),
210
                            'identifier' => $section->identifier,
211
                            'name' => $section->name,
212
                        )
213
                    );
214
                    break;
215
                case 'delete':
216
                    $sectionData = array_merge(
217
                        $sectionData,
218
                        array(
219
                            'match' => array(
220
                                SectionMatcher::MATCH_SECTION_ID => $section->id
221
                            )
222
                        )
223
                    );
224
                    break;
225
                default:
226
                    throw new \Exception("Executor 'section' doesn't support mode '$mode'");
227
            }
228
229
            $data[] = $sectionData;
230
        }
231
232
        $this->loginUser($previousUserId);
233
        return $data;
234
    }
235
}
236