Passed
Push — master ( 8fedad...7afaf7 )
by
unknown
11:25
created

HttpRequestTask   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 166
Duplicated Lines 0 %

Test Coverage

Coverage 85.11%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 38
dl 0
loc 166
rs 10
c 2
b 0
f 0
ccs 40
cts 47
cp 0.8511
wmc 19

9 Methods

Rating   Name   Duplication   Size   Complexity  
A createPostParameter() 0 5 1
A init() 0 5 1
A setResponseRegex() 0 3 1
A setMethod() 0 3 1
A isHeaderSet() 0 11 4
A processResponse() 0 20 5
A setVerbose() 0 3 1
A request() 0 18 4
A setResponseCodeRegex() 0 3 1
1
<?php
2
/**
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the LGPL. For more information please see
17
 * <http://phing.info>.
18
 */
19
20
use GuzzleHttp\Middleware;
21
use Psr\Http\Message\ResponseInterface;
22
use Symfony\Component\Console\Logger\ConsoleLogger;
23
24
/**
25
 * A HTTP request task.
26
 * Making an HTTP request and try to match the response against an provided
27
 * regular expression.
28
 *
29
 * @package phing.tasks.ext
30
 * @author  Benjamin Schultz <[email protected]>
31
 * @since   2.4.1
32
 */
33
class HttpRequestTask extends HttpTask
34
{
35
    /**
36
     * Holds the regular expression that should match the response
37
     *
38
     * @var string
39
     */
40
    protected $responseRegex = '';
41
42
    /**
43
     * Holds the regular expression that should match the response code
44
     *
45
     * @var string
46
     */
47
    protected $responseCodeRegex = '';
48
49
    /**
50
     * Whether to enable detailed logging
51
     *
52
     * @var boolean
53
     */
54
    protected $verbose = false;
55
56
    /**
57
     * Holds additional post parameters for the request
58
     *
59
     * @var Parameter[]
60
     */
61
    protected $postParameters = [];
62
63
    /**
64
     * @var Regexp
65
     */
66
    private $regexp;
67
68
    /**
69
     * Sets the response regex
70
     *
71
     * @param string $regex
72
     */
73 2
    public function setResponseRegex($regex)
74
    {
75 2
        $this->responseRegex = $regex;
76 2
    }
77
78
    /**
79
     * Sets the response code regex
80
     *
81
     * @param string $regex
82
     */
83 1
    public function setResponseCodeRegex($regex)
84
    {
85 1
        $this->responseCodeRegex = $regex;
86 1
    }
87
88
    /**
89
     * Sets whether to enable detailed logging
90
     *
91
     * @param boolean $verbose
92
     */
93
    public function setVerbose($verbose)
94
    {
95
        $this->verbose = StringHelper::booleanValue($verbose);
96
    }
97
98
    /**
99
     * The setter for the method
100
     *
101
     * @param $method
102
     */
103 1
    public function setMethod($method)
104
    {
105 1
        $this->method = $method;
106 1
    }
107
108
    /**
109
     * Creates post body parameters for this request
110
     *
111
     * @return Parameter The created post parameter
112
     */
113 1
    public function createPostParameter()
114
    {
115 1
        $num = array_push($this->postParameters, new Parameter());
116
117 1
        return $this->postParameters[$num - 1];
118
    }
119
120
    /**
121
     * Load the necessary environment for running this task.
122
     *
123
     * @throws BuildException
124
     */
125 8
    public function init()
126
    {
127 8
        parent::init();
128
129 8
        $this->regexp = new Regexp();
130 8
    }
131
132
    /**
133
     * Creates and configures an instance of HTTP_Request2
134
     *
135
     * @param array $options
136
     * @return ResponseInterface
137
     * @throws HTTP_Request2_Exception
138
     */
139 7
    protected function request($options = [])
140
    {
141 7
        if ($this->method === 'POST') {
142 1
            $idx = ($this->isHeaderSet('content-type', 'application/json') ? 'json' : 'form_params');
143 1
            $options[$idx] = array_reduce(
144 1
                $this->postParameters,
145
                function ($carry, Parameter $postParameter) {
146 1
                    return $carry + [$postParameter->getName() => $postParameter->getValue()];
147 1
                },
148 1
                []
149
            );
150
        }
151
152 7
        if ($this->verbose) {
153
            self::getHandlerStack()->push(Middleware::log(new ConsoleLogger(), new \GuzzleHttp\MessageFormatter()));
0 ignored issues
show
Bug introduced by
The call to Symfony\Component\Consol...leLogger::__construct() has too few arguments starting with output. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

153
            self::getHandlerStack()->push(Middleware::log(/** @scrutinizer ignore-call */ new ConsoleLogger(), new \GuzzleHttp\MessageFormatter()));

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
154
        }
155
156 7
        return parent::request($options);
157
    }
158
159 1
    private function isHeaderSet($headerName, $headerValue)
160
    {
161 1
        $isSet = false;
162
163 1
        foreach ($this->headers as $header) {
164
            if ($header->getName() === $headerName && $header->getValue() === $headerValue) {
165
                $isSet = true;
166
            }
167
        }
168
169 1
        return $isSet;
170
    }
171
172
    /**
173
     * Checks whether response body or status-code matches the given regexp
174
     *
175
     * @param ResponseInterface $response
176
     * @return void
177
     * @throws RegexpException
178
     */
179 4
    protected function processResponse(ResponseInterface $response)
180
    {
181 4
        if ($this->responseRegex !== '') {
182 2
            $this->regexp->setPattern($this->responseRegex);
183
184 2
            if (!$this->regexp->matches($response->getBody())) {
185 1
                throw new BuildException('The received response body did not match the given regular expression');
186
            }
187
188 1
            $this->log('The response body matched the provided regex.');
189
        }
190
191 3
        if ($this->responseCodeRegex !== '') {
192 1
            $this->regexp->setPattern($this->responseCodeRegex);
193
194 1
            if (!$this->regexp->matches($response->getStatusCode())) {
195
                throw new BuildException('The received response status-code did not match the given regular expression');
196
            }
197
198 1
            $this->log('The response status-code matched the provided regex.');
199
        }
200 3
    }
201
}
202