Completed
Push — master ( f910d1...68da4b )
by Gaetano
05:20
created

RepositoryExecutor   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 356
Duplicated Lines 6.74 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 90.18%

Importance

Changes 0
Metric Value
wmc 55
lcom 1
cbo 6
dl 24
loc 356
ccs 101
cts 112
cp 0.9018
rs 6
c 0
b 0
f 0

19 Methods

Rating   Name   Duplication   Size   Complexity  
getReferencesValues() 0 1 ?
A setRepository() 0 4 1
A setConfigResolver() 0 4 1
A setReferenceResolver() 0 4 1
A execute() 0 37 5
A getLanguageCode() 0 4 2
A getLanguageCodeFromContext() 0 13 4
A getUserContentType() 0 4 2
A getUserContentTypeFromContext() 0 4 2
A getAdminUserIdentifierFromContext() 0 8 2
B setReferences() 7 45 9
A setReferencesCommon() 0 23 4
A insureSingleEntity() 0 10 2
B insureEntityCountCompatibility() 6 15 8
A getReferencesType() 0 4 2
A allowEmptyReferences() 0 8 5
A getSelfName() 0 8 1
A getCollectionName() 0 8 1
A resolveReferencesRecursively() 11 11 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like RepositoryExecutor often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use RepositoryExecutor, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use eZ\Publish\API\Repository\Repository;
6
use eZ\Publish\Core\MVC\ConfigResolverInterface;
7
use Kaliop\eZMigrationBundle\API\Collection\AbstractCollection;
8
use Kaliop\eZMigrationBundle\API\ReferenceResolverBagInterface;
9
use Kaliop\eZMigrationBundle\API\Value\MigrationStep;
10
use Kaliop\eZMigrationBundle\Core\RepositoryUserSetterTrait;
11
12
/**
13
 * The core manager class that all migration action managers inherit from.
14
 */
