|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Compolomus\RssReader; |
|
6
|
|
|
|
|
7
|
|
|
use DateTime; |
|
8
|
|
|
use DOMDocument; |
|
9
|
|
|
use DOMElement; |
|
10
|
|
|
use DOMXPath; |
|
11
|
|
|
|
|
12
|
|
|
class RssReader |
|
13
|
|
|
{ |
|
14
|
|
|
private Cache $cache; |
|
15
|
|
|
|
|
16
|
|
|
public function __construct(Cache $cache) |
|
17
|
|
|
{ |
|
18
|
|
|
$this->cache = $cache; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function getCache() |
|
22
|
|
|
{ |
|
23
|
|
|
return $this->cache; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function getAll(): array |
|
27
|
|
|
{ |
|
28
|
|
|
$dom = new DOMDocument(); |
|
29
|
|
|
$result = []; |
|
30
|
|
|
$ids = []; |
|
31
|
|
|
|
|
32
|
|
|
foreach ($this->cache->getCacheChannels() as $chanel) { |
|
33
|
|
|
$dom->load($chanel); |
|
34
|
|
|
$items = $dom->getElementsByTagName('item'); |
|
35
|
|
|
$xpath = new DOMXpath($dom); |
|
36
|
|
|
foreach ($items as $item) { |
|
37
|
|
|
$data = $this->getItemData($item, $xpath); |
|
38
|
|
|
$result[] = $data; |
|
39
|
|
|
$ids[] = $data['cacheId']; |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
if (count($ids)) { |
|
44
|
|
|
$this->cache->updateCacheIds($ids); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
return $result; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
public function getItemData(DOMElement $item, DOMXpath $xpath) |
|
51
|
|
|
{ |
|
52
|
|
|
$link = $item->getElementsByTagName('link')->item(0)->nodeValue; |
|
53
|
|
|
preg_match('#\/(\d{3,})\/{0,1}#', $link, $matches); |
|
54
|
|
|
$timestamp = (new DateTime($item->getElementsByTagName('pubDate')->item(0)->nodeValue))->getTimestamp(); |
|
55
|
|
|
$id = $matches[1]; |
|
56
|
|
|
$cacheId = $this->cache->generateId($link); |
|
57
|
|
|
|
|
58
|
|
|
if (!in_array($cacheId, $this->cache->getCacheIds(), true)) { |
|
59
|
|
|
return [ |
|
60
|
|
|
'id' => $id, |
|
61
|
|
|
'title' => $item->getElementsByTagName('title')->item(0)->nodeValue, |
|
62
|
|
|
'desc' => trim(strip_tags($item->getElementsByTagName('description')->item(0)->nodeValue)), |
|
63
|
|
|
'link' => $link, |
|
64
|
|
|
'timestamp' => $timestamp, |
|
65
|
|
|
'img' => $xpath->query('//enclosure/@url')->item(0)->nodeValue, |
|
66
|
|
|
'cacheId' => $cacheId |
|
67
|
|
|
]; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
} |
|
72
|
|
|
|