Completed
Push — 2.0-dev ( 2c252e...97b412 )
by Jan-Petter
02:13
created

SQL::cron()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 28
rs 8.5806
cc 4
eloc 15
nc 4
nop 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A SQL::markAsActive() 0 14 2
1
<?php
2
namespace vipnytt\RobotsTxtParser;
3
4
use PDO;
5
use vipnytt\RobotsTxtParser\Client\SQL\Cache\CacheCoreSQL;
6
use vipnytt\RobotsTxtParser\Parser\UrlParser;
7
8
/**
9
 * Class SQL
10
 *
11
 * @package vipnytt\RobotsTxtParser
12
 */
13
class SQL extends CacheCoreSQL
14
{
15
    use UrlParser;
16
17
    /**
18
     * Client nextUpdate margin in seconds
19
     * @var int
20
     */
21
    private $clientUpdateMargin = 300;
22
23
    /**
24
     * Cache constructor.
25
     *
26
     * @param PDO $pdo
27
     * @param array $guzzleConfig
28
     * @param int|null $byteLimit
29
     */
30
    public function __construct(PDO $pdo, array $guzzleConfig = [], $byteLimit = self::BYTE_LIMIT)
31
    {
32
        parent::__construct($pdo, $guzzleConfig, $byteLimit);
33
    }
34
35
    /**
36
     * Parser client
37
     *
38
     * @param string $baseUri
39
     * @return Basic
40
     */
41
    public function client($baseUri)
42
    {
43
        $base = $this->urlBase($this->urlEncode($baseUri));
44
        $query = $this->pdo->prepare(<<<SQL
45
SELECT
46
  content,
47
  statusCode,
48
  nextUpdate,
49
  worker
50
FROM robotstxt__cache0
51
WHERE base = :base;
52
SQL
53
        );
54
        $query->bindParam(':base', $base, PDO::PARAM_STR);
55
        $query->execute();
56
        if ($query->rowCount() > 0) {
57
            $row = $query->fetch(PDO::FETCH_ASSOC);
58
            if ($row['nextUpdate'] >= (time() - $this->clientUpdateMargin)) {
59
                $this->markAsActive($base, $row['worker']);
60
                return new Basic($base, $row['code'], $row['content'], self::ENCODING, $this->byteLimit);
61
            }
62
        }
63
        $request = new URI($base, $this->guzzleConfig, $this->byteLimit);
64
        $this->push($request);
65
        $this->markAsActive($base);
66
        return new Basic($base, $request->getStatusCode(), $request->getContents(), self::ENCODING, $this->byteLimit);
67
    }
68
69
    /**
70
     * Mark robots.txt as active
71
     *
72
     * @param string $base
73
     * @param int|null $workerID
74
     * @return bool
75
     */
76
    private function markAsActive($base, $workerID = 0)
77
    {
78
        if ($workerID == 0) {
79
            $query = $this->pdo->prepare(<<<SQL
80
UPDATE robotstxt__cache0
81
SET worker = NULL
82
WHERE base = :base AND worker = 0;
83
SQL
84
            );
85
            $query->bindParam(':base', $base, PDO::PARAM_STR);
86
            return $query->execute();
87
        }
88
        return true;
89
    }
90
}
91