1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\MixedContentScanner; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Psr7\Uri; |
6
|
|
|
use Spatie\Crawler\Crawler; |
7
|
|
|
use Spatie\Crawler\CrawlProfile; |
8
|
|
|
use Spatie\Crawler\CrawlInternalUrls; |
9
|
|
|
use Spatie\MixedContentScanner\Exceptions\InvalidUrl; |
10
|
|
|
|
11
|
|
|
class MixedContentScanner |
12
|
|
|
{ |
13
|
|
|
/** @var \Spatie\MixedContentScanner\MixedContentObserver */ |
14
|
|
|
public $mixedContentObserver; |
15
|
|
|
|
16
|
|
|
/** @var null|\Spatie\Crawler\CrawlProfile */ |
17
|
|
|
public $crawlProfile; |
18
|
|
|
|
19
|
|
|
/** @var int|null */ |
20
|
|
|
protected $maximumCrawlCount; |
21
|
|
|
|
22
|
|
|
/** @var callable */ |
23
|
|
|
protected $configureCrawler; |
24
|
|
|
|
25
|
|
|
public function __construct(MixedContentObserver $mixedContentObserver) |
26
|
|
|
{ |
27
|
|
|
$this->mixedContentObserver = $mixedContentObserver; |
28
|
|
|
|
29
|
|
|
$this->configureCrawler = function (Crawler $crawler) { |
|
|
|
|
30
|
|
|
}; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function scan(string $url, array $clientOptions = []) |
34
|
|
|
{ |
35
|
|
|
$this->guardAgainstInvalidUrl($url); |
36
|
|
|
|
37
|
|
|
$url = new Uri($url); |
38
|
|
|
|
39
|
|
|
$crawler = Crawler::create($clientOptions); |
40
|
|
|
|
41
|
|
|
($this->configureCrawler)($crawler); |
42
|
|
|
|
43
|
|
|
if ($this->maximumCrawlCount) { |
|
|
|
|
44
|
|
|
$crawler->setMaximumCrawlCount($this->maximumCrawlCount); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$crawler->setCrawlProfile($this->crawlProfile ?? new CrawlInternalUrls($url)) |
48
|
|
|
->setCrawlObserver($this->mixedContentObserver) |
49
|
|
|
->startCrawling($url); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function configureCrawler(callable $callable) |
53
|
|
|
{ |
54
|
|
|
$this->configureCrawler = $callable; |
55
|
|
|
|
56
|
|
|
return $this; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function setCrawlProfile(CrawlProfile $crawlProfile) |
60
|
|
|
{ |
61
|
|
|
$this->crawlProfile = $crawlProfile; |
62
|
|
|
|
63
|
|
|
return $this; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
protected function guardAgainstInvalidUrl(string $url) |
67
|
|
|
{ |
68
|
|
|
if ($url == '') { |
69
|
|
|
throw InvalidUrl::urlIsEmpty(); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
if (! $this->startsWith($url, ['http://', 'https://'])) { |
73
|
|
|
throw InvalidUrl::invalidScheme($url); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
protected function startsWith(string $haystack, array $needles): bool |
78
|
|
|
{ |
79
|
|
|
foreach ((array) $needles as $needle) { |
80
|
|
|
if ($needle != '' && substr($haystack, 0, strlen($needle)) === (string) $needle) { |
81
|
|
|
return true; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
return false; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.