Completed
Push — master ( dbcf6b...d53ab6 )
by Peter
44:13 queued 37:37
created

GuzzleClient::getRequestOptions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 5
cts 6
cp 0.8333
rs 9.7998
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2.0185
1
<?php
2
3
namespace TreeHouse\IoBundle\Scrape\Crawler\Client;
4
5
use GuzzleHttp\ClientInterface as GuzzleClientInterface;
6
use GuzzleHttp\Exception\RequestException;
7
use GuzzleHttp\RequestOptions;
8
use GuzzleHttp\TransferStats;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Log\LoggerAwareInterface;
11
use Psr\Log\LoggerAwareTrait;
12
use TreeHouse\IoBundle\Scrape\Exception\CrawlException;
13
14
class GuzzleClient implements ClientInterface, LoggerAwareInterface
15
{
16
    use LoggerAwareTrait;
17
18
    /**
19
     * @var GuzzleClientInterface
20
     */
21
    protected $guzzle;
22
23
    /**
24
     * @var string[]
25
     */
26
    protected $effectiveUrls = [];
27
28
    /**
29
     * @param GuzzleClientInterface $guzzle
30
     */
31 2
    public function __construct(GuzzleClientInterface $guzzle)
32
    {
33 2
        $this->guzzle = $guzzle;
34 2
    }
35
36
    /**
37
     * @inheritdoc
38
     */
39 2
    public function fetch($uri, $userAgent = null)
40
    {
41 2
        $this->setEffectiveUri($uri, $uri);
42
43
        try {
44 2
            $response = $this->guzzle->request('GET', $uri, $this->getRequestOptions($userAgent));
45
46 2
            return $this->transformResponse($uri, $response);
47
        } catch (RequestException $e) {
48
            $this->logger->error(
49
                sprintf('Error crawling: %s', $e->getMessage()),
50
                ['url' => (string) $e->getRequest()->getUri()]
51
            );
52
53
            if ($response = $e->getResponse()) {
54
                return $this->transformResponse($uri, $response);
55
            }
56
57
            throw new CrawlException($uri, sprintf('Error crawling url: %s', $e->getMessage()), $e->getCode(), $e);
58
        }
59
    }
60
61
    /**
62
     * @param string $uri
63
     * @param string $effectiveUri
64
     */
65 2
    public function setEffectiveUri($uri, $effectiveUri)
66
    {
67 2
        $this->effectiveUrls[$uri] = $effectiveUri;
68 2
    }
69
70
    /**
71
     * @param string $userAgent
72
     *
73
     * @return array
74
     */
75
    protected function getRequestOptions($userAgent = null)
76
    {
77
        $options = [
78 2
            RequestOptions::ON_STATS => function (TransferStats $stats) {
79
                $this->setEffectiveUri($stats->getRequest(), $stats->getEffectiveUri());
0 ignored issues
show
Documentation introduced by
$stats->getRequest() is of type object<Psr\Http\Message\RequestInterface>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
80 2
            },
81
        ];
82
83 2
        if ($userAgent) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $userAgent of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
84 2
            $options[RequestOptions::HEADERS]['User-Agent'] = $userAgent;
85
        }
86
87 2
        return $options;
88
    }
89
90
    /**
91
     * @param string            $uri
92
     * @param ResponseInterface $response
93
     *
94
     * @return array
95
     */
96 2
    protected function transformResponse($uri, ResponseInterface $response)
97
    {
98
        return [
99 2
            isset($this->effectiveUrls[$uri]) ? $this->effectiveUrls[$uri] : $uri,
100 2
            $response,
101
        ];
102
    }
103
}
104