1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace RicardoFiorani\Validator; |
4
|
|
|
|
5
|
|
|
use Http\Factory\Diactoros\RequestFactory; |
6
|
|
|
use Http\Factory\Diactoros\StreamFactory; |
7
|
|
|
use Psr\Http\Client\ClientInterface; |
8
|
|
|
use Psr\Http\Message\RequestFactoryInterface; |
9
|
|
|
use RicardoFiorani\Validator\Response\ValidationResponseFactory; |
10
|
|
|
use RicardoFiorani\Validator\Response\ValidationResponseInterface; |
11
|
|
|
|
12
|
|
|
class Validator implements ValidatorInterface |
13
|
|
|
{ |
14
|
|
|
const CLOUDFLARE_AMP_VALIDATOR_ENDPOINT = 'https://amp.cloudflare.com/q/'; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var ClientInterface |
18
|
|
|
*/ |
19
|
|
|
private $httpClient; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var ValidationResponseFactory |
23
|
|
|
*/ |
24
|
|
|
private $responseFactory; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var RequestFactoryInterface |
28
|
|
|
*/ |
29
|
|
|
private $requestFactory; |
30
|
|
|
|
31
|
|
|
public function __construct(ClientInterface $httpClient, ?RequestFactoryInterface $requestFactory = null) |
32
|
|
|
{ |
33
|
|
|
$this->setHttpClient($httpClient); |
34
|
|
|
$this->responseFactory = new ValidationResponseFactory(); |
35
|
|
|
|
36
|
|
|
$this->requestFactory = $requestFactory ?? new RequestFactory(); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function setHttpClient(ClientInterface $httpClient) |
40
|
|
|
{ |
41
|
|
|
$this->httpClient = $httpClient; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @throws \Psr\Http\Client\ClientExceptionInterface |
46
|
|
|
*/ |
47
|
|
|
public function validateUrl(string $url): ValidationResponseInterface |
48
|
|
|
{ |
49
|
|
|
$url = $this->normaliseUrl($url); |
50
|
|
|
$request = $this->requestFactory->createRequest('GET', self::CLOUDFLARE_AMP_VALIDATOR_ENDPOINT . $url); |
51
|
|
|
$response = $this->httpClient->sendRequest($request); |
52
|
|
|
|
53
|
|
|
return $this->responseFactory->create($response); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @throws \Psr\Http\Client\ClientExceptionInterface |
58
|
|
|
*/ |
59
|
|
|
public function validateContent(string $content): ValidationResponseInterface |
60
|
|
|
{ |
61
|
|
|
$request = $this->requestFactory->createRequest('POST', self::CLOUDFLARE_AMP_VALIDATOR_ENDPOINT); |
62
|
|
|
$requestWithBody = $request->withBody((new StreamFactory())->createStream($content)); |
63
|
|
|
|
64
|
|
|
$response = $this->httpClient->sendRequest($requestWithBody); |
65
|
|
|
|
66
|
|
|
return $this->responseFactory->create($response); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
private function normaliseUrl(string $url): string |
70
|
|
|
{ |
71
|
|
|
return str_replace(['http://', 'https://'], '', strtolower($url)); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|