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 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Districts\Scraper\Infrastructure; | |
| 6 | ||
| 7 | use Districts\Scraper\Domain\Exception\FetchingException; | |
| 8 | use Districts\Scraper\Domain\HtmlFetcher; | |
| 9 | use Fig\Http\Message\StatusCodeInterface as StatusCode; | |
| 10 | use Psr\Http\Client\ClientInterface; | |
| 11 | use Psr\Http\Message\RequestFactoryInterface; | |
| 12 | ||
| 13 | final 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 | } |