Completed
Push — master ( 68da2d...d119ba )
by Gaetano
07:21
created

SectionManager::setReferences()   D

Complexity

Conditions 10
Paths 15

Size

Total Lines 37
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 26
nc 15
nop 2

How to fix   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
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use Kaliop\eZMigrationBundle\API\Collection\SectionCollection;
6
use Kaliop\eZMigrationBundle\API\MigrationGeneratorInterface;
7
use Kaliop\eZMigrationBundle\Core\Matcher\SectionMatcher;
8
9
/**
10
 * Handles section migrations.
11
 */
12
class SectionManager extends RepositoryExecutor implements MigrationGeneratorInterface
13
{
14
    protected $supportedStepTypes = array('section');
15
16
    /** @var SectionMatcher $sectionMatcher */
17
    protected $sectionMatcher;
18
19
    /**
20
     * @param SectionMatcher $sectionMatcher
21
     */
22
    public function __construct(SectionMatcher $sectionMatcher)
23
    {
24
        $this->sectionMatcher = $sectionMatcher;
25
    }
26
27
    /**
28
     * Handles the section create migration action
29
     */
30
    protected function create($step)
31
    {
32
        $sectionService = $this->repository->getSectionService();
33
34
        $sectionCreateStruct = $sectionService->newSectionCreateStruct();
35
36
        $sectionCreateStruct->identifier = $step->dsl['identifier'];
37
        $sectionCreateStruct->name = $step->dsl['name'];
38
39
        $section = $sectionService->createSection($sectionCreateStruct);
40
41
        $this->setReferences($section, $step);
42
43
        return $section;
44
    }
45
46
    /**
47
     * Handles the section update migration action
48
     */
49
    protected function update($step)
50
    {
51
        $sectionCollection = $this->matchSections('update', $step);
52
53
        if (count($sectionCollection) > 1 && array_key_exists('references', $step->dsl)) {
54
            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");
55
        }
56
57
        $sectionService = $this->repository->getSectionService();
58
        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...
59
            $sectionUpdateStruct = $sectionService->newSectionUpdateStruct();
60
61
            if (isset($step->dsl['identifier'])) {
62
                $sectionUpdateStruct->identifier = $step->dsl['identifier'];
63
            }
64
            if (isset($step->dsl['name'])) {
65
                $sectionUpdateStruct->name = $step->dsl['name'];
66
            }
67
68
            $section = $sectionService->updateSection($section, $sectionUpdateStruct);
69
70
            $sectionCollection[$key] = $section;
71
        }
72
73
        $this->setReferences($sectionCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $sectionCollection defined by $this->matchSections('update', $step) on line 51 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...
74
75
        return $sectionCollection;
76
    }
77
78
    /**
79
     * Handles the section delete migration action
80
     */
81
    protected function delete($step)
82
    {
83
        $sectionCollection = $this->matchSections('delete', $step);
84
85
        $this->setReferences($sectionCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $sectionCollection defined by $this->matchSections('delete', $step) on line 83 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...
86
87
        $sectionService = $this->repository->getSectionService();
88
89
        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...
90
            $sectionService->deleteSection($section);
91
        }
92
93
        return $sectionCollection;
94
    }
95
96
    /**
97
     * @param string $action
98
     * @return SectionCollection
99
     * @throws \Exception
100
     */
101 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...
102
    {
103
        if (!isset($step->dsl['match'])) {
104
            throw new \Exception("A match condition is required to $action a section");
105
        }
106
107
        $match = $step->dsl['match'];
0 ignored issues
show
Unused Code introduced by
$match 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...
108
109
        // convert the references passed in the match
110
        $match = $this->resolveReferencesRecursively($step->dsl['match']);
0 ignored issues
show
Deprecated Code introduced by
The method Kaliop\eZMigrationBundle...ReferencesRecursively() has been deprecated with message: will be moved into the reference resolver classes

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
111
112
        return $this->sectionMatcher->match($match);
113
    }
114
115
    /**
116
     * Sets references to certain section attributes.
117
     *
118
     * @param \eZ\Publish\API\Repository\Values\Content\Section|SectionCollection $section
119
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
120
     * @return boolean
121
     */
122
    protected function setReferences($section, $step)
123
    {
124
        if (!array_key_exists('references', $step->dsl)) {
125
            return false;
126
        }
127
128
        $this->setReferencesCommon($section, $step);
129
        $section = $this->insureSingleEntity($section, $step);
130
131
        foreach ($step->dsl['references'] as $reference) {
132
133
            switch ($reference['attribute']) {
134
                case 'section_id':
135
                case 'id':
136
                    $value = $section->id;
137
                    break;
138
                case 'section_identifier':
139
                case 'identifier':
140
                    $value = $section->identifier;
141
                    break;
142
                case 'section_name':
143
                case 'name':
144
                    $value = $section->name;
145
                    break;
146
                default:
147
                    throw new \InvalidArgumentException('Section Manager does not support setting references for attribute ' . $reference['attribute']);
148
            }
149
150
            $overwrite = false;
151
            if (isset($reference['overwrite'])) {
152
                $overwrite = $reference['overwrite'];
153
            }
154
            $this->referenceResolver->addReference($reference['identifier'], $value, $overwrite);
155
        }
156
157
        return true;
158
    }
159
160
    /**
161
     * @param array $matchCondition
162
     * @param string $mode
163
     * @param array $context
164
     * @throws \Exception
165
     * @return array
166
     */
167 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...
168
    {
169
        $previousUserId = $this->loginUser($this->getAdminUserIdentifierFromContext($context));
170
        $sectionCollection = $this->sectionMatcher->match($matchCondition);
171
        $data = array();
172
173
        /** @var \eZ\Publish\API\Repository\Values\Content\Section $section */
174
        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...
175
176
            $sectionData = array(
177
                'type' => reset($this->supportedStepTypes),
178
                'mode' => $mode,
179
            );
180
181
            switch ($mode) {
182
                case 'create':
183
                    $sectionData = array_merge(
184
                        $sectionData,
185
                        array(
186
                            'identifier' => $section->identifier,
187
                            'name' => $section->name,
188
                        )
189
                    );
190
                    break;
191
                case 'update':
192
                    $sectionData = array_merge(
193
                        $sectionData,
194
                        array(
195
                            'match' => array(
196
                                SectionMatcher::MATCH_SECTION_ID => $section->id
197
                            ),
198
                            'identifier' => $section->identifier,
199
                            'name' => $section->name,
200
                        )
201
                    );
202
                    break;
203
                case 'delete':
204
                    $sectionData = array_merge(
205
                        $sectionData,
206
                        array(
207
                            'match' => array(
208
                                SectionMatcher::MATCH_SECTION_ID => $section->id
209
                            )
210
                        )
211
                    );
212
                    break;
213
                default:
214
                    throw new \Exception("Executor 'section' doesn't support mode '$mode'");
215
            }
216
217
            $data[] = $sectionData;
218
        }
219
220
        $this->loginUser($previousUserId);
221
        return $data;
222
    }
223
}
224