Completed
Push — master ( 372e16...0ba7a7 )
by Freek
10s
created

MixedContentExtractor::extract()   B

Complexity

Conditions 4
Paths 1

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 18
nc 1
nop 2
1
<?php
2
3
namespace Spatie\MixedContentScanner;
4
5
use Spatie\Crawler\Url;
6
use Illuminate\Support\Collection;
7
use Symfony\Component\DomCrawler\Link;
8
use Symfony\Component\DomCrawler\Crawler as DomCrawler;
9
10
class MixedContentExtractor
11
{
12
    public static function extract(string $html, string $currentUri): array
13
    {
14
        return static::getSearchNodes()
15
            ->mapSpread(function ($tagName, $attribute) use ($html, $currentUri) {
16
                return (new DomCrawler($html, $currentUri))
17
                    ->filterXPath("//{$tagName}[@{$attribute}]")
18
                    ->reduce(function (DomCrawler $node) {
19
                        $relAttr = $node->getNode(0)->attributes->getNamedItem('rel');
20
21
                        if ($relAttr !== null && strtolower($relAttr->nodeValue) === 'shortlink') {
22
                            return false;
23
                        }
24
25
                        return true;
26
                    })
27
                    ->each(function (DomCrawler $node) use ($tagName, $attribute) {
28
                        $url = Url::create($node->attr($attribute));
29
30
                        return $url->scheme === 'http' ? [$tagName, $url] : null;
31
                    });
32
            })
33
            ->flatten(1)
34
            ->filter()
35
            ->mapSpread(function ($tagName, $mixedContentUrl) use ($currentUri) {
36
                return new MixedContent($tagName, $mixedContentUrl, Url::create($currentUri));
37
            })
38
            ->toArray();
39
    }
40
41
    protected static function getSearchNodes(): Collection
42
    {
43
        return collect([
44
            ['audio', 'src'],
45
            ['embed', 'src'],
46
            ['form', 'action'],
47
            ['link', 'href'],
48
            ['iframe', 'src'],
49
            ['img', 'src'],
50
            ['img', 'srcset'],
51
            ['object', 'data'],
52
            ['param', 'value'],
53
            ['script', 'src'],
54
            ['source', 'src'],
55
            ['source', 'srcset'],
56
            ['video', 'src'],
57
        ]);
58
    }
59
}
60