1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Nopolabs\Yabot\Plugins\Rss; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Promise\PromiseInterface; |
6
|
|
|
use Nopolabs\Yabot\Guzzle\Guzzle; |
7
|
|
|
use Nopolabs\Yabot\Helpers\ConfigTrait; |
8
|
|
|
use Nopolabs\Yabot\Helpers\GuzzleTrait; |
9
|
|
|
use Nopolabs\Yabot\Helpers\LogTrait; |
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
11
|
|
|
use Psr\Log\LoggerInterface; |
12
|
|
|
use SimpleXMLElement; |
13
|
|
|
|
14
|
|
|
class RssService |
15
|
|
|
{ |
16
|
|
|
use LogTrait; |
17
|
|
|
use GuzzleTrait; |
18
|
|
|
use ConfigTrait; |
19
|
|
|
|
20
|
|
|
public function __construct( |
21
|
|
|
LoggerInterface $logger, |
22
|
|
|
Guzzle $guzzle, |
23
|
|
|
array $config = []) |
24
|
|
|
{ |
25
|
|
|
$this->setLog($logger); |
26
|
|
|
$this->setGuzzle($guzzle); |
27
|
|
|
$this->setConfig(array_merge( |
28
|
|
|
[ |
29
|
|
|
'SimpleXMLElementOptions' => LIBXML_NOCDATA, |
30
|
|
|
'JsonEncodeOptions' => JSON_PRETTY_PRINT, |
31
|
|
|
], |
32
|
|
|
$config |
33
|
|
|
)); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function fetchRaw(string $url) : PromiseInterface |
37
|
|
|
{ |
38
|
|
|
return $this->getAsync($url)->then( |
39
|
|
|
function (ResponseInterface $response) { |
40
|
|
|
return $response->getBody(); |
41
|
|
|
} |
42
|
|
|
); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function fetchXml(string $url) : PromiseInterface |
46
|
|
|
{ |
47
|
|
|
return $this->getAsync($url)->then( |
48
|
|
|
function (ResponseInterface $response) { |
49
|
|
|
$data = $response->getBody(); |
50
|
|
|
$options = $this->get('SimpleXMLElementOptions', 0); |
51
|
|
|
return new SimpleXMLElement($data, $options); |
52
|
|
|
} |
53
|
|
|
); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function fetchJson(string $url) : PromiseInterface |
57
|
|
|
{ |
58
|
|
|
return $this->getAsync($url)->then( |
59
|
|
|
function (ResponseInterface $response) { |
60
|
|
|
$data = $response->getBody(); |
61
|
|
|
$xmlOptions = $this->get('SimpleXMLElementOptions', 0); |
62
|
|
|
$xml = new SimpleXMLElement($data, $xmlOptions); |
63
|
|
|
$jsonOptions = $this->get('JsonEncodeOptions', 0); |
64
|
|
|
return json_encode($xml, $jsonOptions); |
65
|
|
|
} |
66
|
|
|
); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
public function fetch(string $url) : PromiseInterface |
70
|
|
|
{ |
71
|
|
|
return $this->getAsync($url)->then( |
72
|
|
|
function (ResponseInterface $response) { |
73
|
|
|
$data = $response->getBody(); |
74
|
|
|
$xmlOptions = $this->get('SimpleXMLElementOptions', 0); |
75
|
|
|
$xml = new SimpleXMLElement($data, $xmlOptions); |
76
|
|
|
$jsonOptions = $this->get('JsonEncodeOptions', 0); |
77
|
|
|
$json = json_encode($xml, $jsonOptions & ~JSON_PRETTY_PRINT); |
78
|
|
|
return json_decode($json); |
79
|
|
|
} |
80
|
|
|
); |
81
|
|
|
} |
82
|
|
|
} |