Lines 100.00% 9 / 9
Functions and Methods 100.00% 2 / 2
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
PsrHtmlFetcher 100.00% 9 / 9 100.00% 2 / 2 4 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 fetchHtml 100.00% 8 / 8 100.00% 1 / 1 3
1<?php
2
3declare(strict_types=1);
4
5namespace Districts\Scraper\Infrastructure;
6
7use Districts\Scraper\Domain\Exception\FetchingException;
8use Districts\Scraper\Domain\HtmlFetcher;
9use Fig\Http\Message\StatusCodeInterface as StatusCode;
10use Psr\Http\Client\ClientInterface;
11use Psr\Http\Message\RequestFactoryInterface;
12
13final readonly class PsrHtmlFetcher implements HtmlFetcher
14{
15    public function __construct(
16        private ClientInterface $httpClient,
17        private RequestFactoryInterface $requestFactory,
18    ) {
19    }
20
21    public function fetchHtml(string $url): string
22    {
23        $request = $this->requestFactory->createRequest("GET", $url);
24        $response = $this->httpClient->sendRequest($request);
25        if ($response->getStatusCode() !== StatusCode::STATUS_OK) {
26            throw new FetchingException();
27        }
28        $contentType = $response->getHeader("content-type")[0];
29        if (explode(";", $contentType)[0] !== "text/html") {
30            throw new FetchingException();
31        }
32        return (string) $response->getBody();
33    }
34}