Lines 93.10% 27 / 29
Functions and Methods 83.33% 5 / 6
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
DistrictParser 93.10% 27 / 29 83.33% 5 / 6 9.03 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 parse 100.00% 4 / 4 100.00% 1 / 1 1
 getName 100.00% 3 / 3 100.00% 1 / 1 1
 getArea 100.00% 7 / 7 100.00% 1 / 1 1
 getPopulation 100.00% 4 / 4 100.00% 1 / 1 1
 getSingleMatch 80.00% 8 / 10 0.00% 0 / 1 4.13
1<?php
2
3declare(strict_types=1);
4
5namespace Districts\Scraper\Domain\Krakow;
6
7use Districts\Scraper\Domain\DistrictDTO;
8use Districts\Scraper\Domain\Exception\InvalidHtmlException;
9use Districts\Scraper\Domain\Exception\ParsingException;
10use Districts\Scraper\Domain\HtmlFinder;
11
12readonly class DistrictParser
13{
14    public function __construct(
15        private HtmlFinder $htmlFinder,
16    ) {
17    }
18
19    public function parse(string $html): DistrictDTO
20    {
21        $name = $this->getName($html);
22        $area = $this->getArea($html);
23        $population = $this->getPopulation($html);
24        return new DistrictDTO($name, $area, $population);
25    }
26
27    private function getName(string $html): string
28    {
29        $xpath = "//h1[@class='bip' and starts-with(., 'Dzielnica ')]";
30        $regexp = "/^[[:space:]]*Dzielnica[[:space:]]+[IVXLCDM]+[[:space:]]+(.*)[[:space:]]+\\(.*$/uU";
31        return $this->getSingleMatch($html, $xpath, $regexp);
32    }
33
34    private function getArea(string $html): float
35    {
36        $xpath = "//p[contains(., 'Powierzchnia dzielnicy:')]/strong";
37        $regexp = "/([0-9]+(,[0-9]+){0,1})[[:space:]]+ha/";
38
39        $area = $this->getSingleMatch($html, $xpath, $regexp);
40        $area = str_replace(",", ".", $area); // decimal point
41        $area = floatval($area);
42        $area = $area / 100; // unit conversion: ha to square km
43
44        return $area;
45    }
46
47    private function getPopulation(string $html): int
48    {
49        $xpath = "//p[contains(., 'Liczba mieszka')]/strong";
50        $regexp = "/^[[:space:]]*([0-9]+)[[:space:]]*$/u";
51        $text = $this->getSingleMatch($html, $xpath, $regexp);
52        return intval($text);
53    }
54
55    private function getSingleMatch(string $html, string $xpath, string $regexp): string
56    {
57        try {
58            $nodes = $this->htmlFinder->findNodes($html, $xpath);
59        } catch (InvalidHtmlException) {
60            throw new ParsingException();
61        }
62        if (count($nodes) !== 1) {
63            throw new ParsingException();
64        }
65        $value = $nodes[0]->textContent;
66        $matches = [];
67        if (preg_match($regexp, $value, $matches) !== 1) {
68            throw new ParsingException();
69        }
70        return $matches[1];
71    }
72}