Completed
Push — master ( 5940c8...660bec )
by Freek
01:12
created

MixedContentScanner::guardAgainstInvalidUrl()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 1
1
<?php
2
3
namespace Spatie\MixedContentScanner;
4
5
use Spatie\Crawler\Crawler;
6
use Spatie\Crawler\CrawlProfile;
7
use Spatie\Crawler\CrawlInternalUrls;
8
use Spatie\Crawler\Url;
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
    public function __construct(MixedContentObserver $mixedContentObserver)
20
    {
21
        $this->mixedContentObserver = $mixedContentObserver;
22
    }
23
24
    public function scan(string $url, array $clientOptions = [])
25
    {
26
        $this->guardAgainstInvalidUrl($url);
27
28
        $url = Url::create($url);
29
30
        Crawler::create($clientOptions)
31
            ->setCrawlProfile($this->crawlProfile ?? new CrawlInternalUrls($url))
32
            ->setCrawlObserver($this->mixedContentObserver)
33
            ->startCrawling($url);
34
    }
35
36
    public function setCrawlProfile(CrawlProfile $crawlProfile)
37
    {
38
        $this->crawlProfile = $crawlProfile;
39
40
        return $this;
41
    }
42
43
    protected function guardAgainstInvalidUrl(string $url)
44
    {
45
        if ($url == '') {
46
            throw InvalidUrl::urlIsEmpty();
47
        }
48
49
        if (! $this->startsWith($url, ['http://', 'https://'])) {
50
            throw InvalidUrl::invalidScheme($url);
51
        }
52
    }
53
54
    protected function startsWith(string $haystack, array $needles): bool
55
    {
56
        foreach ((array) $needles as $needle) {
57
            if ($needle != '' && substr($haystack, 0, strlen($needle)) === (string) $needle) {
58
                return true;
59
            }
60
        }
61
62
        return false;
63
    }
64
}
65