Completed
Push — master ( 709104...6665be )
by Gaetano
09:48
created

ProcessExecutor::execute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
dl 16
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 1
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use Symfony\Component\Process\ProcessBuilder;
6
use Symfony\Component\Process\Process;
7
use Kaliop\eZMigrationBundle\API\Value\MigrationStep;
8
use Kaliop\eZMigrationBundle\Core\ReferenceResolver\PrefixBasedResolverInterface;
9
10
class ProcessExecutor extends AbstractExecutor
11
{
12
    protected $supportedStepTypes = array('process');
13
    protected $supportedActions = array('run');
14
15
    protected $defaultTimeout = 86400;
16
17
    /** @var PrefixBasedResolverInterface $referenceResolver */
18
    protected $referenceResolver;
19
20
    public function __construct(PrefixBasedResolverInterface $referenceResolver)
21
    {
22
        $this->referenceResolver = $referenceResolver;
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
     * @todo add more options supported by Sf Process
53
     */
54
    protected function run($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...
55
    {
56
        if (!isset($dsl['command'])) {
57
            throw new \Exception("Can not run process: command missing");
58
        }
59
60
        $builder = new ProcessBuilder();
61
62
        // mandatory args and options
63
        $builderArgs = array($this->referenceResolver->resolveReference($dsl['command']));
64
65
        if (isset($dsl['arguments'])) {
66
            foreach($dsl['arguments'] as $arg) {
67
                $builderArgs[] = $this->referenceResolver->resolveReference($arg);
68
            }
69
        }
70
71
        $process = $builder
72
            ->setArguments($builderArgs)
73
            ->getProcess();
74
75
        // allow long migrations processes by default
76
        $timeout = $this->defaultTimeout;
77
        if (isset($dsl['timeout'])) {
78
            $timeout = $dsl['timeout'];
79
        }
80
        $process->setTimeout($timeout);
81
82
        if (isset($dsl['working_directory'])) {
83
            $process->setWorkingDirectory($dsl['working_directory']);
84
        }
85
86
        if (isset($dsl['disable_output'])) {
87
            $process->disableOutput();
88
        }
89
90
        if (isset($dsl['environment'])) {
91
            $process->setEnv($dsl['environment']);
92
        }
93
94
        $process->run();
95
96
        $this->setReferences($process, $dsl);
97
98
        return $process;
99
    }
100
101 View Code Duplication
    protected function setReferences(Process $process, $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...
102
    {
103
        if (!array_key_exists('references', $dsl)) {
104
            return false;
105
        }
106
107
108
        foreach ($dsl['references'] as $reference) {
109
            switch ($reference['attribute']) {
110
                case 'error_output':
111
                    $value = $process->getErrorOutput();
112
                    break;
113
                case 'exit_code':
114
                    $value = $process->getExitCode();
115
                    break;
116
                case 'output':
117
                    $value = $process->getOutput();
118
                    break;
119
                default:
120
                    throw new \InvalidArgumentException('Process executor does not support setting references for attribute ' . $reference['attribute']);
121
            }
122
123
            $overwrite = false;
124
            if (isset($reference['overwrite'])) {
125
                $overwrite = $reference['overwrite'];
126
            }
127
            $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...
128
        }
129
130
        return true;
131
    }
132
133
    /**
134
     * Replaces any references inside a string
135
     *
136
     * @param string
137
     * @return string
138
     */
139 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...
140
    {
141
        // 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
142
        $regexp = substr($this->referenceResolver->getRegexp(), 1, -1);
143
        // NB: here we assume that all regexp resolvers give us a regexp with a very specific format...
144
        $regexp = '/\[' . preg_replace(array('/^\^/'), array('', ''), $regexp) . '[^]]+\]/';
145
146
        $count = preg_match_all($regexp, $text, $matches);
147
        // $matches[0][] will have the matched full string eg.: [reference:example_reference]
148
        if ($count) {
149
            foreach ($matches[0] as $referenceIdentifier) {
150
                $reference = $this->referenceResolver->getReferenceValue(substr($referenceIdentifier, 1, -1));
151
                $text = str_replace($referenceIdentifier, $reference, $text);
152
            }
153
        }
154
155
        return $text;
156
    }
157
}