Completed
Push — master ( bdbb05...9c991f )
by Gaetano
07:38
created

HTTPExecutor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
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\API\ReferenceResolverInterface;
8
use Kaliop\eZMigrationBundle\Core\ReferenceResolver\PrefixBasedResolverInterface;
9
use Psr\Http\Message\ResponseInterface;
10
11
class HTTPExecutor extends AbstractExecutor
12
{
13
    protected $supportedStepTypes = array('http');
14
    protected $supportedActions = array('call');
15
16
    /** @var ReferenceResolverInterface $referenceResolver */
17
    protected $referenceResolver;
18
19
    protected $container;
20
21
    public function __construct(ContainerInterface $container, PrefixBasedResolverInterface $referenceResolver)
22
    {
23
        $this->referenceResolver = $referenceResolver;
24
        $this->container = $container;
25
    }
26
27
    /**
28
     * @param MigrationStep $step
29
     * @return mixed
30
     * @throws \Exception
31
     */
32 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...
33
    {
34
        parent::execute($step);
35
36
        if (!isset($step->dsl['mode'])) {
37
            throw new \Exception("Invalid step definition: missing 'mode'");
38
        }
39
40
        $action = $step->dsl['mode'];
41
42
        if (!in_array($action, $this->supportedActions)) {
43
            throw new \Exception("Invalid step definition: value '$action' is not allowed for 'mode'");
44
        }
45
46
        return $this->$action($step->dsl, $step->context);
47
    }
48
49
    /**
50
     * @param array $dsl
51
     * @param array $context
52
     * @return true
53
     * @throws \Exception
54
     */
55
    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...
56
    {
57
        if (!isset($dsl['uri'])) {
58
            throw new \Exception("Can not execute http call without 'uri' in the step definition");
59
        }
60
61
        $method = isset($dsl['method']) ? $dsl['method'] : 'GET';
62
63
        $uri = $this->resolveReferencesInText($dsl['uri']);
64
65
        $headers = isset($dsl['headers']) ? $this->resolveReferencesInTextRecursively($dsl['headers']) : array();
66
67
        $body = isset($dsl['body']) ? $this->resolveReferencesInText($dsl['body']) : null;
68
69
        if (isset($dsl['client'])) {
70
            $client = $this->container->get('httplug.client.'.$dsl['client']);
71
        } else {
72
            $client = $this->container->get('httplug.client');
73
        }
74
75
        $request = $this->container->get('httplug.message_factory')->createRequest($method, $uri, $headers, $body);
76
77
        $response = $client->sendRequest($request);
78
79
        $this->setReferences($response, $dsl);
80
81
        return $response;
82
    }
83
84
    protected function setReferences(ResponseInterface $response, $dsl)
85
    {
86
        if (!array_key_exists('references', $dsl)) {
87
            return false;
88
        }
89
90
        foreach ($dsl['references'] as $reference) {
91
            switch ($reference['attribute']) {
92
                case 'status_code':
93
                    $value = $response->getStatusCode();
94
                    break;
95
                case 'reason_phrase':
96
                    $value = $response->getReasonPhrase();
97
                    break;
98
                case 'protocol_version':
99
                    $value = $response->getProtocolVersion();
100
                    break;
101
                case 'body':
102
                    $value = $response->getBody();
103
                    break;
104
                default:
105
                    throw new \InvalidArgumentException('HTTP executor does not support setting references for attribute ' . $reference['attribute']);
106
            }
107
108
            $overwrite = false;
109
            if (isset($reference['overwrite'])) {
110
                $overwrite = $reference['overwrite'];
111
            }
112
            $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...erenceResolverInterface as the method addReference() does only exist in the following implementations of said interface: Kaliop\eZMigrationBundle...ver\ChainPrefixResolver, Kaliop\eZMigrationBundle...ver\ChainRegexpResolver, Kaliop\eZMigrationBundle...eResolver\ChainResolver, 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...
113
        }
114
115
        return true;
116
    }
117
118
    /**
119
     * @deprecated should be moved into the reference resolver classes
120
     */
121 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...
122
    {
123
        if (is_array($match)) {
124
            foreach ($match as $condition => $values) {
125
                $match[$condition] = $this->resolveReferencesRecursively($values);
0 ignored issues
show
Deprecated Code introduced by
The method Kaliop\eZMigrationBundle...ReferencesRecursively() has been deprecated with message: should be moved into the reference resolver classes

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
126
            }
127
            return $match;
128
        } else {
129
            return $this->referenceResolver->resolveReference($match);
130
        }
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);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Kaliop\eZMigrationBundle...erenceResolverInterface as the method getRegexp() does only exist in the following implementations of said interface: Kaliop\eZMigrationBundle...solver\AbstractResolver, Kaliop\eZMigrationBundle...ver\ChainPrefixResolver, Kaliop\eZMigrationBundle...ver\ChainRegexpResolver, Kaliop\eZMigrationBundle...esolver\ContentResolver, Kaliop\eZMigrationBundle...CustomReferenceResolver, Kaliop\eZMigrationBundle...solver\LocationResolver, Kaliop\eZMigrationBundle...ver\PrefixBasedResolver, Kaliop\eZMigrationBundle...nceResolver\TagResolver.

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...
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
158
    protected function resolveReferencesInTextRecursively($textOrArray)
159
    {
160
        if (is_array($textOrArray)) {
161
            foreach ($textOrArray as $condition => $values) {
162
                $textOrArray[$condition] = $this->resolveReferencesInTextRecursively($values);
163
            }
164
            return $textOrArray;
165
        } else {
166
            return $this->resolveReferencesInText($textOrArray);
167
        }
168
    }
169
}
170