Completed
Push — master ( 72ca4d...2bd329 )
by Gaetano
26:05
created

ServiceExecutor::resolveReferencesRecursively()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 11
Ratio 100 %

Importance

Changes 0
Metric Value
dl 11
loc 11
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
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
    public function __construct(ContainerInterface $container, PrefixBasedResolverInterface $referenceResolver)
20
    {
21
        $this->referenceResolver = $referenceResolver;
22
        $this->container = $container;
23
    }
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($dsl['service']);
66
        $method = $dsl['method'];
67
        $callable = array($service, $method);
68
        if (isset($dsl['arguments'])) {
69
            $args = $dsl['arguments'];
70
        } else {
71
            $args = array();
72
        }
73
74
        if (!is_callable($callable)) {
75
            throw new \Exception("Can not call service method: $method is not a method of " . get_class($service));
76
        }
77
78
        foreach($args as &$val) {
79
            $val = $this->resolveReferencesRecursively($val);
80
        }
81
82
        try {
83
            $result = call_user_func_array($callable, $args);
84
        } catch (\Exception $e) {
85
            // @todo allow to specify a set of exceptions to tolerate
86
            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...
87
88
            }
89
90
            throw $e;
91
        }
92
93
        $this->setReferences($result, $dsl);
94
95
        return $output;
0 ignored issues
show
Bug introduced by
The variable $output does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
96
    }
97
98 View Code Duplication
    protected function setReferences($result, $dsl)
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...
99
    {
100
        if (!array_key_exists('references', $dsl)) {
101
            return false;
102
        }
103
104
        foreach ($dsl['references'] as $reference) {
105
            switch ($reference['attribute']) {
106
                case 'result':
107
                    $value = $result;
108
                    break;
109
                default:
110
                    throw new \InvalidArgumentException('Service executor does not support setting references for attribute ' . $reference['attribute']);
111
            }
112
113
            $overwrite = false;
114
            if (isset($reference['overwrite'])) {
115
                $overwrite = $reference['overwrite'];
116
            }
117
            $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...
118
        }
119
120
        return true;
121
    }
122
123 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...
124
    {
125
        if (is_array($match)) {
126
            foreach ($match as $condition => $values) {
127
                $match[$condition] = $this->resolveReferencesRecursively($values);
128
            }
129
            return $match;
130
        } else {
131
            return $this->referenceResolver->resolveReference($match);
132
        }
133
    }
134
}
135