Lines
93.10%
27 / 29
Methods
83.33%
5 / 6
Classes
0.00%
0 / 1
| Name | Lines | Methods | CRAP | ||||
|---|---|---|---|---|---|---|---|
| __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 | ||
| 12 | readonly 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 | } |