Passed
Push — master ( c0f32c...e879f4 )
by Chema
04:17 queued 41s
created

BarronsSiteCrawler::crawl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 9.9666
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chemaclass\StockTicker\Domain\Crawler\Site\Barrons;
6
7
use Chemaclass\StockTicker\Domain\Crawler\SiteCrawlerInterface;
8
use Chemaclass\StockTicker\Domain\ReadModel\Site;
9
use Chemaclass\StockTicker\Domain\ReadModel\Symbol;
10
use Symfony\Contracts\HttpClient\HttpClientInterface;
11
12
final class BarronsSiteCrawler implements SiteCrawlerInterface
13
{
14
    private const REQUEST_METHOD = 'GET';
15
16
    private const REQUEST_URL = 'https://www.barrons.com/quote/stock/%s';
17
18
    private const EXAMPLE_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36';
19
20
    /** @var HtmlCrawlerInterface[] */
21
    private array $crawlers;
22
23 4
    public function __construct(array $crawlers)
24
    {
25 4
        $this->crawlers = $crawlers;
26 4
    }
27
28 4
    public function crawl(HttpClientInterface $httpClient, Symbol $symbol): Site
29
    {
30 4
        $symbol = mb_strtolower($symbol->toString());
31 4
        $url = sprintf(self::REQUEST_URL, $symbol);
32
33
        $html = $httpClient
34 4
            ->request(self::REQUEST_METHOD, $url, $this->buildRequestHeaders())
35 4
            ->getContent($throw = false);
36
37 4
        $crawled = [];
38
39 4
        foreach ($this->crawlers as $name => $crawler) {
40 4
            $crawled[$name] = $crawler->crawlHtml($html);
41
        }
42
43 4
        return new Site($crawled);
44
    }
45
46 4
    private function buildRequestHeaders(): array
47
    {
48
        return [
49
            'headers' => [
50 4
                'User-Agent' => self::EXAMPLE_USER_AGENT,
51
            ],
52
        ];
53
    }
54
}
55