Completed
Push — master ( 49e9a0...fa7091 )
by Jan-Petter
02:11
created

Download   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 72
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 72
rs 10

5 Methods

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