Passed
Push — master ( b97c32...e7e450 )
by Carlos C
10:36 queued 12s
created

ScrapingReviewerLinkExtractor::fromUrlResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpCfdi\SatCatalogosPopulate\Origins;
6
7
use RuntimeException;
8
use Symfony\Component\DomCrawler\Crawler;
9
use Symfony\Component\DomCrawler\Link;
10
11
final class ScrapingReviewerLinkExtractor
12
{
13 10
    public function __construct(private Crawler $crawler)
14
    {
15
    }
16
17 11
    public static function fromUrlResponse(UrlResponse $response): self
18
    {
19 11
        if (empty($response->body())) {
20 1
            throw new RuntimeException('Content is empty');
21
        }
22 10
        $crawler = new Crawler($response->body(), $response->url());
23 10
        return new self($crawler);
24
    }
25
26 10
    public function search(string $search): string
27
    {
28 10
        $link = $this->selectLink($search);
29 10
        $downloadUrl = $link->getUri();
30
31 10
        if (empty($downloadUrl)) {
32
            throw new RuntimeException('The link was found but it does not contains the url to download');
33
        }
34
35 10
        return $downloadUrl;
36
    }
37
38 10
    public function selectLink(string $search): Link
39
    {
40 10
        $elements = $this->crawler->filterXPath('//a')->reduce(
41
            fn (Crawler $linkElement): bool =>
42 10
                ('' !== $text = $linkElement->text('')) && fnmatch($search, $text, FNM_CASEFOLD)
43
        );
44
45 10
        if ($elements->count() > 0) {
46 10
            return $elements->first()->link();
47
        }
48
49
        throw new RuntimeException(sprintf('Link text "%s" was not found', $search));
50
    }
51
}
52