-
Notifications
You must be signed in to change notification settings - Fork 611
/
Feed.php
132 lines (115 loc) · 2.84 KB
/
Feed.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
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\widgets;
use Craft;
use craft\base\Widget;
use craft\helpers\Json;
use craft\web\assets\feed\FeedAsset;
/**
* Feed represents a Feed dashboard widget.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0.0
*/
class Feed extends Widget
{
/**
* @inheritdoc
*/
public static function displayName(): string
{
return Craft::t('app', 'Feed');
}
/**
* @inheritdoc
*/
public static function icon(): ?string
{
return 'rss';
}
/**
* @var string|null The feed URL
*/
public ?string $url = null;
/**
* @var string|null The feed title
*/
public ?string $title = null;
/**
* @var int The maximum number of feed items to display
*/
public int $limit = 5;
/**
* @inheritdoc
*/
public function __construct($config = [])
{
// Config normalization
if (($config['limit'] ?? null) === '') {
unset($config['limit']);
}
parent::__construct($config);
}
/**
* @inheritdoc
*/
protected function defineRules(): array
{
$rules = parent::defineRules();
$rules[] = [['url', 'title'], 'required'];
$rules[] = [['url'], 'url'];
$rules[] = [['limit'], 'integer', 'min' => 1];
return $rules;
}
/**
* @inheritdoc
*/
public function getSettingsHtml(): ?string
{
return Craft::$app->getView()->renderTemplate('_components/widgets/Feed/settings.twig',
[
'widget' => $this,
]);
}
/**
* @inheritdoc
*/
public function getTitle(): ?string
{
return $this->title;
}
/**
* @inheritdoc
*/
public function getBodyHtml(): ?string
{
// See if it's already cached
$data = Craft::$app->getCache()->get("feed:$this->url");
if ($data) {
$data['items'] = array_slice($data['items'] ?? [], 0, $this->limit);
} else {
// Fake it for now and fetch it later
$data = [
'direction' => 'ltr',
'items' => [],
];
for ($i = 0; $i < $this->limit; $i++) {
$data['items'][] = [];
}
$view = Craft::$app->getView();
$view->registerAssetBundle(FeedAsset::class);
$view->registerJs(
"new Craft.FeedWidget($this->id, " .
Json::encode($this->url) . ', ' .
Json::encode($this->limit) . ');'
);
}
return Craft::$app->getView()->renderTemplate('_components/widgets/Feed/body.twig', [
'feed' => $data,
]);
}
}