Completed
Push — master ( 705095...78cb27 )
by Jan-Petter
04:57
created

Download   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
c 1
b 0
f 0
lcom 1
cbo 4
dl 0
loc 73
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A getStatusCode() 0 4 1
A getEncoding() 0 11 3
A detectEncoding() 0 7 2
A getBody() 0 4 1
1
<?php
2
namespace vipnytt\RobotsTxtParser\Client;
3
4
use GuzzleHttp;
5
use vipnytt\RobotsTxtParser\Parser\UrlParser;
6
use vipnytt\RobotsTxtParser\RobotsTxtInterface;
7
8
/**
9
 * Class Download
10
 *
11
 * @package vipnytt\RobotsTxtParser\Client
12
 */
13
class Download implements RobotsTxtInterface
14
{
15
    use UrlParser;
16
17
    private $response;
18
19
    /**
20
     * Download constructor.
21
     *
22
     * @param string $url
23
     */
24
    public function __construct($url)
25
    {
26
        $client = new GuzzleHttp\Client(
27
            [
28
                'base_uri' => $this->urlBase($url),
29
                'max' => self::MAX_REDIRECTS,
30
                'http_errors' => false,
31
            ]
32
        );
33
        $this->response = $client->request('GET', '/robots.txt');
34
    }
35
36
    /**
37
     * Status code
38
     *
39
     * @return int
40
     */
41
    public function getStatusCode()
42
    {
43
        return $this->response->getStatusCode();
44
    }
45
46
    /**
47
     * Encoding
48
     *
49
     * @return string
50
     */
51
    public function getEncoding()
52
    {
53
        $header = $this->response->getHeader('content-type')[0];
54
        $split = array_map('trim', mb_split(';', $header));
55
        foreach ($split as $string) {
56
            if (mb_stripos($string, 'charset=') === 0) {
57
                return mb_split('=', $string, 2)[1];
58
            }
59
        }
60
        return $this->detectEncoding();
61
    }
62
63
    /**
64
     * Manually detect encoding
65
     *
66
     * @return string
67
     */
68
    protected function detectEncoding()
69
    {
70
        if (($encoding = mb_detect_encoding($this->getBody())) !== false) {
71
            return $encoding;
72
        }
73
        return self::ENCODING;
74
    }
75
76
    /**
77
     * URL content
78
     *
79
     * @return string
80
     */
81
    public function getBody()
82
    {
83
        return $this->response->getBody()->getContents();
84
    }
85
}
86