-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIconsCrawler.php
More file actions
99 lines (81 loc) · 2.4 KB
/
IconsCrawler.php
File metadata and controls
99 lines (81 loc) · 2.4 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
<?php
/**
* Bit&Black Document Crawler.
*
* @author Tobias Köngeter
* @copyright Copyright © Bit&Black
* @link https://www.bitandblack.com
* @license MIT
*/
namespace BitAndBlack\DocumentCrawler\Crawler;
use BitAndBlack\DocumentCrawler\DTO\Icon;
use BitAndBlack\DocumentCrawler\ResourceHandler\PassiveResourceHandler;
use BitAndBlack\DocumentCrawler\ResourceHandler\ResourceHandlerInterface;
use Symfony\Component\DomCrawler\Crawler;
/**
* Crawl and extract all defined icons in a document, that have been declared with `<link rel="icon" ... />`.
*/
class IconsCrawler implements CrawlerInterface
{
/**
* @var array<int, Icon>
*/
private array $icons = [];
private ResourceHandlerInterface $resourceHandler;
public function __construct(
private readonly Crawler $crawler,
) {
$this->resourceHandler = new PassiveResourceHandler();
}
public function crawlContent(): void
{
$eachNode = static function (Crawler $node): ?array {
$key = $node->attr('rel');
if (null === $key || !str_contains($key, 'icon')) {
return null;
}
return [
'name' => $key,
'value' => $node->attr('href'),
];
};
/**
* @var array<int, array{
* name: string,
* value: string|null,
* }|null> $favicons
*/
$favicons = $this->crawler
->filter('head > link')
->each($eachNode)
;
$favicons = array_filter($favicons);
foreach ($favicons as $favicon) {
$iconName = $favicon['name'];
$iconResource = $favicon['value'];
if (null === $iconResource) {
continue;
}
$iconResourceHandled = $this->resourceHandler->handleResource(
$iconResource,
$this->crawler->getUri()
);
if (false === $iconResourceHandled) {
continue;
}
$this->icons[] = new Icon($iconName, $iconResourceHandled);
}
}
/**
* @return array<int, Icon>
*/
public function getIcons(): array
{
return $this->icons;
}
public function setResourceHandler(ResourceHandlerInterface $resourceHandler): self
{
$this->resourceHandler = $resourceHandler;
return $this;
}
}