1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SilverStripe\Blog\Widgets; |
4
|
|
|
|
5
|
|
|
use SilverStripe\Blog\Model\Blog; |
6
|
|
|
use SilverStripe\Control\Director; |
7
|
|
|
use SilverStripe\Forms\DropdownField; |
8
|
|
|
use SilverStripe\Forms\FieldList; |
9
|
|
|
use SilverStripe\Forms\NumericField; |
10
|
|
|
use SilverStripe\ORM\DataList; |
11
|
|
|
use SilverStripe\Widgets\Model\Widget; |
12
|
|
|
|
13
|
|
|
if (!class_exists(Widget::class)) { |
14
|
|
|
return; |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @method Blog Blog() |
19
|
|
|
* |
20
|
|
|
* @property int $NumberOfPosts |
21
|
|
|
*/ |
22
|
|
View Code Duplication |
class BlogFeaturedPostsWidget extends Widget |
|
|
|
|
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* @var string |
26
|
|
|
*/ |
27
|
|
|
private static $title = 'Featured Posts'; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var string |
31
|
|
|
*/ |
32
|
|
|
private static $cmsTitle = 'Featured Posts'; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @var string |
36
|
|
|
*/ |
37
|
|
|
private static $description = 'Displays a list of featured blog posts.'; |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @var array |
41
|
|
|
*/ |
42
|
|
|
private static $db = [ |
43
|
|
|
'NumberOfPosts' => 'Int', |
44
|
|
|
]; |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @var array |
48
|
|
|
*/ |
49
|
|
|
private static $has_one = [ |
50
|
|
|
'Blog' => Blog::class, |
51
|
|
|
]; |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @var string |
55
|
|
|
*/ |
56
|
|
|
private static $table_name = 'BlogFeaturedPostsWidget'; |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* {@inheritdoc} |
60
|
|
|
*/ |
61
|
|
|
public function getCMSFields() |
62
|
|
|
{ |
63
|
|
|
$this->beforeUpdateCMSFields(function ($fields) { |
64
|
|
|
/** |
65
|
|
|
* @var FieldList $fields |
66
|
|
|
*/ |
67
|
|
|
$fields->merge([ |
68
|
|
|
DropdownField::create('BlogID', _t(__CLASS__ . '.Blog', 'Blog'), Blog::get()->map()), |
69
|
|
|
NumericField::create('NumberOfPosts', _t(__CLASS__ . '.NumberOfPosts', 'Number of Posts')) |
70
|
|
|
]); |
71
|
|
|
}); |
72
|
|
|
|
73
|
|
|
return parent::getCMSFields(); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @return array|DataList |
78
|
|
|
*/ |
79
|
|
|
public function getPosts() |
80
|
|
|
{ |
81
|
|
|
$blog = $this->Blog(); |
82
|
|
|
|
83
|
|
|
if ($blog) { |
84
|
|
|
return $blog->getBlogPosts() |
85
|
|
|
->filter('ID:not', Director::get_current_page()->ID) |
86
|
|
|
->filter('FeaturedInWidget', true) |
87
|
|
|
->sort('RAND()') |
88
|
|
|
->limit($this->NumberOfPosts); |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
return []; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|
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.