-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathHtmlScraper.php
More file actions
186 lines (147 loc) · 5.64 KB
/
Copy pathHtmlScraper.php
File metadata and controls
186 lines (147 loc) · 5.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
<?php
declare(strict_types=1);
namespace App\Service\Scraper;
use App\Entity\Datum;
use App\Enum\DatumTypeEnum;
use App\Enum\VisibilityEnum;
use App\Model\ScrapingCollection;
use App\Model\ScrapingItem;
use App\Model\ScrapingWish;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Intl\Countries;
use Symfony\Component\HttpClient\CurlHttpClient;
use Twig\Environment;
abstract class HtmlScraper
{
protected ?CurlHttpClient $client = null;
public function __construct(
protected Environment $twig
) {
$this->client = new CurlHttpClient();
}
protected function getCrawler(ScrapingItem|ScrapingCollection|ScrapingWish $scraping): Crawler
{
if ($scraping->getFile() instanceof UploadedFile) {
$content = $scraping->getFile()->getContent();
} else {
$headers = [];
foreach ($scraping->getScraper()->getHeaders() as $header) {
$headers[$header['header']] = $header['value'];
}
$response = $this->client->request('GET', $scraping->getUrl(), [
'headers' => $headers
]);
if (200 !== $response->getStatusCode()) {
throw new \Exception('Api error: ' . $response->getStatusCode() . ' - ' . $response->getContent());
}
$content = $response->getContent();
}
return new Crawler($content);
}
protected function extract(?string $template, string $type, Crawler $crawler, $scraping): ?string
{
if (!$template) {
return '';
}
$values = [];
preg_match_all('/#(.*?)#/', $template, $matches);
foreach ($matches[1] as $xPath) {
$results = $crawler->evaluate($xPath);
if ($results instanceof Crawler) {
$results = $results->each(static function (Crawler $node): string {
return $node->text();
});
}
foreach ($results as $key => $result) {
if (isset($values[$key])) {
$values[$key] = str_replace("#{$xPath}#", $result, $values[$key]);
} else {
$values[$key] = str_replace("#{$xPath}#", $result, $template);
}
}
// Remove xPath from result in case nothing was found
foreach ($values as &$value) {
$value = str_replace("#{$xPath}#", '', $value);
}
}
return $this->formatValues($values, $type, $scraping);
}
protected function scrapData(ScrapingItem|ScrapingCollection|ScrapingWish $scraping, Crawler $crawler, string $entityType): array
{
$data = [];
foreach ($scraping->getDataToScrap() as $key => $dataToScrap) {
$value = $this->extract($dataToScrap->getPath(), $dataToScrap->getType(), $crawler, $scraping);
$datum = (new Datum())
->setValue($value)
->setLabel($dataToScrap->getName())
->setType($dataToScrap->getType())
->setPosition((int) $key)
;
$data[] = [
$dataToScrap->getType(),
$dataToScrap->getName(),
$this->twig->render('App/Datum/_datum.html.twig', [
'entity' => $entityType,
'iteration' => '__placeholder__',
'type' => $dataToScrap->getType(),
'datum' => $datum,
'label' => $datum->getLabel(),
'choiceList' => $datum->getChoiceList(),
'visibility' => $datum->getVisibility()
])
];
}
return $data;
}
protected function formatValues(?array $values, string $type, $scraping): ?string
{
if ($values === null || $values === []) {
return null;
}
if ($type === DatumTypeEnum::TYPE_TEXT) {
return implode(', ', $values);
}
if ($type === DatumTypeEnum::TYPE_LIST) {
return json_encode($values);
}
if ($type === DatumTypeEnum::TYPE_TEXTAREA) {
return $values[0];
}
if ($type === DatumTypeEnum::TYPE_COUNTRY) {
$value = array_shift($values);
// Try to match alpha2 code
if (\strlen($value) === 2 && Countries::exists(strtoupper($value))) {
return strtoupper($value);
}
// Try to match alpha3 code
if (\strlen($value) === 3 && Countries::alpha3CodeExists(strtoupper($value))) {
return strtoupper($value);
}
// Else try to match the country name
return array_flip(Countries::getNames())[$value] ?? null;
}
if ($type === DatumTypeEnum::TYPE_IMAGE) {
return $this->guessHost($values[0], $scraping);
}
if ($type === DatumTypeEnum::TYPE_LINK) {
return $this->guessHost($values[0], $scraping);
}
if ($type === DatumTypeEnum::TYPE_PRICE) {
return $values[0];
}
return null;
}
protected function guessHost(?string $url, ScrapingItem|ScrapingCollection|ScrapingWish $scraping): ?string
{
if ($url === null || $scraping->getUrl() === null) {
return null;
}
$urlElements = parse_url($url);
if (!isset($urlElements['host'])) {
$scrapingUrlElements = parse_url($scraping->getUrl());
$url = $scrapingUrlElements['scheme'] . '://' . $scrapingUrlElements['host'] . $urlElements['path'];
}
return $url;
}
}