Completed
Push — master ( ba3b59...d7270b )
by Gaetano
16:37 queued 12:29
created

SectionManager::setReferences()   D

Complexity

Conditions 10
Paths 15

Size

Total Lines 36
Code Lines 26

Duplication

Lines 36
Ratio 100 %

Code Coverage

Tests 15
CRAP Score 16.4

Importance

Changes 0
Metric Value
dl 36
loc 36
ccs 15
cts 25
cp 0.6
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 26
nc 15
nop 2
crap 16.4

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 73
    public function __construct(SectionMatcher $sectionMatcher)
23
    {
24 73
        $this->sectionMatcher = $sectionMatcher;
25 73
    }
26
27
    /**
28
     * Handles the section create migration action
29
     */
30 1
    protected function create($step)
31
    {
32 1 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...
33 1
            if (!isset($step->dsl[$key])) {
34 1
                throw new \Exception("The '$key' key is missing in a section creation definition");
35
            }
36
        }
37
38 1
        $sectionService = $this->repository->getSectionService();
39
40 1
        $sectionCreateStruct = $sectionService->newSectionCreateStruct();
41
42 1
        $sectionIdentifier = $this->referenceResolver->resolveReference($step->dsl['identifier']);
43 1
        $sectionCreateStruct->identifier = $sectionIdentifier;
44 1
        $sectionCreateStruct->name = $step->dsl['name'];
45
46 1
        $section = $sectionService->createSection($sectionCreateStruct);
47
48 1
        $this->setReferences($section, $step);
49
50 1
        return $section;
51
    }
52
53
    /**
54
     * Handles the section update migration action
55
     */
56 1
    protected function update($step)
57
    {
58 1
        $sectionCollection = $this->matchSections('update', $step);
59
60 1
        if (count($sectionCollection) > 1 && array_key_exists('references', $step->dsl)) {
61
            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");
62
        }
63
64 1
        $sectionService = $this->repository->getSectionService();
65 1
        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...
66 1
            $sectionUpdateStruct = $sectionService->newSectionUpdateStruct();
67
68 1
            if (isset($step->dsl['identifier'])) {
69 1
                $sectionUpdateStruct->identifier = $this->referenceResolver->resolveReference($step->dsl['identifier']);
70
            }
71 1
            if (isset($step->dsl['name'])) {
72 1
                $sectionUpdateStruct->name = $step->dsl['name'];
73
            }
74
75 1
            $section = $sectionService->updateSection($section, $sectionUpdateStruct);
76
77 1
            $sectionCollection[$key] = $section;
78
        }
79
80 1
        $this->setReferences($sectionCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $sectionCollection defined by $this->matchSections('update', $step) on line 58 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...
81
82 1
        return $sectionCollection;
83
    }
84
85
    /**
86
     * Handles the section delete migration action
87
     */
88 1
    protected function delete($step)
89
    {
90 1
        $sectionCollection = $this->matchSections('delete', $step);
91
92 1
        $this->setReferences($sectionCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $sectionCollection defined by $this->matchSections('delete', $step) on line 90 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...
93
94 1
        $sectionService = $this->repository->getSectionService();
95
96 1
        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...
97 1
            $sectionService->deleteSection($section);
98
        }
99
100 1
        return $sectionCollection;
101
    }
102
103
    /**
104
     * @param string $action
105
     * @return SectionCollection
106
     * @throws \Exception
107
     */
108 1 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...
109
    {
110 1
        if (!isset($step->dsl['match'])) {
111
            throw new \Exception("A match condition is required to $action a section");
112
        }
113
114
        // convert the references passed in the match
115 1
        $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...
116
117 1
        return $this->sectionMatcher->match($match);
118
    }
119
120
    /**
121
     * Sets references to certain section attributes.
122
     *
123
     * @param \eZ\Publish\API\Repository\Values\Content\Section|SectionCollection $section
124
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
125
     * @return boolean
126
     */
127 1 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...
128
    {
129 1
        if (!array_key_exists('references', $step->dsl)) {
130 1
            return false;
131
        }
132
133 1
        $references = $this->setReferencesCommon($section, $step->dsl['references']);
134 1
        $section = $this->insureSingleEntity($section, $references);
135
136 1
        foreach ($references as $reference) {
137 1
            switch ($reference['attribute']) {
138 1
                case 'section_id':
139 1
                case 'id':
140 1
                    $value = $section->id;
141 1
                    break;
142
                case 'section_identifier':
143
                case 'identifier':
144
                    $value = $section->identifier;
145
                    break;
146
                case 'section_name':
147
                case 'name':
148
                    $value = $section->name;
149
                    break;
150
                default:
151
                    throw new \InvalidArgumentException('Section Manager does not support setting references for attribute ' . $reference['attribute']);
152
            }
153
154 1
            $overwrite = false;
155 1
            if (isset($reference['overwrite'])) {
156
                $overwrite = $reference['overwrite'];
157
            }
158 1
            $this->referenceResolver->addReference($reference['identifier'], $value, $overwrite);
159
        }
160
161 1
        return true;
162
    }
163
164
    /**
165
     * @param array $matchCondition
166
     * @param string $mode
167
     * @param array $context
168
     * @throws \Exception
169
     * @return array
170
     */
171 3 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...
172
    {
173 3
        $previousUserId = $this->loginUser($this->getAdminUserIdentifierFromContext($context));
174 3
        $sectionCollection = $this->sectionMatcher->match($matchCondition);
175 3
        $data = array();
176
177
        /** @var \eZ\Publish\API\Repository\Values\Content\Section $section */
178 3
        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...
179
180
            $sectionData = array(
181 3
                'type' => reset($this->supportedStepTypes),
182 3
                'mode' => $mode,
183
            );
184
185
            switch ($mode) {
186 3
                case 'create':
187 1
                    $sectionData = array_merge(
188 1
                        $sectionData,
189
                        array(
190 1
                            'identifier' => $section->identifier,
191 1
                            'name' => $section->name,
192
                        )
193
                    );
194 1
                    break;
195 2
                case 'update':
196 1
                    $sectionData = array_merge(
197 1
                        $sectionData,
198
                        array(
199
                            'match' => array(
200 1
                                SectionMatcher::MATCH_SECTION_ID => $section->id
201
                            ),
202 1
                            'identifier' => $section->identifier,
203 1
                            'name' => $section->name,
204
                        )
205
                    );
206 1
                    break;
207 1
                case 'delete':
208 1
                    $sectionData = array_merge(
209 1
                        $sectionData,
210
                        array(
211
                            'match' => array(
212 1
                                SectionMatcher::MATCH_SECTION_ID => $section->id
213
                            )
214
                        )
215
                    );
216 1
                    break;
217
                default:
218
                    throw new \Exception("Executor 'section' doesn't support mode '$mode'");
219
            }
220
221 3
            $data[] = $sectionData;
222
        }
223
224 3
        $this->loginUser($previousUserId);
225 3
        return $data;
226
    }
227
}
228