Passed
Push — master ( b5ca42...8fe651 )
by Siad
05:05
created

HttpTask::request()   B

Complexity

Conditions 7
Paths 24

Size

Total Lines 32
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7.0099

Importance

Changes 0
Metric Value
cc 7
eloc 16
nc 24
nop 1
dl 0
loc 32
ccs 16
cts 17
cp 0.9412
crap 7.0099
rs 8.8333
c 0
b 0
f 0
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\Client;
21
use GuzzleHttp\Exception\GuzzleException;
22
use GuzzleHttp\HandlerStack;
23
use Phing\Exception\BuildException;
24
use Phing\Task;
25
use Phing\Type\Parameter;
26
use Psr\Http\Message\ResponseInterface;
27
28
/**
29
 * Base class for GuzzleHttp-backed tasks
30
 *
31
 * Handles nested <config /> and <header /> tags, contains a method for
32
 * GuzzleHttp instance creation
33
 *
34
 * @package phing.tasks.ext
35
 * @author  Alexey Borzov <[email protected]>
36
 */
37
abstract class HttpTask extends Task
38
{
39
    /**
40
     * Holds the request URL
41
     *
42
     * @var string
43
     */
44
    protected $url = null;
45
46
    /**
47
     * Holds additional header data
48
     *
49
     * @var Parameter[]
50
     */
51
    protected $headers = [];
52
53
    /**
54
     * Holds additional config data for GuzzleHttp
55
     *
56
     * @var Parameter[]
57
     */
58
    protected $configData = [];
59
60
    /**
61
     * Holds the request method
62
     *
63
     * @var string
64
     */
65
    protected $method = 'GET';
66
67
    /**
68
     * Holds the authentication user name
69
     *
70
     * @var string
71
     */
72
    protected $authUser = '';
73
74
    /**
75
     * Holds the authentication password
76
     *
77
     * @var string
78
     */
79
    protected $authPassword = '';
80
81
    /**
82
     * Holds the authentication scheme
83
     *
84
     * @var string
85
     */
86
    protected $authScheme = 'basic';
87
88
    /**
89
     * @var HandlerStack
90
     */
91
    protected static $handlerStack = null;
92
93
    /**
94
     * @return HandlerStack
95
     */
96 14
    public static function getHandlerStack(): HandlerStack
97
    {
98 14
        if (self::$handlerStack === null) {
99 1
            self::$handlerStack = HandlerStack::create();
100
        }
101 14
        return self::$handlerStack;
102
    }
103
104
    /**
105
     * Load the necessary environment for running this task.
106
     *
107
     * @throws BuildException
108
     */
109 23
    public function init()
110
    {
111 23
        if (!class_exists('\GuzzleHttp\Client')) {
112
            throw new BuildException(
113
                get_class($this) . ' depends on Guzzle being installed '
114
                . 'and on include_path.',
115
                $this->getLocation()
116
            );
117
        }
118 23
    }
119
120
    /**
121
     * Sets the request URL
122
     *
123
     * @param string $url
124
     */
125 15
    public function setUrl($url)
126
    {
127 15
        $this->url = $url;
128 15
    }
129
130
    /**
131
     * Creates, configures, and sends a request
132
     *
133
     * @param array $options
134
     * @return ResponseInterface
135
     */
136 14
    protected function request($options = [])
137
    {
138
        // set the authentication data
139 14
        if (!empty($this->authUser)) {
140
            $options['auth'] = [
141 2
                $this->authUser,
142 2
                $this->authPassword,
143 2
                $this->authScheme
144
            ];
145
        }
146
147 14
        if (!empty($this->headers)) {
148 2
            $options['headers'] = [];
149
150 2
            foreach ($this->headers as $header) {
151 2
                $options['headers'][$header->getName()] = $header->getValue();
152
            }
153
        }
154
155 14
        foreach (array_keys($this->getProject()->getProperties()) as $propName) {
156 14
            if (0 === strpos($propName, 'phing.http.')) {
157 3
                $options[substr($propName, 11)] = (string) $this->getProject()->getProperty($propName);
158
            }
159
        }
160
161 14
        foreach ($this->configData as $parameter) {
162 2
            $options[$parameter->getName()] = $parameter->getValue();
163
        }
164
165 14
        $client = new Client(['handler' => self::$handlerStack]);
166
167 14
        return $client->request($this->method, $this->url, $options);
168
    }
169
170
    /**
171
     * Processes the server's response
172
     *
173
     * @param  ResponseInterface $response
174
     * @return void
175
     * @throws BuildException
176
     */
177
    abstract protected function processResponse(ResponseInterface $response);
178
179
    /**
180
     * Makes a HTTP request and processes its response
181
     *
182
     * @throws BuildException
183
     * @throws Exception
184
     */
185 17
    public function main()
186
    {
187 17
        if (!isset($this->url)) {
188 2
            throw new BuildException("Required attribute 'url' is missing");
189
        }
190
191 15
        $this->processResponse($this->request());
192 4
    }
193
194
    /**
195
     * Creates an additional header for this task
196
     *
197
     * @return Parameter The created header
198
     */
199 2
    public function createHeader()
200
    {
201 2
        $num = array_push($this->headers, new Parameter());
202
203 2
        return $this->headers[$num - 1];
204
    }
205
206
    /**
207
     * Creates a config parameter for this task
208
     *
209
     * @return Parameter The created config parameter
210
     */
211 2
    public function createConfig()
212
    {
213 2
        $num = array_push($this->configData, new Parameter());
214
215 2
        return $this->configData[$num - 1];
216
    }
217
218
    /**
219
     * Sets the authentication user name
220
     *
221
     * @param string $user
222
     */
223 2
    public function setAuthUser($user)
224
    {
225 2
        $this->authUser = $user;
226 2
    }
227
228
    /**
229
     * Sets the authentication password
230
     *
231
     * @param string $password
232
     */
233 2
    public function setAuthPassword($password)
234
    {
235 2
        $this->authPassword = $password;
236 2
    }
237
238
    /**
239
     * Sets the authentication scheme
240
     *
241
     * @param string $scheme
242
     */
243 2
    public function setAuthScheme($scheme)
244
    {
245 2
        $this->authScheme = $scheme;
246 2
    }
247
}
248