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

ScrapingReviewerLinkExtractor   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 88.89%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 39
ccs 16
cts 18
cp 0.8889
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A selectLink() 0 12 3
A fromUrlResponse() 0 7 2
A __construct() 0 2 1
A search() 0 10 2
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