1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace juniorb2ss\DeathByCaptcha\Abstracts; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
6
|
|
|
use juniorb2ss\DeathByCaptcha\Exceptions\AccessDeniedException; |
7
|
|
|
use juniorb2ss\DeathByCaptcha\Exceptions\CaptchaNotFoundException; |
8
|
|
|
use juniorb2ss\DeathByCaptcha\Exceptions\InternalServiceException; |
9
|
|
|
use juniorb2ss\DeathByCaptcha\Exceptions\InvalidCaptchaException; |
10
|
|
|
use juniorb2ss\DeathByCaptcha\Exceptions\InvalidServiceResponseException; |
11
|
|
|
use juniorb2ss\DeathByCaptcha\Exceptions\ServiceOverloadException; |
12
|
|
|
|
13
|
|
|
abstract class HttpHandlerResponseAbstract |
14
|
|
|
{ |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Define o content que deverá ser a resposta |
18
|
|
|
* do serviço |
19
|
|
|
* @var string |
20
|
|
|
*/ |
21
|
|
|
protected $contentTypeOk = 'application/json; charset=utf8'; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Executa verificação da integridade da resposta |
25
|
|
|
* desde do cabeçalho do response até o conteúdo |
26
|
|
|
* @return void|ClientException |
27
|
|
|
*/ |
28
|
75 |
|
protected function handlerHttpResponseIsOk() |
29
|
|
|
{ |
30
|
75 |
|
$response = $this->response; |
|
|
|
|
31
|
75 |
|
$contentType = $response->getHeaderLine('Content-Type'); |
32
|
|
|
|
33
|
75 |
|
$statusCode = $response->getStatusCode(); |
34
|
|
|
|
35
|
|
|
// Efetua o tratamento do status code do response |
36
|
|
|
switch ($statusCode) { |
37
|
75 |
|
case 400: |
38
|
3 |
|
throw new InvalidCaptchaException; |
39
|
|
|
break; |
|
|
|
|
40
|
72 |
|
case 403: |
41
|
3 |
|
throw new AccessDeniedException; |
42
|
|
|
break; |
|
|
|
|
43
|
69 |
|
case 404: |
44
|
3 |
|
throw new CaptchaNotFoundException; |
45
|
|
|
break; |
|
|
|
|
46
|
66 |
|
case 413: |
47
|
3 |
|
throw new InvalidCaptchaException; |
48
|
|
|
break; |
|
|
|
|
49
|
63 |
|
case 500: |
50
|
3 |
|
throw new InternalServiceException; |
51
|
60 |
|
case 503: |
52
|
3 |
|
throw new ServiceOverloadException; |
53
|
|
|
break; |
|
|
|
|
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
// Uma coisa básica é verificar o tipo do conteúdo |
57
|
|
|
// da resposta HTTP. |
58
|
|
|
// Parece a principio algo meio "desnecessário" |
59
|
|
|
// já que se a resposta for ok e for passado o |
60
|
|
|
// accept de json, técnicamente deverá retornar |
61
|
|
|
// o content type como json |
62
|
|
|
// mas... nunca se sabe, né? |
63
|
57 |
|
if (($contentType !== $this->contentTypeOk) or (empty((string)$response->getBody()))) { |
|
|
|
|
64
|
6 |
|
throw new InvalidServiceResponseException; |
65
|
|
|
} |
66
|
51 |
|
} |
67
|
|
|
} |
68
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: