1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Nopolabs\Yabot\Plugins\Examples; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
use Exception; |
7
|
|
|
use Nopolabs\Yabot\Message\Message; |
8
|
|
|
use Nopolabs\Yabot\Plugin\PluginInterface; |
9
|
|
|
use Nopolabs\Yabot\Plugin\PluginTrait; |
10
|
|
|
use Nopolabs\Yabot\Plugins\Giphy\GiphyService; |
11
|
|
|
use Nopolabs\Yabot\Plugins\Rss\RssService; |
12
|
|
|
use Psr\Log\LoggerInterface; |
13
|
|
|
use React\EventLoop\LoopInterface; |
14
|
|
|
|
15
|
|
|
class NytPlugin implements PluginInterface |
16
|
|
|
{ |
17
|
|
|
use PluginTrait; |
18
|
|
|
|
19
|
|
|
private $rssService; |
20
|
|
|
private $giphyService; |
21
|
|
|
|
22
|
|
View Code Duplication |
public function __construct( |
|
|
|
|
23
|
|
|
LoggerInterface $logger, |
24
|
|
|
RssService $rssService, |
25
|
|
|
GiphyService $giphyService, |
26
|
|
|
array $config = []) |
27
|
|
|
{ |
28
|
|
|
$this->setLog($logger); |
29
|
|
|
$this->rssService = $rssService; |
30
|
|
|
$this->giphyService = $giphyService; |
31
|
|
|
$this->setConfig(array_merge( |
32
|
|
|
[ |
33
|
|
|
'help' => '<prefix> number-of-items', |
34
|
|
|
'prefix' => 'nyt', |
35
|
|
|
'matchers' => [ |
36
|
|
|
'nyt' => "/^(?:(?'n'\\d\\d?)|)$/", |
37
|
|
|
], |
38
|
|
|
'url' => 'http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml', |
39
|
|
|
'format' => 'fixed_height_downsampled', |
40
|
|
|
], |
41
|
|
|
$config |
42
|
|
|
)); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function nyt(Message $msg, array $matches) |
46
|
|
|
{ |
47
|
|
|
$n = $matches['n'] ? $matches['n'] : 1; |
48
|
|
|
$url = $this->get('url'); |
49
|
|
|
|
50
|
|
|
$this->rssService |
51
|
|
|
->fetch($url) |
52
|
|
|
->then( |
53
|
|
|
function ($rss) use ($msg, $n) { |
54
|
|
|
$items = $rss->channel->item; |
55
|
|
|
$n = min($n, count($items)); |
|
|
|
|
56
|
|
|
$format = $this->get('format', 'fixed_height'); |
57
|
|
|
for ($i = 0; $i < $n; $i++) { |
58
|
|
|
$title = $items[$i]->title; |
59
|
|
|
$this->giphyService |
60
|
|
|
->search($title, $format) |
61
|
|
|
->then( |
62
|
|
|
function (string $gifUrl) use ($msg, $title, $i) { |
63
|
|
|
$msg->reply("<$gifUrl|$i: $title>"); |
64
|
|
|
}, |
65
|
|
|
function (Exception $e) { |
66
|
|
|
$this->getLog()->warning($e->getMessage()); |
67
|
|
|
} |
68
|
|
|
); |
69
|
|
|
} |
70
|
|
|
}, |
71
|
|
|
function (Exception $e) { |
72
|
|
|
$this->getLog()->warning($e->getMessage()); |
73
|
|
|
} |
74
|
|
|
); |
75
|
|
|
|
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.