Passed
Pull Request — master (#16)
by
unknown
13:19 queued 10:34
created

Srcset::scrape()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5.0984

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 5
eloc 21
c 1
b 0
f 1
nc 3
nop 1
dl 0
loc 34
ccs 16
cts 19
cp 0.8421
crap 5.0984
rs 9.2728
1
<?php
2
3
namespace Aoe\Asdis\Content\Scraper\Html;
4
5
use Aoe\Asdis\Content\Scraper\ScraperInterface;
6
use Aoe\Asdis\Domain\Model\Asset\Collection;
7
use Aoe\Asdis\Domain\Model\Asset\Factory;
8
9
/**
10
 * Scrapes assets from all tags by using data-src attributes.
11
 */
12
class Srcset extends AbstractHtmlScraper implements ScraperInterface
13
{
14
    private Factory $assetFactory;
15
16 2
    public function injectAssetFactory(Factory $assetFactory): void
17
    {
18 2
        $this->assetFactory = $assetFactory;
19 2
    }
20
21 2
    public function scrape(string $content): ?Collection
22
    {
23 2
        $paths = [];
24 2
        $masks = [];
25 2
        $matches = [];
26 2
        preg_match_all(
27 2
            '/srcset=*\s?=\s?([\'"])(.*?)([\'"])/i',
28
            $content,
29
            $matches
30
        );
31
32 2
        foreach ($matches[2] as $mkey => $path) {
33 2
            if (!str_contains($path, ',')) {
34
                $paths[] = $path;
35
                $masks[] = $matches[1][$mkey];
36
                continue;
37
            }
38
39 2
            $expPaths = explode(',', $path);
40
41 2
            foreach ($expPaths as $singlePath) {
42 2
                $cleanSinglePath = trim($singlePath);
43
44 2
                if (str_contains($cleanSinglePath, ' ')) {
45 2
                    $paths[] = substr($cleanSinglePath, 0, strpos($cleanSinglePath, ' '));
46
                } else {
47 1
                    $paths[] = $cleanSinglePath;
48
                }
49
50 2
                $masks[] = '';
51
            }
52
        }
53
54 2
        return $this->assetFactory->createAssetsFromPaths($paths, $masks);
55
    }
56
}
57