1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Crawler; |
4
|
|
|
|
5
|
|
|
use Iterator; |
6
|
|
|
use ArrayAccess; |
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
8
|
|
|
use GuzzleHttp\Exception\RequestException; |
9
|
|
|
|
10
|
|
|
class ObserverCollection implements ArrayAccess, Iterator |
11
|
|
|
{ |
12
|
|
|
/** @var \Spatie\Crawler\CrawlObserver[] */ |
13
|
|
|
protected $observers; |
14
|
|
|
|
15
|
|
|
/** @var int */ |
16
|
|
|
protected $position; |
17
|
|
|
|
18
|
|
|
public function __construct(array $observers = []) |
19
|
|
|
{ |
20
|
|
|
$this->observers = $observers; |
21
|
|
|
$this->position = 0; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function addObserver(CrawlObserver $observer) |
25
|
|
|
{ |
26
|
|
|
$this->observers[] = $observer; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function crawled(CrawlUrl $crawlUrl, ResponseInterface $response) |
30
|
|
|
{ |
31
|
|
|
foreach ($this->observers as $crawlObserver) { |
32
|
|
|
$crawlObserver->crawled( |
33
|
|
|
$crawlUrl->url, |
34
|
|
|
$response, |
35
|
|
|
$crawlUrl->foundOnUrl |
36
|
|
|
); |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function crawlFailed(CrawlUrl $crawlUrl, RequestException $exception) |
41
|
|
|
{ |
42
|
|
|
foreach ($this->observers as $crawlObserver) { |
43
|
|
|
$crawlObserver->crawlFailed( |
44
|
|
|
$crawlUrl->url, |
45
|
|
|
$exception, |
46
|
|
|
$crawlUrl->foundOnUrl |
47
|
|
|
); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function current() |
52
|
|
|
{ |
53
|
|
|
return $this->observers[$this->position]; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function offsetGet($offset) |
57
|
|
|
{ |
58
|
|
|
return isset($this->observers[$offset]) ? $this->observers[$offset] : null; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function offsetSet($offset, $value) |
62
|
|
|
{ |
63
|
|
|
if (is_null($offset)) { |
64
|
|
|
$this->observers[] = $value; |
65
|
|
|
} else { |
66
|
|
|
$this->observers[$offset] = $value; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public function offsetExists($offset) |
71
|
|
|
{ |
72
|
|
|
return isset($this->observers[$offset]); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
public function offsetUnset($offset) |
76
|
|
|
{ |
77
|
|
|
unset($this->observers[$offset]); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
public function next() |
81
|
|
|
{ |
82
|
|
|
$this->position++; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
public function key() |
86
|
|
|
{ |
87
|
|
|
return $this->position; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
public function valid() |
91
|
|
|
{ |
92
|
|
|
return isset($this->observers[$this->position]); |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
public function rewind() |
96
|
|
|
{ |
97
|
|
|
$this->position = 0; |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|