PolitenessPolicyListener   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 30
rs 10
c 0
b 0
f 0
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A onCrawlPreRequest() 0 9 2
1
<?php
2
namespace VDB\Spider\EventListener;
3
4
use Symfony\Component\EventDispatcher\GenericEvent;
5
6
/**
7
 * @author Matthijs van den Bos <[email protected]>
8
 * @copyright 2013 Matthijs van den Bos
9
 */
10
class PolitenessPolicyListener
11
{
12
    /** @var string */
13
    private $previousHostname;
14
15
    /** @var int the delay in microseconds between requests to the same domain */
16
    private $requestDelay;
17
18
    public $totalDelay = 0;
19
20
    /**
21
     * @param int $requestDelay the delay in milliseconds between requests to the same domain
22
     */
23
    public function __construct($requestDelay)
24
    {
25
        $this->requestDelay = $requestDelay * 1000;
26
    }
27
28
    /**
29
     * @param GenericEvent $event
30
     */
31
    public function onCrawlPreRequest(GenericEvent $event)
32
    {
33
        $currentHostname = $event->getArgument('uri')->getHost();
34
35
        if ($currentHostname === $this->previousHostname) {
36
            $this->totalDelay = $this->totalDelay + $this->requestDelay;
37
            usleep($this->requestDelay);
38
        }
39
        $this->previousHostname = $currentHostname;
40
    }
41
}
42