Validator   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 6
dl 0
loc 62
ccs 0
cts 20
cp 0
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A setHttpClient() 0 4 1
A validateUrl() 0 8 1
A validateContent() 0 9 1
A normaliseUrl() 0 4 1
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