Completed
Push — master ( d1a68d...21f884 )
by Gaetano
06:22
created

ServiceExecutor::setReferences()   C

Complexity

Conditions 13
Paths 21

Size

Total Lines 37
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 182

Importance

Changes 0
Metric Value
dl 0
loc 37
ccs 0
cts 18
cp 0
rs 5.1234
c 0
b 0
f 0
cc 13
eloc 27
nc 21
nop 3
crap 182

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 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 mixed
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
        $result = null;
83
        try {
84
            $result = call_user_func_array($callable, $args);
85
        } catch (\Exception $exception) {
86
            $catch = false;
87
88
            // allow to specify a set of exceptions to tolerate
89
            if (isset($dsl['catch'])) {
90
                if (is_array($dsl['catch'])) {
91
                    $caught = $dsl['catch'];
92
                } else {
93
                    $caught = array($dsl['catch']);
94
                }
95
96
                foreach ($caught as $baseException) {
97
                    if (is_subclass_of($exception, $baseException)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if $baseException can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
98
                        $catch = true;
99
                        break;
100
                    }
101
                }
102
            }
103
104
            if (!$catch) {
105
                throw $exception;
106
            }
107
        }
108
109
        $this->setReferences($result, $exception, $dsl);
110
111
        return $result;
112
    }
113
114
    protected function setReferences($result, \Exception $exception = null, $dsl)
115
    {
116
        if (!array_key_exists('references', $dsl)) {
117
            return false;
118
        }
119
120
        foreach ($dsl['references'] as $reference) {
121
            switch ($reference['attribute']) {
122
                case 'result':
123
                    $value = $result;
124
                    break;
125
                case 'exception_code':
126
                    $value = $exception ? $exception->getCode() : null;
127
                    break;
128
                case 'exception_message':
129
                    $value = $exception ? $exception->getMessage() : null;
130
                    break;
131
                case 'exception_file':
132
                    $value = $exception ? $exception->getFile() : null;
133
                    break;
134
                case 'exception_line':
135
                    $value = $exception ? $exception->getLine() : null;
136
                    break;
137
138
                default:
139
                    throw new \InvalidArgumentException('Service executor does not support setting references for attribute ' . $reference['attribute']);
140
            }
141
142
            $overwrite = false;
143
            if (isset($reference['overwrite'])) {
144
                $overwrite = $reference['overwrite'];
145
            }
146
            $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...
147
        }
148
149
        return true;
150
    }
151
152 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...
153
    {
154
        if (is_array($match)) {
155
            foreach ($match as $condition => $values) {
156
                $match[$condition] = $this->resolveReferencesRecursively($values);
157
            }
158
            return $match;
159
        } else {
160
            return $this->referenceResolver->resolveReference($match);
161
        }
162
    }
163
}
164