-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRssCollector.php
153 lines (140 loc) · 3.14 KB
/
RssCollector.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
<?php
/**
* slince rss-collector
* @author Tao <[email protected]>
*/
namespace Slince\RssCollector;
class RssCollector
{
/**
* rss源地址
*
* @var string
*/
protected $rssUrl;
/**
* 文章处理器,采集完成之后会触发
*
* @var array
*/
protected $handlers = [];
/**
* 最终的数据结构
*
* @var object
*/
protected $dataObject;
function __construct($rssUrl = null, array $handlers = [])
{
$this->rssUrl = $rssUrl;
$this->pushHandlers($handlers);
$this->dataObject = new \stdClass();
}
/**
* 运行
*/
function run()
{
$rss = \Feed::loadRss($this->rssUrl);
$data = [
'title' => $rss->title,
'description' => $rss->description,
'link' => $rss->link,
'items' => $rss->item,
'articles' => $this->parseItems($rss->item)
];
$this->dataObject = (object)$data;
return $this;
}
/**
* 解析rss中的items
*
* @param array|Iterator $items
*/
protected function parseItems($items)
{
$articles = [];
foreach ($items as $item) {
if (($html = file_get_contents($item->link)) !== false) {
$result = ArticleExtractor::extact($html, $item->link);
if ($result !== false) {
list($title, $content) = $result;
$link = $item->link;
$this->triggerHander($title, $content, $link, (array)$item);
$articles[] = (object)[
'title' => $title,
'content' => $content,
'link' => $link,
];
}
}
}
return $articles;
}
/**
* 触发所有的文章处理器
*
* @param string $title
* @param string $content
* @param string $link
* @param array $item
*/
protected function triggerHander(&$title, &$content, &$link, $item)
{
foreach ($this->handlers as $handler) {
call_user_func($handler, $title, $content, $link, $item);
}
}
/**
* 获取rssurl
*/
function getRssUrl()
{
return $this->rssUrl;
}
/**
* 设置rss url
*
* @param string $rssUrl
*/
function setRssUrl($rssUrl)
{
$this->rssUrl = $rssUrl;
}
/**
* 添加handler
*
* @param callable $handler
*/
function pushHandler(callable $handler)
{
$this->handlers[] = $handler;
}
/**
* 批量添加handler
*
* @param array $handlers
*/
function pushHandlers(array $handlers = [])
{
foreach ($handlers as $handler) {
$this->pushHandler($handler);
}
}
/**
* 获取所有的handlers
*
* @return array
*/
function getHandlers()
{
return $this->handlers;
}
/**
* 获取数据
*/
function getData()
{
return $this->dataObject;
}
}