1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace RicardoFiorani\Validator; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Psr7\Request; |
6
|
|
|
use Psr\Http\Client\ClientInterface; |
7
|
|
|
use RicardoFiorani\Validator\Response\ValidationResponseFactory; |
8
|
|
|
use RicardoFiorani\Validator\Response\ValidationResponseInterface; |
9
|
|
|
|
10
|
|
|
class Validator implements ValidatorInterface |
11
|
|
|
{ |
12
|
|
|
const CLOUDFLARE_AMP_VALIDATOR_ENDPOINT = 'https://amp.cloudflare.com/q/'; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var ClientInterface |
16
|
|
|
*/ |
17
|
|
|
private $httpClient; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var ValidationResponseFactory |
21
|
|
|
*/ |
22
|
|
|
private $responseFactory; |
23
|
|
|
|
24
|
4 |
|
public function __construct(ClientInterface $httpClient) |
25
|
|
|
{ |
26
|
4 |
|
$this->setHttpClient($httpClient); |
27
|
4 |
|
$this->responseFactory = new ValidationResponseFactory(); |
28
|
4 |
|
} |
29
|
|
|
|
30
|
4 |
|
public function setHttpClient(ClientInterface $httpClient) |
31
|
|
|
{ |
32
|
4 |
|
$this->httpClient = $httpClient; |
33
|
4 |
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @throws \Psr\Http\Client\ClientExceptionInterface |
37
|
|
|
*/ |
38
|
2 |
View Code Duplication |
public function validateUrl(string $url): ValidationResponseInterface |
|
|
|
|
39
|
|
|
{ |
40
|
2 |
|
$url = $this->normaliseUrl($url); |
41
|
2 |
|
$request = new Request('GET', self::CLOUDFLARE_AMP_VALIDATOR_ENDPOINT . $url); |
42
|
2 |
|
$response = $this->httpClient->sendRequest($request); |
43
|
|
|
|
44
|
2 |
|
return $this->responseFactory->create($response); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @throws \Psr\Http\Client\ClientExceptionInterface |
49
|
|
|
*/ |
50
|
2 |
View Code Duplication |
public function validateContent(string $content): ValidationResponseInterface |
|
|
|
|
51
|
|
|
{ |
52
|
2 |
|
$request = new Request('POST', self::CLOUDFLARE_AMP_VALIDATOR_ENDPOINT, [], $content); |
53
|
2 |
|
$response = $this->httpClient->sendRequest($request); |
54
|
|
|
|
55
|
2 |
|
return $this->responseFactory->create($response); |
56
|
|
|
} |
57
|
|
|
|
58
|
2 |
|
private function normaliseUrl(string $url): string |
59
|
|
|
{ |
60
|
2 |
|
return str_replace(['http://', 'https://'], '', strtolower($url)); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.