Skip to content

Commit 73da18b

Browse files
author
Martin Brecht-Precht
committed
Extended exception handing.
Updated the readme.
1 parent b84cbda commit 73da18b

21 files changed

+318
-32
lines changed

README.md

Lines changed: 61 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ use BasicHttpClient\Request\Request;
224224
225225
// Configuring and performing a Request
226226
$request = new Request();
227-
$response = $request
227+
$request
228228
->setUserAgent('PHP Basic HTTP Client Test 1.0')
229229
->setEndpoint('https://yourapihere-com-98yq3775xff0.runscope.net/')
230230
->setPort(443)
@@ -276,7 +276,7 @@ $basicAuthentication = new BasicAuthentication('username', 'password');
276276
277277
// Adding the authentication instance to the Request
278278
$request = new Request();
279-
$response = $request->addAuthentication($basicAuthentication);
279+
$request->addAuthentication($basicAuthentication);
280280
```
281281

282282
#### SSL Client Certificate Authentication
@@ -296,14 +296,32 @@ $clientCertificateAuthentication = new ClientCertificateAuthentication(
296296
297297
// Adding the authentication instance to the Request
298298
$request = new Request();
299-
$response = $request->addAuthentication($clientCertificateAuthentication);
299+
$request->addAuthentication($clientCertificateAuthentication);
300300
```
301301

302302
---
303303

304304
## Reading from the resulting Response instance
305305

306-
TODO
306+
### Getting the response object
307+
308+
If using the `BasicHttpClient` the response object is returned by the termination methods listed above. If directly using the Request instance, you can get the Response object via a getter.
309+
310+
```{php}
311+
$response = $request->getResponse();
312+
313+
// Reading the HTTP status code as integer; will return `200`
314+
echo print_r($response->getStatusCode(), true).PHP_EOL;
315+
316+
// Reading the HTTP status text as string; will return `HTTP/1.1 200 OK`
317+
echo print_r($response->getStatusText(), true).PHP_EOL;
318+
319+
// Reading the HTTP response headers as array of BasicHttpClient\Response\Header\Header objects
320+
echo print_r($response->getHeaders(), true).PHP_EOL;
321+
322+
// Reading the HTTP response body as string
323+
echo print_r($response->getBody(), true).PHP_EOL;
324+
```
307325

308326
---
309327

@@ -315,7 +333,34 @@ TODO
315333

316334
## Getting some transactional statistics
317335

318-
TODO
336+
```
337+
// Getting the statistics BasicHttpClient\Response\Statistics\Statistics object
338+
$statistics = $request->getResponse()->getStatistics();
339+
340+
// Reading the redirection URL if the server responds with an redirect HTTP header and followRedirects is set to false
341+
echo print_r($statistics->getRedirectEndpoint(), true).PHP_EOL;
342+
343+
// Reading the numbers of redirection as integer
344+
echo print_r($statistics->getRedirectCount(), true).PHP_EOL;
345+
346+
// Getting the time in seconds the redirect utilized as float
347+
echo print_r($statistics->getRedirectTime(), true).PHP_EOL;
348+
349+
// Getting the time in seconds that was utilized until the connection was established
350+
echo print_r($statistics->getConnectionEstablishTime(), true).PHP_EOL;
351+
352+
// Getting the time in seconds that was utilized until the DNS hostname lookup was done
353+
echo print_r($statistics->getHostLookupTime(), true).PHP_EOL;
354+
355+
// Getting the time in seconds that was utilized before the first data was sent
356+
echo print_r($statistics->getPreTransferTime(), true).PHP_EOL;
357+
358+
// Getting the time in seconds that was utilized before the first data was received
359+
echo print_r($statistics->getStartTransferTime(), true).PHP_EOL;
360+
361+
// Getting the time in seconds that was utilized to perfom the request an read the response
362+
echo print_r($statistics->getTotalTime(), true).PHP_EOL;
363+
```
319364

320365
---
321366

