1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Compolomus\RssReader; |
4
|
|
|
|
5
|
|
|
use DateTime; |
6
|
|
|
use DOMDocument; |
7
|
|
|
use DOMXPath; |
8
|
|
|
use function array_column; |
9
|
|
|
use function array_merge; |
10
|
|
|
use function count; |
11
|
|
|
use function crc32; |
12
|
|
|
use function in_array; |
13
|
|
|
use function strip_tags; |
14
|
|
|
use function trim; |
15
|
|
|
|
16
|
|
|
class RssReader |
17
|
|
|
{ |
18
|
|
|
public function __construct( |
19
|
|
|
public array $channels = [], |
20
|
|
|
public ?CacheInterface $cache = null, |
21
|
|
|
) { |
22
|
|
|
if (null === $this->cache) { |
23
|
|
|
$this->cache = new FileCache(); |
24
|
|
|
} |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @throws \Exception |
29
|
|
|
*/ |
30
|
|
|
protected function getPostsFromChannel(string $chanel): ?array |
31
|
|
|
{ |
32
|
|
|
// Load document |
33
|
|
|
$dom = new DOMDocument(); |
34
|
|
|
$dom->load($chanel); |
35
|
|
|
|
36
|
|
|
// Extract all items |
37
|
|
|
$items = $dom->getElementsByTagName('item'); |
38
|
|
|
|
39
|
|
|
// Build XPath object |
40
|
|
|
$xpath = new DOMXpath($dom); |
41
|
|
|
|
42
|
|
|
// Parse all items in loop |
43
|
|
|
$result = []; |
44
|
|
|
foreach ($items as $item) { |
45
|
|
|
$link = $item->getElementsByTagName('link')->item(0)->nodeValue; |
46
|
|
|
$itemId = crc32($link); |
47
|
|
|
$timestamp = (new DateTime($item->getElementsByTagName('pubDate')->item(0)->nodeValue))->getTimestamp(); |
48
|
|
|
|
49
|
|
|
// Extract posts which is not in a cache |
50
|
|
|
if (!in_array($itemId, $this->cache->getIds(), false)) { |
|
|
|
|
51
|
|
|
$result[] = [ |
52
|
|
|
'id' => $itemId, |
53
|
|
|
'title' => $item->getElementsByTagName('title')->item(0)->nodeValue, |
54
|
|
|
'desc' => trim(strip_tags($item->getElementsByTagName('description')->item(0)->nodeValue)), |
55
|
|
|
'link' => $link, |
56
|
|
|
'timestamp' => $timestamp, |
57
|
|
|
'img' => $xpath->query('//enclosure/@url')->item(0)->nodeValue, |
58
|
|
|
]; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $result; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @throws \Exception |
67
|
|
|
*/ |
68
|
|
|
public function getAll(): array |
69
|
|
|
{ |
70
|
|
|
$result = []; |
71
|
|
|
foreach ($this->channels as $chanel) { |
72
|
|
|
$result[] = $this->getPostsFromChannel($chanel); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
$result = array_merge(...$result); |
76
|
|
|
$ids = array_column($result, 'id'); |
77
|
|
|
|
78
|
|
|
if (count($ids)) { |
79
|
|
|
$this->cache->saveIds($ids); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return $result; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.
This is most likely a typographical error or the method has been renamed.