Passed
Push — master ( 92084b...91cbe9 )
by Dev
13:57 queued 12:21
created

RobotsTxtTrait::getRobotsTxt()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6.0087

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 27
ccs 15
cts 16
cp 0.9375
rs 9.0777
cc 6
nc 5
nop 0
crap 6.0087
1
<?php
2
3
namespace PiedWeb\UrlHarvester;
4
5
use PiedWeb\Curl\Request as CurlRequest;
6
use Spatie\Robots\RobotsTxt;
7
8
trait RobotsTxtTrait
9
{
10
    /** @var RobotsTxt|string (empty string) */
11
    protected $robotsTxt;
12
13
    //abstract public function getDomainAndScheme();
14
15
    abstract public function getResponse();
16
17
    abstract public function url();
18
19
    /**
20
     * @return RobotsTxt|string containing the current Robots.txt or NULL if an error occured
21
     *                          or empty string if robots is empty file
22
     */
23 9
    public function getRobotsTxt()
24
    {
25 9
        if (null === $this->robotsTxt) {
26 9
            $url = $this->url()->getOrigin().'/robots.txt';
27
28 9
            $request = $this->getResponse()->getRequest();
29 9
            $userAgent = $request ? $request->getUserAgent() : Harvest::DEFAULT_USER_AGENT;
30
31 9
            $request = new CurlRequest($url);
32
            $request
33 9
                ->setDefaultSpeedOptions()
34 9
                ->setDownloadOnly('0-500000')
35 9
                ->setUserAgent($userAgent)
36
            ;
37 9
            $result = $request->exec();
38
39 9
            if (!$result instanceof \PiedWeb\Curl\Response
40 9
                || false === stripos($result->getContentType(), 'text/plain')
41 9
                || empty(trim($result->getContent()))
42
            ) {
43
                $this->robotsTxt = '';
44
            } else {
45 9
                $this->robotsTxt = new RobotsTxt($result->getContent());
46
            }
47
        }
48
49 9
        return $this->robotsTxt;
50
    }
51
52
    /**
53
     * @param RobotsTxt|string $robotsTxt
54
     *
55
     * @return self
56
     */
57 3
    public function setRobotsTxt($robotsTxt)
58
    {
59 3
        $this->robotsTxt = is_string($robotsTxt) ? (empty($robotsTxt) ? '' : new RobotsTxt($robotsTxt)) : $robotsTxt;
60
61 3
        return $this;
62
    }
63
}
64