|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* File: ManufacturerHtmlScrapper.php |
|
4
|
|
|
* |
|
5
|
|
|
* @author Maciej Sławik <[email protected]> |
|
6
|
|
|
* Github: https://github.com/maciejslawik |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace MSlwk\Otomoto\App\Manufacturer\Scrapper; |
|
10
|
|
|
|
|
11
|
|
|
use MSlwk\Otomoto\App\Manufacturer\Data\ManufacturerDTO; |
|
12
|
|
|
use MSlwk\Otomoto\App\Manufacturer\Data\ManufacturerDTOArray; |
|
13
|
|
|
use Symfony\Component\DomCrawler\Crawler; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Class ManufacturerHtmlScrapper |
|
17
|
|
|
* @package MSlwk\Otomoto\App\Manufacturer\Scrapper |
|
18
|
|
|
*/ |
|
19
|
|
|
class ManufacturerHtmlScrapper implements ManufacturerHtmlScrapperInterface |
|
20
|
|
|
{ |
|
21
|
|
|
const MANUFACTURER_SELECT_CSS_SELECTOR = 'select[name="search[filter_enum_make]"]'; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @param string $html |
|
25
|
|
|
* @return ManufacturerDTOArray |
|
26
|
|
|
*/ |
|
27
|
1 |
|
public function scrapManufacturers(string $html): ManufacturerDTOArray |
|
28
|
|
|
{ |
|
29
|
1 |
|
$manufacturerDTOArray = new ManufacturerDTOArray(); |
|
30
|
|
|
|
|
31
|
1 |
|
$manufacturerSelectOptions = $this->getManufacturersSelectOptions($html); |
|
32
|
|
|
$manufacturerSelectOptions->each(function (Crawler $crawler) use (&$manufacturerDTOArray) { |
|
33
|
1 |
|
$optionNode = $crawler->getNode(0); |
|
34
|
1 |
|
if ($optionNode->getAttribute('value')) { |
|
35
|
1 |
|
$manufacturerDTO = new ManufacturerDTO($this->retrieveManufacturerNameFromOptionText($optionNode)); |
|
36
|
1 |
|
$manufacturerDTOArray->add($manufacturerDTO); |
|
37
|
|
|
} |
|
38
|
1 |
|
}); |
|
39
|
|
|
|
|
40
|
1 |
|
return $manufacturerDTOArray; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* @param string $html |
|
45
|
|
|
* @return Crawler |
|
46
|
|
|
*/ |
|
47
|
1 |
|
private function getManufacturersSelectOptions(string $html): Crawler |
|
48
|
|
|
{ |
|
49
|
1 |
|
$crawler = new Crawler($html); |
|
50
|
1 |
|
$manufacturerSelectField = $crawler->filter($this->getManufacturerSelectCssSelector())->first(); |
|
51
|
1 |
|
$manufacturerSelectOptions = $manufacturerSelectField->filter('option'); |
|
52
|
1 |
|
return $manufacturerSelectOptions; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* @return string |
|
57
|
|
|
*/ |
|
58
|
1 |
|
private function getManufacturerSelectCssSelector(): string |
|
59
|
|
|
{ |
|
60
|
1 |
|
return self::MANUFACTURER_SELECT_CSS_SELECTOR; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @param $optionNode |
|
65
|
|
|
* @return string |
|
66
|
|
|
*/ |
|
67
|
1 |
|
private function retrieveManufacturerNameFromOptionText($optionNode): string |
|
68
|
|
|
{ |
|
69
|
1 |
|
return preg_replace('/\s\([^)]+\)/', '', $optionNode->nodeValue); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|