15
abstract class RepositoryExecutor extends AbstractExecutor
16
{
17
    use RepositoryUserSetterTrait;
18
    use IgnorableStepExecutorTrait;
19
20
    /**
21
     * Constant defining the default language code (used if not specified by the migration or on the command line)
22
     */
23
    const DEFAULT_LANGUAGE_CODE = 'eng-GB';
24
25
    /**
26
     * The default Admin user Id, used when no Admin user is specified
27
     */
28
    const ADMIN_USER_ID = 14;
29
30
    /** Used if not specified by the migration */
31
    const USER_CONTENT_TYPE = 'user';
32
33
    const REFERENCE_TYPE_SCALAR = 'scalar';
34
    const REFERENCE_TYPE_ARRAY = 'array';
35
36
    /**
37
     * @var array $dsl The parsed DSL instruction array
38
     */
39
    //protected $dsl;
40
41
    /** @var array $context The context (configuration) for the execution of the current step */
42
    //protected $context;
43
44
    /**
45
     * The eZ Publish 5 API repository.
46
     *
47
     * @var \eZ\Publish\API\Repository\Repository
48
     */
49
    protected $repository;
50
51
    protected $configResolver;
52
53
    /** @var ReferenceResolverBagInterface $referenceResolver */
54
    protected $referenceResolver;
55
56
    // to redefine in subclasses if they don't support all methods, or if they support more...
57
    protected $supportedActions = array(
58
        'create', 'update', 'delete'
59
    );
60
61 80
    public function setRepository(Repository $repository)
62
    {
63 80
        $this->repository = $repository;
64 80
    }
65
66 80
    public function setConfigResolver(ConfigResolverInterface $configResolver)
67
    {
68 80
        $this->configResolver = $configResolver;
69 80
    }
70
71 80
    public function setReferenceResolver(ReferenceResolverBagInterface $referenceResolver)
72
    {
73 80
        $this->referenceResolver = $referenceResolver;
74 80
    }
75
76 24
    public function execute(MigrationStep $step)
77
    {
78
        // base checks
79 24
        parent::execute($step);
80
81 24
        if (!isset($step->dsl['mode'])) {
82
            throw new \Exception("Invalid step definition: missing 'mode'");
83
        }
84
85
        // q: should we convert snake_case to camelCase ?
86 24
        $action = $step->dsl['mode'];
87
88 24
        if (!in_array($action, $this->supportedActions)) {
89
            throw new \Exception("Invalid step definition: value '$action' is not allowed for 'mode'");
90
        }
91
92 24
        if (method_exists($this, $action)) {
93
94 24
            $this->skipStepIfNeeded($step);
95
96 24
            $previousUserId = $this->loginUser($this->getAdminUserIdentifierFromContext($step->context));
97
98
            try {
99 24
                $output = $this->$action($step);
100 6
            } catch (\Exception $e) {
101 6
                $this->loginUser($previousUserId);
102 6
                throw $e;
103
            }
104
105
            // reset the environment as much as possible as we had found it before the migration
106 22
            $this->loginUser($previousUserId);
107
108 22
            return $output;
109
        } else {
110
            throw new \Exception("Invalid step definition: value '$action' is not a method of " . get_class($this));
111
        }
112
    }
113
114
    /**
115
     * Method that each executor (subclass) has to implement.
116
     *
117
     * It is used to get values for references based on the DSL instructions executed in the current step, for later steps to reuse.
118
     *
119
     * @throws \InvalidArgumentException when trying to set a reference to an unsupported attribute.
120
     * @param mixed $object a single element to extract reference values from
121
     * @param array $referencesDefinitions the definitions of the references to extract
122
     * @param MigrationStep $step
123
     * @return array key: the reference name (taken from $referencesDefinitions[n]['identifier'], value: the ref. value
124
     */
125
    abstract protected function getReferencesValues($object, array $referencesDefinitions, $step);
126
127
    /**
128
     * @param MigrationStep $step
129
     * @return string
130
     */
131 17
    protected function getLanguageCode($step)
132
    {
133 17
        return isset($step->dsl['lang']) ? $step->dsl['lang'] : $this->getLanguageCodeFromContext($step->context);
134
    }
135
136
    /**
137
     * @param array|null $context
138
     * @return string
139
     */
140 22
    protected function getLanguageCodeFromContext($context)
141
    {
142 22
        if (is_array($context) && isset($context['defaultLanguageCode'])) {
143 6
            return $context['defaultLanguageCode'];
144
        }
145
146 16
        if ($this->configResolver) {
147 16
            $locales = $this->configResolver->getParameter('languages');
148 16
            return reset($locales);
149
        }
150
151
        return self::DEFAULT_LANGUAGE_CODE;
152
    }
153
154
    /**
155
     * @param MigrationStep $step
156
     * @return string
157
     */
158 2
    protected function getUserContentType($step)
159
    {
160 2
        return isset($step->dsl['user_content_type']) ? $this->referenceResolver->resolveReference($step->dsl['user_content_type']) : $this->getUserContentTypeFromContext($step->context);
161
    }
162
163
    /**
164
     * @param array $context
165
     * @return string
166
     */
167 2
    protected function getUserContentTypeFromContext($context)
168
    {
169 2
        return isset($context['userContentType']) ? $context['userContentType'] : self::USER_CONTENT_TYPE;
170
    }
171
172
    /**
173
     * @param array $context we have to return FALSE if that is set as adminUserLogin, whereas if NULL is set, we return the default admin
174
     * @return int|string|false
175
     */
176 49
    protected function getAdminUserIdentifierFromContext($context)
177
    {
178 49
        if (isset($context['adminUserLogin'])) {
179
            return $context['adminUserLogin'];
180
        }
181
182 49
        return self::ADMIN_USER_ID;
183
    }
184
185
    /**
186
     * Sets references to certain attributes of the items returned by steps.
187
     *
188
     * @param \Object|AbstractCollection $item
189
     * @param MigrationStep $step
190
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
191
     * @return boolean
192
     * @todo should we allow to be passed in plain arrays as well as Collections?
193
     */
194 23
    protected function setReferences($item, $step)
195
    {
196 23
        if (!array_key_exists('references', $step->dsl)) {
197 20
            return false;
198
        }
199
200 18
        $referencesDefs = $this->setReferencesCommon($item, $step->dsl['references']);
201
202 18
        $this->insureEntityCountCompatibility($item, $referencesDefs, $step);
203
204 17
        $multivalued = ($this->getReferencesType($step) == self::REFERENCE_TYPE_ARRAY);
0 ignored issues
show
Documentation introduced by
$step is of type object<Kaliop\eZMigratio...PI\Value\MigrationStep>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
205
206 17
        if ($item instanceof AbstractCollection) {
207 12
            $items = $item;
208
        } else {
209 16
            $items = array($item);
210
        }
211
212 17
        $referencesValues = array();
213 17
        foreach ($items as $item) {
214 17
            $itemReferencesValues = $this->getReferencesValues($item, $referencesDefs, $step);
215 17
            if (!$multivalued) {
216 16
                $referencesValues = $itemReferencesValues;
217
            } else {
218 1
                foreach ($itemReferencesValues as $refName => $refValue) {
219 1
                    if (!isset($referencesValues[$refName])) {
220 1
                        $referencesValues[$refName] = array($refValue);
221
                    } else {
222 17
                        $referencesValues[$refName][] = $refValue;
223
                    }
224
                }
225
            }
226
        }
227
228 17 View Code Duplication
        foreach($referencesDefs 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...
229 17
            $overwrite = false;
230 17
            if (isset($reference['overwrite'])) {
231 1
                $overwrite = $reference['overwrite'];
232
            }
233 17
            $this->referenceResolver->addReference($reference['identifier'], $referencesValues[$reference['identifier']], $overwrite);
234
        }
235
236
237 17
        return true;
238
    }
239
240
    /**
241
     * @param mixed $entity
242
     * @param array $referencesDefinition
243
     * @return array the same as $referencesDefinition, with the references already treated having been removed
244
     */
245 18
    protected function setReferencesCommon($entity, $referencesDefinition)
246
    {
247
        // allow setting *some* refs even when we have 0 or N matches
248 18
        foreach ($referencesDefinition as $key => $reference) {
249 18
            switch($reference['attribute']) {
250
251 18
                case 'count':
252 4
                    $value = count($entity);
253 4
                    $overwrite = false;
254 4
                    if (isset($reference['overwrite'])) {
255 1
                        $overwrite = $reference['overwrite'];
256
                    }
257 4
                    $this->referenceResolver->addReference($reference['identifier'], $value, $overwrite);
258 4
                    unset($referencesDefinition[$key]);
259 4
                    break;
260
261 18
                default:
262
                    // do nothing
263
            }
264
        }
265
266 18
        return $referencesDefinition;
267
    }
268
269
    /**
270
     * Verifies compatibility between the definition of the refences to be set and the data set to extarct them from,
271
     * and returns a single entity
272
     *
273
     * @param AbstractCollection|mixed $entity
274
     * @param array $referencesDefinition
275
     * @param MigrationStep $step
276
     * @return AbstractCollection|mixed
277
     * @deprecated
278
     */
279
    protected function insureSingleEntity($entity, $referencesDefinition, $step)
280
    {
281
        $this->insureEntityCountCompatibility($entity, $referencesDefinition, $step);
282
283
        if ($entity instanceof AbstractCollection) {
284
            return reset($entity);
285
        }
286
287
        return $entity;
288
    }
289
290
    /**
291
     * Verifies compatibility between the definition of the references to be set and the data set to extract them from.
292
     * NB: for multivalued refs, we assume that the users always expect at least one value
293
     * @param AbstractCollection|mixed $entity
294
     * @param array $referencesDefinition
295
     * @param MigrationStep $step
296
     * @return void throws when incompatibility is found
297
     * @todo should we allow to be passed in plain arrays as well as Collections?
298
     */
299 18
    protected function insureEntityCountCompatibility($entity, $referencesDefinition, $step)
300
    {
301 18
        if ($entity instanceof AbstractCollection) {
302
303 13
            $minOneRef = count($referencesDefinition) > 0 && (!$this->allowEmptyReferences($step));
0 ignored issues
show
Documentation introduced by
$step is of type object<Kaliop\eZMigratio...PI\Value\MigrationStep>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
304 13
            $maxOneRef = count($referencesDefinition) > 0 && $this->getReferencesType($step) == self::REFERENCE_TYPE_SCALAR;
0 ignored issues
show
Documentation introduced by
$step is of type object<Kaliop\eZMigratio...PI\Value\MigrationStep>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
305
306 13 View Code Duplication
            if ($maxOneRef && count($entity) > 1) {
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...
307 1
                throw new \InvalidArgumentException($this->getSelfName() . ' does not support setting references for multiple ' . $this->getCollectionName($entity) . 's');
308
            }
309 12 View Code Duplication
            if ($minOneRef && count($entity) == 0) {
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...
310
                throw new \InvalidArgumentException($this->getSelfName() . ' does not support setting references for no ' . $this->getCollectionName($entity) . 's');
311
            }
312
        }
313 17
    }
314
315 18
    /**
316
     * @param array $step
317 18
     * @return string
318
     */
319
    protected function getReferencesType($step)
320 1
    {
321
        return isset($step->dsl['references_type']) ? $step->dsl['references_type'] : self::REFERENCE_TYPE_SCALAR;
322 1
    }
323 1
324 1
    /**
325
     * @param array $step
326 1
     * @return bool
327
     */
328
    protected function allowEmptyReferences($step)
329 1
    {
330
        if (isset($step->dsl['references_type']) && $step->dsl['references_type'] == self::REFERENCE_TYPE_ARRAY &&
331 1
            isset($step->dsl['references_allow_empty']) && $step->dsl['references_allow_empty'] == true
332 1
        )
333 1
            return true;
334
        return false;
335 1
    }
336
337
    protected function getSelfName()
338
    {
339
        $className = get_class($this);
340
        $array = explode('\\', $className);
341
        $className = end($array);
342 19
        // CamelCase to Camel Case using negative look-behind in regexp
343
        return preg_replace('/(?<!^)[A-Z]/', ' $0', $className);
344 19
    }
345 19
346 19
    protected function getCollectionName($collection)
347
    {
348 18
        $className = get_class($collection);
349
        $array = explode('\\', $className);
350 19
        $className = str_replace('Collection', '', end($array));
351
        // CamelCase to snake case using negative look-behind in regexp
352
        return strtolower(preg_replace('/(?<!^)[A-Z]/', ' $0', $className));
353
    }
354
355
    /**
356
     * Courtesy code to avoid reimplementing it in every subclass
357
     * @todo will be moved into the reference resolver classes
358
     */
359 View Code Duplication
    protected function resolveReferencesRecursively($match)
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...
360
    {
361
        if (is_array($match)) {
362
            foreach ($match as $condition => $values) {
363
                $match[$condition] = $this->resolveReferencesRecursively($values);
364
            }
365
            return $match;
366
        } else {
367
            return $this->referenceResolver->resolveReference($match);
368
        }
369
    }
370
}
371