Completed
Push — master ( d7270b...0d7df6 )
by Gaetano
10:12
created

FileExecutor   C

Complexity

Total Complexity 57

Size/Duplication

Total Lines 309
Duplicated Lines 40.78 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 76.8%

Importance

Changes 0
Metric Value
wmc 57
lcom 1
cbo 3
dl 126
loc 309
ccs 96
cts 125
cp 0.768
rs 6.433
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A load() 0 14 3
A execute() 16 16 3
C save() 0 25 7
A append() 20 20 4
B prepend() 22 22 4
C copy() 25 25 8
C move() 25 25 8
A delete() 0 19 4
C setReferences() 0 49 12
A resolveReferencesInText() 18 18 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 FileExecutor 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 FileExecutor, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use Kaliop\eZMigrationBundle\API\Value\MigrationStep;
6
use Kaliop\eZMigrationBundle\Core\ReferenceResolver\PrefixBasedResolverInterface;
7
8
class FileExecutor extends AbstractExecutor
9
{
10
    protected $supportedStepTypes = array('file');
11
    protected $supportedActions = array('load', 'save', 'copy', 'move', 'delete', 'append', 'prepend');
12
13
    /** @var PrefixBasedResolverInterface $referenceResolver */
14
    protected $referenceResolver;
15
16 73
    public function __construct(PrefixBasedResolverInterface $referenceResolver)
17
    {
18 73
        $this->referenceResolver = $referenceResolver;
19 73
    }
20
21
    /**
22
     * @param MigrationStep $step
23
     * @return mixed
24
     * @throws \Exception
25
     */
26 2 View Code Duplication
    public function execute(MigrationStep $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...
27
    {
28 2
        parent::execute($step);
29
30 2
        if (!isset($step->dsl['mode'])) {
31
            throw new \Exception("Invalid step definition: missing 'mode'");
32
        }
33
34 2
        $action = $step->dsl['mode'];
35
36 2
        if (!in_array($action, $this->supportedActions)) {
37
            throw new \Exception("Invalid step definition: value '$action' is not allowed for 'mode'");
38
        }
39
40 2
        return $this->$action($step->dsl, $step->context);
41
    }
42
43
    /**
44
     * @param array $dsl
45
     * @param array $context
46
     * @return string
47
     * @throws \Exception
48
     */
49 2
    protected function load($dsl, $context)
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
50
    {
51 2
        if (!isset($dsl['file'])) {
52
            throw new \Exception("Can not load file: name missing");
53
        }
54 2
        $fileName = $this->referenceResolver->resolveReference($dsl['file']);
55 2
        if (!file_exists($fileName)) {
56
            throw new \Exception("Can not move load '$fileName': file missing");
57
        }
58
59 2
        $this->setReferences($fileName, $dsl);
60
61 2
        return file_get_contents($fileName);
62
    }
63
64
    /**
65
     * @param array $dsl
66
     * @param array $context
67
     * @return int
68
     * @throws \Exception
69
     */
70 1
    protected function save($dsl, $context)
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
71
    {
72 1
        if (!isset($dsl['file']) || !isset($dsl['body'])) {
73
            throw new \Exception("Can not save file: name or body missing");
74
        }
75
76 1
        if (is_string($dsl['body'])) {
77 1
            $contents = $this->resolveReferencesInText($dsl['body']);
78
        } else {
79
            throw new \Exception("Can not save file: body tag must be a string");
80
        }
81
82 1
        $fileName = $this->referenceResolver->resolveReference($dsl['file']);
83
84 1
        $overwrite = isset($dsl['overwrite']) ? $overwrite = $dsl['overwrite'] : false;
85 1
        if (!$overwrite && file_exists($fileName)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $overwrite of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
86
            throw new \Exception("Can not save file '$fileName: file already exists");
87
        }
88
89 1
        $return = file_put_contents($fileName, $contents);
90
91 1
        $this->setReferences($fileName, $dsl);
92
93 1
        return $return;
94
    }
95
96
    /**
97
     * @param array $dsl
98
     * @param array $context
99
     * @return int
100
     * @throws \Exception
101
     */
102 1 View Code Duplication
    protected function append($dsl, $context)
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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...
103
    {
104 1
        if (!isset($dsl['file']) || !isset($dsl['body'])) {
105
            throw new \Exception("Can not append to file: name or body missing");
106
        }
107
108 1
        if (is_string($dsl['body'])) {
109 1
            $contents = $this->resolveReferencesInText($dsl['body']);
110
        } else {
111
            throw new \Exception("Can not append to file: body tag must be a string");
112
        }
113
114 1
        $fileName = $this->referenceResolver->resolveReference($dsl['file']);
115
116 1
        $return = file_put_contents($fileName, $contents, FILE_APPEND);
117
118 1
        $this->setReferences($fileName, $dsl);
119
120 1
        return $return;
121
    }
122
123
    /**
124
     * @param array $dsl
125
     * @param array $context
126
     * @return int
127
     * @throws \Exception
128
     */
129 1 View Code Duplication
    protected function prepend($dsl, $context)
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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...
130
    {
131 1
        if (!isset($dsl['file']) || !isset($dsl['body'])) {
132
            throw new \Exception("Can not prepend to file: name or body missing");
133
        }
134
135 1
        if (is_string($dsl['body'])) {
136 1
            $contents = $this->resolveReferencesInText($dsl['body']);
137
        } else {
138
            throw new \Exception("Can not append to file: body tag must be a string");
139
        }
140 1
141
        $fileName = $this->referenceResolver->resolveReference($dsl['file']);
142 1
143 1
        $contents .= file_get_contents($fileName);
144 1
145
        $return = file_put_contents($fileName, $contents);
146
147
        $this->setReferences($fileName, $dsl);
148 1
149
        return $return;
150
    }
151
152 1
    /**
153
     * @param array $dsl
154
     * @param array $context
155
     * @return true
156
     * @throws \Exception
157
     */
158 View Code Duplication
    protected function copy($dsl, $context)
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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...
159
    {
160
        if (!isset($dsl['from']) || !isset($dsl['to'])) {
161 1
            throw new \Exception("Can not copy file: from or to missing");
162
        }
163 1
164
        $fileName = $this->referenceResolver->resolveReference($dsl['from']);
165
        if (!file_exists($fileName)) {
166
            throw new \Exception("Can not copy file '$fileName': file missing");
167 1
        }
168 1
169
        $this->setReferences($fileName, $dsl);
170
171
        $to = $this->referenceResolver->resolveReference($dsl['to']);
172 1
        $overwrite = isset($dsl['overwrite']) ? $overwrite = $dsl['overwrite'] : false;
173
        if (!$overwrite && file_exists($to)) {
174 1
            throw new \Exception("Can not copy file to '$to: file already exists");
175 1
        }
176 1
177
        if (!copy($fileName, $to)) {
178
            throw new \Exception("Can not copy file '$fileName' to '$to': operation failed");
179
        }
180 1
181
        return true;
182
    }
183
184 1
    /**
185
     * @param array $dsl
186
     * @param array $context
187
     * @return true
188
     * @throws \Exception
189
     */
190 View Code Duplication
    protected function move($dsl, $context)
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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...
191
    {
192
        if (!isset($dsl['from']) || !isset($dsl['to'])) {
193 1
            throw new \Exception("Can not move file: from or to missing");
194
        }
195 1
196
        $fileName = $this->referenceResolver->resolveReference($dsl['from']);
197
        if (!file_exists($fileName)) {
198
            throw new \Exception("Can not move file '$fileName': file missing");
199 1
        }
200 1
201
        $this->setReferences($fileName, $dsl);
202
203
        $to = $this->referenceResolver->resolveReference($dsl['to']);
204 1
        $overwrite = isset($dsl['overwrite']) ? $overwrite = $dsl['overwrite'] : false;
205
        if (!$overwrite && file_exists($to)) {
206 1
            throw new \Exception("Can not move to '$to': file already exists");
207
        }
208
209
        if (!rename($fileName, $to)) {
210 1
            throw new \Exception("Can not move file '$fileName': operation failed");
211
        }
212
213 2
        return true;
214
    }
215 2
216 1
    /**
217
     * @param array $dsl
218
     * @param array $context
219 2
     * @return true
220 2
     * @throws \Exception
221
     */
222 2
    protected function delete($dsl, $context)
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
223
    {
224
        if (!isset($dsl['file'])) {
225
            throw new \Exception("Can not delete file: name missing");
226 2
        }
227 2
228 2
        $fileName = $this->referenceResolver->resolveReference($dsl['file']);
229 2
        if (!file_exists($fileName)) {
230 2
            throw new \Exception("Can not move delete '$fileName': file missing");
231 1
        }
232 1
233 1
        $this->setReferences($fileName, $dsl);
234 1
235
        if (!unlink($fileName)) {
236
            throw new \Exception("Can not delete file '$fileName': operation failed");
237 1
        }
238
239
        return true;
240 1
    }
241 1
242 1
    protected function setReferences($fileName, $dsl)
243 1
    {
244
        if (!array_key_exists('references', $dsl)) {
245
            return false;
246 1
        }
247 1
248 1
        clearstatcache(true, $fileName);
249
        $stats = stat($fileName);
250
251
        if (!$stats) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $stats of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
252
            throw new \Exception("Can not set references for file '$fileName': stat failed");
253 2
        }
254 2
255
        foreach ($dsl['references'] as $reference) {
256
            switch ($reference['attribute']) {
257 2
                case 'body':
258
                    $value = file_get_contents($fileName);
259
                    break;
260 2
                case 'size':
261
                    $value = $stats[7];
262
                    break;
263
                case 'uid':
264
                    $value = $stats[4];
265
                    break;
266
                case 'gid':
267
                    $value = $stats[5];
268
                    break;
269 1
                case 'atime':
270
                    $value = $stats[8];
271
                    break;
272 1
                case 'mtime':
273
                    $value = $stats[9];
274 1
                    break;
275
                case 'ctime':
276 1
                    $value = $stats[10];
277
                    break;
278 1
                default:
279 1
                    throw new \InvalidArgumentException('File executor does not support setting references for attribute ' . $reference['attribute']);
280 1
            }
281 1
282
            $overwrite = false;
283
            if (isset($reference['overwrite'])) {
284
                $overwrite = $reference['overwrite'];
285 1
            }
286
            $this->referenceResolver->addReference($reference['identifier'], $value, $overwrite);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Kaliop\eZMigrationBundle...xBasedResolverInterface as the method addReference() does only exist in the following implementations of said interface: Kaliop\eZMigrationBundle...ver\ChainPrefixResolver, Kaliop\eZMigrationBundle...CustomReferenceResolver.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
287
        }
288
289
        return true;
290
    }
291
292
    /**
293
     * Replaces any references inside a string
294
     *
295
     * @param string
296
     * @return string
297
     */
298 View Code Duplication
    protected function resolveReferencesInText($text)
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...
299
    {
300
        // we need to alter the regexp we get from the resolver, as it will be used to match parts of text, not the whole string
301
        $regexp = substr($this->referenceResolver->getRegexp(), 1, -1);
302
        // NB: here we assume that all regexp resolvers give us a regexp with a very specific format...
303
        $regexp = '/\[' . preg_replace(array('/^\^/'), array('', ''), $regexp) . '[^]]+\]/';
304
305
        $count = preg_match_all($regexp, $text, $matches);
306
        // $matches[0][] will have the matched full string eg.: [reference:example_reference]
307
        if ($count) {
308
            foreach ($matches[0] as $referenceIdentifier) {
309
                $reference = $this->referenceResolver->getReferenceValue(substr($referenceIdentifier, 1, -1));
310
                $text = str_replace($referenceIdentifier, $reference, $text);
311
            }
312
        }
313
314
        return $text;
315
    }
316
}
317