Passed
Push — master ( f380be...f04938 )
by Michiel
11:54
created

HttpRequestTask::processResponse()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.0187

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
c 1
b 0
f 0
nc 7
nop 1
dl 0
loc 20
ccs 10
cts 11
cp 0.9091
crap 5.0187
rs 9.6111
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
use Symfony\Component\Console\Output\ConsoleOutput;
24
25
/**
26
 * A HTTP request task.
27
 * Making an HTTP request and try to match the response against an provided
28
 * regular expression.
29
 *
30
 * @package phing.tasks.ext
31
 * @author  Benjamin Schultz <[email protected]>
32
 * @since   2.4.1
33
 */
34
class HttpRequestTask extends HttpTask
35
{
36
    /**
37
     * Holds the regular expression that should match the response
38
     *
39
     * @var string
40
     */
41
    protected $responseRegex = '';
42
43
    /**
44
     * Holds the regular expression that should match the response code
45
     *
46
     * @var string
47
     */
48
    protected $responseCodeRegex = '';
49
50
    /**
51
     * Whether to enable detailed logging
52
     *
53
     * @var boolean
54
     */
55
    protected $verbose = false;
56
57
    /**
58
     * Holds additional post parameters for the request
59
     *
60
     * @var Parameter[]
61
     */
62
    protected $postParameters = [];
63
64
    /**
65
     * @var Regexp
66
     */
67
    private $regexp;
68
69
    /**
70
     * Sets the response regex
71
     *
72
     * @param string $regex
73
     */
74 2
    public function setResponseRegex($regex)
75
    {
76 2
        $this->responseRegex = $regex;
77 2
    }
78
79
    /**
80
     * Sets the response code regex
81
     *
82
     * @param string $regex
83
     */
84 1
    public function setResponseCodeRegex($regex)
85
    {
86 1
        $this->responseCodeRegex = $regex;
87 1
    }
88
89
    /**
90
     * Sets whether to enable detailed logging
91
     *
92
     * @param boolean $verbose
93
     */
94
    public function setVerbose($verbose)
95
    {
96
        $this->verbose = StringHelper::booleanValue($verbose);
97
    }
98
99
    /**
100
     * The setter for the method
101
     *
102
     * @param $method
103
     */
104 1
    public function setMethod($method)
105
    {
106 1
        $this->method = $method;
107 1
    }
108
109
    /**
110
     * Creates post body parameters for this request
111
     *
112
     * @return Parameter The created post parameter
113
     */
114 1
    public function createPostParameter()
115
    {
116 1
        $num = array_push($this->postParameters, new Parameter());
117
118 1
        return $this->postParameters[$num - 1];
119
    }
120
121
    /**
122
     * Load the necessary environment for running this task.
123
     *
124
     * @throws BuildException
125
     */
126 8
    public function init()
127
    {
128 8
        parent::init();
129
130 8
        $this->regexp = new Regexp();
131 8
    }
132
133
    /**
134
     * Creates, configures, and sends a request
135
     *
136
     * @param array $options
137
     * @return ResponseInterface
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 ConsoleOutput()), new \GuzzleHttp\MessageFormatter()));
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