@@ -333,6 +378,17 @@ Take a look at the [PHP JSON HTTP Client](https://github.com/markenwerk/php-json
333378
PHP Basic HTTP Client provides different exceptions – also provided by the PHP Common Exceptions project – for proper handling.
334379
You can find more information about [PHP Common Exceptions at Github](https://github.com/markenwerk/php-common-exceptions).
335380

381+
### Exceptions to be expected
382+
383+
In general you should expect that any setter method could thrown an `\InvalidArgumentException`. The following exceptions could get thrown while using PHP Basic HTTP Client.
384+
385+
- `CommonException\IoException\FileReadableException` on configuring a `ClientCertificateAuthentication`instance
386+
- `BasicHttpClient\Exception\HttpRequestAuthenticationException` on performing a request
387+
- `BasicHttpClient\Exception\HttpRequestException` on performing a request
388+
- `CommonException\NetworkException\ConnectionTimeoutException` on performing a request
389+
- `CommonException\NetworkException\CurlException` on performing a request
390+
391+
336392
## Contribution
337393

338394
Contributing to our projects is always very appreciated.

detaild.php

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
namespace Project;
44

55
use BasicHttpClient\Request\Authentication\BasicAuthentication;
6-
use BasicHttpClient\Request\Authentication\ClientCertificateAuthentication;
76
use BasicHttpClient\Request\Message\Body\Body;
87
use BasicHttpClient\Request\Message\Cookie\Cookie;
98
use BasicHttpClient\Request\Message\Header\Header;
@@ -45,34 +44,41 @@
4544
->addCookie(new Cookie('PHPSESSID', '<MY_SESSION_ID>'))
4645
->setBody($messageBody);
4746

48-
$header1 = $message->getHeaderByName('Content-Type');
49-
$header2 = $message->getHeaderByName('content-type');
50-
$header3 = $message->getHeaderByName('CONTENT-Type');
51-
5247
$message->addHeader(new Header('Custom-Header', array('CustomHeaderValue')));
5348
$message->addAdditionalHeader(new Header('Custom-Header', array('AnotherCustomHeaderValue')));
5449

5550
$request = new Request();
56-
$response = $request
51+
$request
5752
->setUserAgent('PHP Basic HTTP Client Test 1.0')
5853
->setEndpoint('https://yourapihere-com-98yq3775xff0.runscope.net/')
5954
->setPort(443)
6055
->addAuthentication(new BasicAuthentication('username', 'password'))
6156
->setQueryParameters(
6257
array(
6358
'paramName1' => 'paramValue1',
64-
'paramName2' => 'paramValue2'
59+
'paramName2' => 'paramValue2',
60+
'paramName3' => true,
61+
'paramName4' => 42,
6562
)
6663
)
6764
->setMethod(Request::REQUEST_METHOD_POST)
6865
->setTransport($transport)
6966
->setMessage($message)
7067
->perform();
7168

72-
$auth = new ClientCertificateAuthentication(
73-
'/var/www/project/clientCert/ca.crt',
74-
'/var/www/project/clientCert/client.crt',
75-
'clientCertPassword'
76-
);
69+
$response = $request->getResponse();
70+
echo print_r($response->getStatusCode(), true).PHP_EOL;
71+
echo print_r($response->getStatusText(), true).PHP_EOL;
72+
echo print_r($response->getHeaders(), true).PHP_EOL;
73+
echo print_r($response->getBody(), true).PHP_EOL;
74+
75+
$statistics = $response->getStatistics();
76+
echo print_r($statistics->getRedirectEndpoint(), true).PHP_EOL;
77+
echo print_r($statistics->getRedirectCount(), true).PHP_EOL;
78+
echo print_r($statistics->getRedirectTime(), true).PHP_EOL;
7779

78-
print_r($request->getEffectiveRawHeader());
80+
echo print_r($statistics->getConnectionEstablishTime(), true).PHP_EOL;
81+
echo print_r($statistics->getHostLookupTime(), true).PHP_EOL;
82+
echo print_r($statistics->getPreTransferTime(), true).PHP_EOL;
83+
echo print_r($statistics->getStartTransferTime(), true).PHP_EOL;
84+
echo print_r($statistics->getTotalTime(), true).PHP_EOL;

src/BasicHttpClient.php

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ class BasicHttpClient implements HttpClientInterface
3131
*/
3232
public function __construct($endpoint)
3333
{
34+
if (!is_string($endpoint)) {
35+
$argumentType = (is_object($endpoint)) ? get_class($endpoint) : gettype($endpoint);
36+
throw new \InvalidArgumentException('Expected the endpoint as string. Got ' . $argumentType);
37+
}
3438
$urlUtil = new UrlUtil();
3539
$transport = new HttpTransport();
3640
if ($urlUtil->getScheme($endpoint) == 'HTTPS') {
@@ -52,7 +56,7 @@ public function getRequest()
5256
}
5357

5458
/**
55-
* @param string[] $queryParameters
59+
* @param mixed[] $queryParameters
5660
* @return ResponseInterface
5761
* @throws \CommonException\NetworkException\Base\NetworkException
5862
* @throws \CommonException\NetworkException\ConnectionTimeoutException
@@ -67,7 +71,7 @@ public function get(array $queryParameters = null)
6771
}
6872

6973
/**
70-
* @param string[] $queryParameters
74+
* @param mixed[] $queryParameters
7175
* @return ResponseInterface
7276
* @throws \CommonException\NetworkException\Base\NetworkException
7377
* @throws \CommonException\NetworkException\ConnectionTimeoutException
@@ -139,7 +143,7 @@ public function patch(array $patchData = null)
139143
}
140144

141145
/**
142-
* @param string[] $queryParameters
146+
* @param mixed[] $queryParameters
143147
* @return ResponseInterface
144148
* @throws \CommonException\NetworkException\Base\NetworkException
145149
* @throws \CommonException\NetworkException\ConnectionTimeoutException
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
3+
namespace BasicHttpClient\Exception;
4+
5+
/**
6+
* Class HttpRequestAuthenticationException
7+
*
8+
* @package BasicHttpClient\Exception
9+
*/
10+
class HttpRequestAuthenticationException extends \Exception
11+
{
12+
13+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
3+
namespace BasicHttpClient\Exception;
4+
5+
/**
6+
* Class HttpRequestException
7+
*
8+
* @package BasicHttpClient\Exception
9+
*/
10+
class HttpRequestException extends \Exception
11+
{
12+
13+
}

src/HttpClientInterface.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,13 @@ interface HttpClientInterface
1919
public function getRequest();
2020

2121
/**
22-
* @param string[] $queryParameters
22+
* @param mixed[] $queryParameters
2323
* @return ResponseInterface
2424
*/
2525
public function get(array $queryParameters = null);
2626

2727
/**
28-
* @param string[] $queryParameters
28+
* @param mixed[] $queryParameters
2929
* @return ResponseInterface
3030
*/
3131
public function head(array $queryParameters = null);
@@ -49,7 +49,7 @@ public function put(array $putData = null);
4949
public function patch(array $patchData = null);
5050

5151
/**
52-
* @param string[] $queryParameters
52+
* @param mixed[] $queryParameters
5353
* @return ResponseInterface
5454
*/
5555
public function delete(array $queryParameters = null);

src/Request/AbstractRequest.php

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace BasicHttpClient\Request;
44

5+
use BasicHttpClient\Exception\HttpRequestException;
56
use BasicHttpClient\Request\Authentication\AuthenticationInterface;
67
use BasicHttpClient\Request\Message\MessageInterface;
78
use BasicHttpClient\Request\Message\Header\Header;
@@ -12,12 +13,11 @@
1213
use BasicHttpClient\Util\UrlUtil;
1314
use CommonException\NetworkException\Base\NetworkException;
1415
use CommonException\NetworkException\ConnectionTimeoutException;
16+
use CommonException\NetworkException\CurlException;
1517

1618
/**
1719
* Class Request
1820
*
19-
* TODO: Add query params to be concatenated to the endpoints URL for performing GET, HEAD and DELETE requests.
20-
*
2121
* @package BasicHttpClient\Request
2222
*/
2323
abstract class AbstractRequest implements RequestInterface
@@ -216,10 +216,14 @@ public function addQueryParameter($parameterName, $parameterValue)
216216
*/
217217
public function setQueryParameters($queryParameters)
218218
{
219-
foreach ($queryParameters as $parameterName => $parameterValue) {
220-
if (!is_string($parameterName) || !is_string($parameterValue)) {
221-
throw new \InvalidArgumentException('Query parameters have to be an associative array.');
219+
foreach ($queryParameters as &$queryParameter) {
220+
if (!is_scalar($queryParameter)) {
221+
$argumentType = (is_object($queryParameter)) ? get_class($queryParameter) : gettype($queryParameter);
222+
throw new \InvalidArgumentException(
223+
'Expected the query parameters as array of scalar values. Got ' . $argumentType
224+
);
222225
}
226+
$queryParameter = (string)$queryParameter;
223227
}
224228
$this->queryParameters = $queryParameters;
225229
return $this;
@@ -351,6 +355,10 @@ public function countAuthentications()
351355
*/
352356
public function configureCurl($curl)
353357
{
358+
if (!is_resource($curl)) {
359+
$argumentType = (is_object($curl)) ? get_class($curl) : gettype($curl);
360+
throw new \InvalidArgumentException('curl argument invalid. Expected a valid resource. Got ' . $argumentType);
361+
}
354362
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
355363
curl_setopt($curl, CURLOPT_HEADER, true);
356364
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
@@ -386,7 +394,9 @@ public function perform()
386394
$this->getTransport()->configureCurl($curl);
387395
$this->getMessage()->configureCurl($curl);
388396
for ($i = 0; $i < count($this->authentications); $i++) {
389-
$this->authentications[$i]->configureCurl($curl);
397+
$this->authentications[$i]
398+
->validate($this)
399+
->configureCurl($curl);
390400
}
391401
// Execute request
392402
$responseBody = curl_exec($curl);
@@ -404,7 +414,7 @@ public function perform()
404414
throw new ConnectionTimeoutException('The request timed out with message: ' . $curlErrorMessage);
405415
break;
406416
default:
407-
throw new NetworkException('The request failed with message: ' . $curlErrorMessage);
417+
throw new CurlException('The request failed with message: ' . $curlErrorMessage);
408418
break;
409419
}
410420
}
@@ -475,7 +485,7 @@ protected function prePerform()
475485
{
476486
$urlUtil = new UrlUtil();
477487
if ($urlUtil->getScheme($this->getEndpoint()) == 'HTTPS' && !$this->getTransport() instanceof HttpsTransport) {
478-
throw new \Exception('Transport misconfiguration. Use HttpsTransport for HTTPS requests.');
488+
throw new HttpRequestException('Transport misconfiguration. Use HttpsTransport for HTTPS requests.');
479489
}
480490
}
481491

src/Request/Authentication/AuthenticationInterface.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace BasicHttpClient\Request\Authentication;
44

55
use BasicHttpClient\Request\Base\CurlConfiguratorInterface;
6+
use BasicHttpClient\Request\RequestInterface;
67

78
/**
89
* Interface AuthenticationInterface
@@ -12,4 +13,10 @@
1213
interface AuthenticationInterface extends CurlConfiguratorInterface
1314
{
1415

16+
/**
17+
* @param RequestInterface $request
18+
* @return $this
19+
*/
20+
public function validate(RequestInterface $request);
21+
1522
}

src/Request/Authentication/BasicAuthentication.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace BasicHttpClient\Request\Authentication;
44

5+
use BasicHttpClient\Request\RequestInterface;
6+
57
/**
68
* Class BasicAuthentication
79
*
@@ -69,12 +71,25 @@ public function setPassword($password)
6971
return $this;
7072
}
7173

74+
/**
75+
* @param RequestInterface $request
76+
* @return $this
77+
*/
78+
public function validate(RequestInterface $request)
79+
{
80+
return $this;
81+
}
82+
7283
/**
7384
* @param resource $curl
7485
* @return $this
7586
*/
7687
public function configureCurl($curl)
7788
{
89+
if (!is_resource($curl)) {
90+
$argumentType = (is_object($curl)) ? get_class($curl) : gettype($curl);
91+
throw new \InvalidArgumentException('curl argument invalid. Expected a valid resource. Got ' . $argumentType);
92+
}
7893
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
7994
curl_setopt($curl, CURLOPT_USERPWD, $this->username . ':' . $this->password);
8095
return $this;

0 commit comments

Comments
 (0)