Completed
Push — master ( 2bd329...4a0c8e )
by Gaetano
18:18 queued 15:28
created

ServiceExecutor   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 138
Duplicated Lines 19.57 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 5.88%

Importance

Changes 0
Metric Value
wmc 30
lcom 1
cbo 4
dl 27
loc 138
ccs 4
cts 68
cp 0.0588
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A execute() 16 16 3
D call() 0 43 10
C setReferences() 0 37 13
A resolveReferencesRecursively() 11 11 3

How to fix   Duplicated Code   

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:

1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use Symfony\Component\DependencyInjection\ContainerInterface;
6
use Kaliop\eZMigrationBundle\API\Value\MigrationStep;
7
use Kaliop\eZMigrationBundle\Core\ReferenceResolver\PrefixBasedResolverInterface;
8
9
class ServiceExecutor extends AbstractExecutor
10
{
11
    protected $supportedStepTypes = array('service');
12
    protected $supportedActions = array('call');
13
14
    /** @var PrefixBasedResolverInterface $referenceResolver */
15
    protected $referenceResolver;
16
17
    protected $container;
18
19 72
    public function __construct(ContainerInterface $container, PrefixBasedResolverInterface $referenceResolver)
20
    {
21 72
        $this->referenceResolver = $referenceResolver;
22 72
        $this->container = $container;
23 72
    }
24
25
    /**
26
     * @param MigrationStep $step
27
     * @return mixed
28
     * @throws \Exception
29
     */
30 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...
31
    {
32
        parent::execute($step);
33
34
        if (!isset($step->dsl['mode'])) {
35
            throw new \Exception("Invalid step definition: missing 'mode'");
36
        }
37
38
        $action = $step->dsl['mode'];
39
40
        if (!in_array($action, $this->supportedActions)) {
41
            throw new \Exception("Invalid step definition: value '$action' is not allowed for 'mode'");
42
        }
43
44
        return $this->$action($step->dsl, $step->context);
45
    }
46
47
    /**
48
     * @param $dsl
49
     * @param $context
50
     * @return \Symfony\Component\Process\Process
51
     * @throws \Exception
52
     */
53
    protected function call($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...
54
    {
55
        if (!isset($dsl['service'])) {
56
            throw new \Exception("Can not call service method: 'service' missing");
57
        }
58
        if (!isset($dsl['method'])) {
59
            throw new \Exception("Can not call service method: 'method' missing");
60
        }
61
        if (isset($dsl['arguments']) && !is_array($dsl['arguments'])) {
62
            throw new \Exception("Can not call service method: 'arguments' is not an array");
63
        }
64
65
        $service = $this->container->get($this->referenceResolver->resolveReference($dsl['service']));
66
        $method = $this->referenceResolver->resolveReference($dsl['method']);
67
        $callable = array($service, $method);
68
        if (!is_callable($callable)) {
69
            throw new \Exception("Can not call service method: $method is not a method of " . get_class($service));
70
        }
71
72
        if (isset($dsl['arguments'])) {
73
            $args = $dsl['arguments'];
74
        } else {
75
            $args = array();
76
        }
77
        foreach($args as &$val) {
78
            $val = $this->resolveReferencesRecursively($val);
79
        }
80
81
        $exception = null;
82
        try {
83
            $result = call_user_func_array($callable, $args);
84
        } catch (\Exception $exception) {
85
            if (isset($dsl['catch'])) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
86
                // @todo allow to specify a set of exceptions to tolerate
87
            }
88
89
            throw $exception;
90
        }
91
92
        $this->setReferences($result, $exception, $dsl);
93
94
        return $result;
95
    }
96
97
    protected function setReferences($result, \Exception $exception = null, $dsl)
98
    {
99
        if (!array_key_exists('references', $dsl)) {
100
            return false;
101
        }
102
103
        foreach ($dsl['references'] as $reference) {
104
            switch ($reference['attribute']) {
105
                case 'result':
106
                    $value = $result;
107
                    break;
108
                case 'exception_code':
109
                    $value = $exception ? $exception->getCode() : null;
110
                    break;
111
                case 'exception_message':
112
                    $value = $exception ? $exception->getMessage() : null;
113
                    break;
114
                case 'exception_file':
115
                    $value = $exception ? $exception->getFile() : null;
116
                    break;
117
                case 'exception_line':
118
                    $value = $exception ? $exception->getLine() : null;
119
                    break;
120
121
                default:
122
                    throw new \InvalidArgumentException('Service executor does not support setting references for attribute ' . $reference['attribute']);
123
            }
124
125
            $overwrite = false;
126
            if (isset($reference['overwrite'])) {
127
                $overwrite = $reference['overwrite'];
128
            }
129
            $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...
130
        }
131
132
        return true;
133
    }
134
135 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...
136
    {
137
        if (is_array($match)) {
138
            foreach ($match as $condition => $values) {
139
                $match[$condition] = $this->resolveReferencesRecursively($values);
140
            }
141
            return $match;
142
        } else {
143
            return $this->referenceResolver->resolveReference($match);
144
        }
145
    }
146
}
147