Passed
Push — master ( a2a476...278f1c )
by Steve
14:06 queued 10:56
created
src/PageTypes/EventHolder.php 1 patch
Indentation   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -7,57 +7,57 @@
 block discarded – undo
7 7
 
8 8
 class EventHolder extends DatedUpdateHolder
9 9
 {
10
-    private static $description = 'Container page for Event Pages, provides event filtering and pagination';
11
-
12
-    private static $allowed_children = [
13
-        EventPage::class,
14
-    ];
15
-
16
-    private static $default_child = EventPage::class;
17
-
18
-    private static $update_name = 'Events';
19
-
20
-    private static $update_class = EventPage::class;
21
-
22
-    private static $icon_class = 'font-icon-p-event-alt';
23
-
24
-    private static $singular_name = 'Event Holder';
25
-
26
-    private static $plural_name = 'Event Holders';
27
-
28
-    private static $table_name = 'EventHolder';
29
-
30
-    /**
31
-     * Find all site's news items, based on some filters.
32
-     * Omitting parameters will prevent relevant filters from being applied. The filters are ANDed together.
33
-     *
34
-     * @param string $className The name of the class to fetch.
35
-     * @param int $parentID The ID of the holder to extract the news items from.
36
-     * @param int $tagID The ID of the tag to filter the news items by.
37
-     * @param string $dateFrom The beginning of a date filter range.
38
-     * @param string $dateTo The end of the date filter range. If empty, only one day will be searched for.
39
-     * @param int $year Numeric value of the year to show.
40
-     * @param int $monthNumber Numeric value of the month to show.
41
-     *
42
-     * @returns DataList|PaginatedList
43
-     */
44
-    public static function AllUpdates(
45
-        $className = 'Events',
46
-        $parentID = null,
47
-        $tagID = null,
48
-        $dateFrom = null,
49
-        $dateTo = null,
50
-        $year = null,
51
-        $monthNumber = null
52
-    ) {
53
-        return parent::AllUpdates(
54
-            $className,
55
-            $parentID,
56
-            $tagID,
57
-            $dateFrom,
58
-            $dateTo,
59
-            $year,
60
-            $monthNumber
61
-        )->Sort('Date', 'ASC');
62
-    }
10
+	private static $description = 'Container page for Event Pages, provides event filtering and pagination';
11
+
12
+	private static $allowed_children = [
13
+		EventPage::class,
14
+	];
15
+
16
+	private static $default_child = EventPage::class;
17
+
18
+	private static $update_name = 'Events';
19
+
20
+	private static $update_class = EventPage::class;
21
+
22
+	private static $icon_class = 'font-icon-p-event-alt';
23
+
24
+	private static $singular_name = 'Event Holder';
25
+
26
+	private static $plural_name = 'Event Holders';
27
+
28
+	private static $table_name = 'EventHolder';
29
+
30
+	/**
31
+	 * Find all site's news items, based on some filters.
32
+	 * Omitting parameters will prevent relevant filters from being applied. The filters are ANDed together.
33
+	 *
34
+	 * @param string $className The name of the class to fetch.
35
+	 * @param int $parentID The ID of the holder to extract the news items from.
36
+	 * @param int $tagID The ID of the tag to filter the news items by.
37
+	 * @param string $dateFrom The beginning of a date filter range.
38
+	 * @param string $dateTo The end of the date filter range. If empty, only one day will be searched for.
39
+	 * @param int $year Numeric value of the year to show.
40
+	 * @param int $monthNumber Numeric value of the month to show.
41
+	 *
42
+	 * @returns DataList|PaginatedList
43
+	 */
44
+	public static function AllUpdates(
45
+		$className = 'Events',
46
+		$parentID = null,
47
+		$tagID = null,
48
+		$dateFrom = null,
49
+		$dateTo = null,
50
+		$year = null,
51
+		$monthNumber = null
52
+	) {
53
+		return parent::AllUpdates(
54
+			$className,
55
+			$parentID,
56
+			$tagID,
57
+			$dateFrom,
58
+			$dateTo,
59
+			$year,
60
+			$monthNumber
61
+		)->Sort('Date', 'ASC');
62
+	}
63 63
 }
Please login to merge, or discard this patch.
src/Model/Quicklink.php 1 patch
Indentation   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -15,121 +15,121 @@
 block discarded – undo
15 15
  */
16 16
 class Quicklink extends DataObject
17 17
 {
18
-    private static $db = [
19
-        'Name' => 'Varchar(255)',
20
-        'ExternalLink' => 'Varchar(255)',
21
-        'SortOrder' => 'Int',
22
-    ];
23
-
24
-    private static $has_one = [
25
-        'Parent' => BaseHomePage::class,
26
-        'InternalLink' => SiteTree::class,
27
-    ];
28
-
29
-    private static $summary_fields = [
30
-        'Name' => 'Name',
31
-        'InternalLink.Title' => 'Internal Link',
32
-        'ExternalLink' => 'External Link',
33
-    ];
34
-
35
-    private static $table_name = 'Quicklink';
36
-
37
-    public function fieldLabels($includerelations = true)
38
-    {
39
-        $labels = parent::fieldLabels($includerelations);
40
-        $labels['Name'] = _t(__CLASS__ . '.NameLabel', 'Name');
41
-        $labels['ExternalLink'] = _t(__CLASS__ . '.ExternalLinkLabel', 'External Link');
42
-        $labels['SortOrder'] = _t(__CLASS__ . '.SortOrderLabel', 'Sort Order');
43
-        $labels['ParentID'] = _t(__CLASS__ . '.ParentRelationLabel', 'Parent');
44
-        $labels['InternalLinkID'] = _t(__CLASS__ . '.InternalLinkLabel', 'Internal Link');
45
-
46
-        return $labels;
47
-    }
48
-
49
-    public function getLink()
50
-    {
51
-        if ($this->ExternalLink) {
52
-            $url = parse_url($this->ExternalLink);
53
-
54
-            // if no scheme set in the link, default to http
55
-            if (!isset($url['scheme'])) {
56
-                return 'http://' . $this->ExternalLink;
57
-            }
58
-
59
-            return $this->ExternalLink;
60
-        }
61
-
62
-        if ($this->InternalLinkID) {
63
-            return $this->InternalLink()->Link();
64
-        }
65
-    }
66
-
67
-    public function canCreate($member = null, $context = [])
68
-    {
69
-        // Creating quick links should not be the same permission level as creating parent pages for them, they're
70
-        // essentially content in the context of the page, so use the edit permission instead.
71
-        return $this->canEdit($member);
72
-    }
73
-
74
-    public function canEdit($member = null)
75
-    {
76
-        return $this->Parent()->canEdit($member);
77
-    }
78
-
79
-    public function canDelete($member = null)
80
-    {
81
-        return $this->Parent()->canDelete($member);
82
-    }
83
-
84
-    public function canView($member = null)
85
-    {
86
-        return $this->Parent()->canView($member);
87
-    }
88
-
89
-    public function getCMSFields()
90
-    {
91
-        $fields = parent::getCMSFields();
92
-
93
-        $fields->removeByName('ParentID');
94
-
95
-        $externalLinkField = $fields->fieldByName('Root.Main.ExternalLink');
96
-
97
-        $fields->removeByName('ExternalLink');
98
-        $fields->removeByName('InternalLinkID');
99
-        $fields->removeByName('SortOrder');
100
-        $externalLinkField->addExtraClass('noBorder');
101
-
102
-        $fields->addFieldToTab('Root.Main', CompositeField::create(
103
-            array(
104
-                TreeDropdownField::create(
105
-                    'InternalLinkID',
106
-                    $this->fieldLabel('InternalLinkID'),
107
-                    SiteTree::class
108
-                ),
109
-                $externalLinkField,
110
-                $wrap = CompositeField::create(
111
-                    $extraLabel = LiteralField::create(
112
-                        'NoteOverride',
113
-                        sprintf('<div class="message good notice">%s</div>', _t(
114
-                            __CLASS__ . '.Note',
115
-                            'Note: If you specify an External Link, the Internal Link will be ignored.'
116
-                        ))
117
-                    )
118
-                )
119
-            )
120
-        ));
121
-        $fields->insertBefore(
122
-            'Name',
123
-            LiteralField::create(
124
-                'Note',
125
-                sprintf('<p>%s</p>', _t(
126
-                    __CLASS__ . '.Note2',
127
-                    'Use this to specify a link to a page either on this site '
128
-                        . '(Internal Link) or another site (External Link).'
129
-                ))
130
-            )
131
-        );
132
-
133
-        return $fields;
134
-    }
18
+	private static $db = [
19
+		'Name' => 'Varchar(255)',
20
+		'ExternalLink' => 'Varchar(255)',
21
+		'SortOrder' => 'Int',
22
+	];
23
+
24
+	private static $has_one = [
25
+		'Parent' => BaseHomePage::class,
26
+		'InternalLink' => SiteTree::class,
27
+	];
28
+
29
+	private static $summary_fields = [
30
+		'Name' => 'Name',
31
+		'InternalLink.Title' => 'Internal Link',
32
+		'ExternalLink' => 'External Link',
33
+	];
34
+
35
+	private static $table_name = 'Quicklink';
36
+
37
+	public function fieldLabels($includerelations = true)
38
+	{
39
+		$labels = parent::fieldLabels($includerelations);
40
+		$labels['Name'] = _t(__CLASS__ . '.NameLabel', 'Name');
41
+		$labels['ExternalLink'] = _t(__CLASS__ . '.ExternalLinkLabel', 'External Link');
42
+		$labels['SortOrder'] = _t(__CLASS__ . '.SortOrderLabel', 'Sort Order');
43
+		$labels['ParentID'] = _t(__CLASS__ . '.ParentRelationLabel', 'Parent');
44
+		$labels['InternalLinkID'] = _t(__CLASS__ . '.InternalLinkLabel', 'Internal Link');
45
+
46
+		return $labels;
47
+	}
48
+
49
+	public function getLink()
50
+	{
51
+		if ($this->ExternalLink) {
52
+			$url = parse_url($this->ExternalLink);
53
+
54
+			// if no scheme set in the link, default to http
55
+			if (!isset($url['scheme'])) {
56
+				return 'http://' . $this->ExternalLink;
57
+			}
58
+
59
+			return $this->ExternalLink;
60
+		}
61
+
62
+		if ($this->InternalLinkID) {
63
+			return $this->InternalLink()->Link();
64
+		}
65
+	}
66
+
67
+	public function canCreate($member = null, $context = [])
68
+	{
69
+		// Creating quick links should not be the same permission level as creating parent pages for them, they're
70
+		// essentially content in the context of the page, so use the edit permission instead.
71
+		return $this->canEdit($member);
72
+	}
73
+
74
+	public function canEdit($member = null)
75
+	{
76
+		return $this->Parent()->canEdit($member);
77
+	}
78
+
79
+	public function canDelete($member = null)
80
+	{
81
+		return $this->Parent()->canDelete($member);
82
+	}
83
+
84
+	public function canView($member = null)
85
+	{
86
+		return $this->Parent()->canView($member);
87
+	}
88
+
89
+	public function getCMSFields()
90
+	{
91
+		$fields = parent::getCMSFields();
92
+
93
+		$fields->removeByName('ParentID');
94
+
95
+		$externalLinkField = $fields->fieldByName('Root.Main.ExternalLink');
96
+
97
+		$fields->removeByName('ExternalLink');
98
+		$fields->removeByName('InternalLinkID');
99
+		$fields->removeByName('SortOrder');
100
+		$externalLinkField->addExtraClass('noBorder');
101
+
102
+		$fields->addFieldToTab('Root.Main', CompositeField::create(
103
+			array(
104
+				TreeDropdownField::create(
105
+					'InternalLinkID',
106
+					$this->fieldLabel('InternalLinkID'),
107
+					SiteTree::class
108
+				),
109
+				$externalLinkField,
110
+				$wrap = CompositeField::create(
111
+					$extraLabel = LiteralField::create(
112
+						'NoteOverride',
113
+						sprintf('<div class="message good notice">%s</div>', _t(
114
+							__CLASS__ . '.Note',
115
+							'Note: If you specify an External Link, the Internal Link will be ignored.'
116
+						))
117
+					)
118
+				)
119
+			)
120
+		));
121
+		$fields->insertBefore(
122
+			'Name',
123
+			LiteralField::create(
124
+				'Note',
125
+				sprintf('<p>%s</p>', _t(
126
+					__CLASS__ . '.Note2',
127
+					'Use this to specify a link to a page either on this site '
128
+						. '(Internal Link) or another site (External Link).'
129
+				))
130
+			)
131
+		);
132
+
133
+		return $fields;
134
+	}
135 135
 }
Please login to merge, or discard this patch.
tests/PageTypes/NewsPageTest.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -9,21 +9,21 @@
 block discarded – undo
9 9
 
10 10
 class NewsPageTest extends SapphireTest
11 11
 {
12
-    protected $usesDatabase = true;
12
+	protected $usesDatabase = true;
13 13
 
14
-    public function testGetNewsPageAuthor()
15
-    {
16
-        $holder = new NewsHolder();
17
-        $holder->Title = 'Holder';
18
-        $holder->write();
14
+	public function testGetNewsPageAuthor()
15
+	{
16
+		$holder = new NewsHolder();
17
+		$holder->Title = 'Holder';
18
+		$holder->write();
19 19
 
20
-        $page = new NewsPage();
21
-        $page->Author = 'Leslie Lawless';
22
-        $page->ParentID = $holder->ID;
23
-        $page->write();
20
+		$page = new NewsPage();
21
+		$page->Author = 'Leslie Lawless';
22
+		$page->ParentID = $holder->ID;
23
+		$page->write();
24 24
 
25
-        $field = $page->getNewsPageAuthor();
26
-        $this->assertInstanceOf(DBField::class, $field);
27
-        $this->assertSame('Leslie Lawless', $field->getValue());
28
-    }
25
+		$field = $page->getNewsPageAuthor();
26
+		$this->assertInstanceOf(DBField::class, $field);
27
+		$this->assertSame('Leslie Lawless', $field->getValue());
28
+	}
29 29
 }
Please login to merge, or discard this patch.
src/PageTypes/DatedUpdateHolderController.php 2 patches
Indentation   +366 added lines, -366 removed lines patch added patch discarded remove patch
@@ -35,370 +35,370 @@
 block discarded – undo
35 35
  */
36 36
 class DatedUpdateHolderController extends PageController
37 37
 {
38
-    private static $allowed_actions = [
39
-        'rss',
40
-        'atom',
41
-        'DateRangeForm',
42
-    ];
43
-
44
-    private static $casting = [
45
-        'MetaTitle' => 'Text',
46
-        'FilterDescription' => 'Text',
47
-    ];
48
-
49
-    /**
50
-     * The session key for storing temporary form messages
51
-     *
52
-     * @var string
53
-     */
54
-    const TEMP_FORM_MESSAGE = __CLASS__ . '.TempFormMessage';
55
-
56
-    /**
57
-     * Get the meta title for the current action
58
-     *
59
-     * @return string
60
-     */
61
-    public function getMetaTitle()
62
-    {
63
-        $title = $this->data()->getTitle();
64
-        $filter = $this->FilterDescription();
65
-        if ($filter) {
66
-            $title = "{$title} - {$filter}";
67
-        }
68
-
69
-        $this->extend('updateMetaTitle', $title);
70
-        return $title;
71
-    }
72
-
73
-    /**
74
-     * Returns a description of the current filter
75
-     *
76
-     * @return string
77
-     */
78
-    public function FilterDescription()
79
-    {
80
-        $params = $this->parseParams();
81
-
82
-        $filters = array();
83
-        if ($params['tag']) {
84
-            $term = TaxonomyTerm::get_by_id(TaxonomyTerm::class, $params['tag']);
85
-            if ($term) {
86
-                $filters[] = _t(
87
-                    'CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_WITHIN',
88
-                    'within'
89
-                ) . ' "' . $term->Name . '"';
90
-            }
91
-        }
92
-
93
-        if ($params['from'] || $params['to']) {
94
-            if ($params['from']) {
95
-                $from = strtotime($params['from']);
96
-                if ($params['to']) {
97
-                    $to = strtotime($params['to']);
98
-                    $filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_BETWEEN', 'between') . ' '
99
-                        . date('j/m/Y', $from) . ' and ' . date('j/m/Y', $to);
100
-                } else {
101
-                    $filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_ON', 'on')
102
-                        . ' ' . date('j/m/Y', $from);
103
-                }
104
-            } else {
105
-                $to = strtotime($params['to']);
106
-                $filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_ON', 'on')
107
-                    . ' ' . date('j/m/Y', $to);
108
-            }
109
-        }
110
-
111
-        if ($params['year'] && $params['month']) {
112
-            $timestamp = mktime(1, 1, 1, $params['month'], 1, $params['year']);
113
-            $filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_IN', 'in')
114
-                . ' ' . date('F', $timestamp) . ' ' . $params['year'];
115
-        }
116
-
117
-        if ($filters) {
118
-            return $this->getUpdateName() . ' ' . implode(' ', $filters);
119
-        }
120
-    }
121
-
122
-    public function getUpdateName()
123
-    {
124
-        return Config::inst()->get($this->data()->ClassName, 'update_name');
125
-    }
126
-
127
-    protected function init()
128
-    {
129
-        parent::init();
130
-        RSSFeed::linkToFeed($this->Link() . 'rss', $this->getSubscriptionTitle());
131
-    }
132
-
133
-    /**
134
-     * Parse URL parameters.
135
-     *
136
-     * @param bool $produceErrorMessages Set to false to omit session messages.
137
-     */
138
-    public function parseParams($produceErrorMessages = true)
139
-    {
140
-        $tag = $this->request->getVar('tag');
141
-        $from = $this->request->getVar('from');
142
-        $to = $this->request->getVar('to');
143
-        $year = $this->request->getVar('year');
144
-        $month = $this->request->getVar('month');
145
-
146
-        if ($tag == '') {
147
-            $tag = null;
148
-        }
149
-        if ($from == '') {
150
-            $from = null;
151
-        }
152
-        if ($to == '') {
153
-            $to = null;
154
-        }
155
-        if ($year == '') {
156
-            $year = null;
157
-        }
158
-        if ($month == '') {
159
-            $month = null;
160
-        }
161
-
162
-        if (isset($tag)) {
163
-            $tag = (int)$tag;
164
-        }
165
-        try {
166
-            if (isset($from)) {
167
-                $from = urldecode($from);
168
-                $parser = DBDatetime::create();
169
-                $parser->setValue($from);
170
-                $from = $parser->Format('y-MM-dd');
171
-            }
172
-            if (isset($to)) {
173
-                $to = urldecode($to);
174
-                $parser = DBDatetime::create();
175
-                $parser->setValue($to);
176
-                $to = $parser->Format('y-MM-dd');
177
-            }
178
-        } catch (InvalidArgumentException $e) {
179
-            if ($produceErrorMessages) {
180
-                $this->getRequest()->getSession()->set(self::TEMP_FORM_MESSAGE, _t(
181
-                    __CLASS__ . '.InvalidDateFormat',
182
-                    'Dates must be in "y-MM-dd" format.'
183
-                ));
184
-            }
185
-        }
186
-        if (isset($year)) {
187
-            $year = (int)$year;
188
-        }
189
-        if (isset($month)) {
190
-            $month = (int)$month;
191
-        }
192
-
193
-        // If only "To" has been provided filter by single date. Normalise by swapping with "From".
194
-        if (isset($to) && !isset($from)) {
195
-            list($to, $from) = [$from, $to];
196
-        }
197
-
198
-        // Flip the dates if the order is wrong.
199
-        if (isset($to) && isset($from) && strtotime($from) > strtotime($to)) {
200
-            list($to, $from) = [$from, $to];
201
-
202
-            if ($produceErrorMessages) {
203
-                $this->getRequest()->getSession()->set(self::TEMP_FORM_MESSAGE, _t(
204
-                    __CLASS__ . '.FilterAppliedMessage',
205
-                    'Filter has been applied with the dates reversed.'
206
-                ));
207
-            }
208
-        }
209
-
210
-        // Notify the user that filtering by single date is taking place.
211
-        if (isset($from) && !isset($to)) {
212
-            if ($produceErrorMessages) {
213
-                $this->getRequest()->getSession()->set(self::TEMP_FORM_MESSAGE, _t(
214
-                    __CLASS__ . '.DateRangeFilterMessage',
215
-                    'Filtered by a single date.'
216
-                ));
217
-            }
218
-        }
219
-
220
-        return [
221
-            'tag' => $tag,
222
-            'from' => $from,
223
-            'to' => $to,
224
-            'year' => $year,
225
-            'month' => $month,
226
-        ];
227
-    }
228
-
229
-    /**
230
-     * Build the link - keep the date range, reset the rest.
231
-     */
232
-    public function AllTagsLink()
233
-    {
234
-        $link = HTTP::setGetVar('tag', null, null, '&');
235
-        $link = HTTP::setGetVar('month', null, $link, '&');
236
-        $link = HTTP::setGetVar('year', null, $link, '&');
237
-        $link = HTTP::setGetVar('start', null, $link, '&');
238
-
239
-        return $link;
240
-    }
241
-
242
-    /**
243
-     * List tags and attach links.
244
-     */
245
-    public function UpdateTagsWithLinks()
246
-    {
247
-        $tags = $this->UpdateTags();
248
-
249
-        $processed = ArrayList::create();
250
-
251
-        foreach ($tags as $tag) {
252
-            // Build the link - keep the tag, and date range, but reset month, year and pagination.
253
-            $link = HTTP::setGetVar('tag', $tag->ID, null, '&');
254
-            $link = HTTP::setGetVar('month', null, $link, '&');
255
-            $link = HTTP::setGetVar('year', null, $link, '&');
256
-            $link = HTTP::setGetVar('start', null, $link, '&');
257
-
258
-            $tag->Link = $link;
259
-            $processed->push($tag);
260
-        }
261
-
262
-        return $processed;
263
-    }
264
-
265
-    /**
266
-     * Get the TaxonomyTerm related to the current tag GET parameter.
267
-     */
268
-    public function CurrentTag()
269
-    {
270
-        $tagID = $this->request->getVar('tag');
271
-
272
-        if (isset($tagID)) {
273
-            return TaxonomyTerm::get_by_id(TaxonomyTerm::class, (int)$tagID);
274
-        }
275
-    }
276
-
277
-    /**
278
-     * Extract the available months based on the current query.
279
-     * Only tag is respected. Pagination and months are ignored.
280
-     */
281
-    public function AvailableMonths()
282
-    {
283
-        $params = $this->parseParams();
284
-
285
-        return DatedUpdateHolder::ExtractMonths(
286
-            $this->Updates($params['tag'], $params['from'], $params['to']),
287
-            Director::makeRelative($_SERVER['REQUEST_URI']),
288
-            $params['year'],
289
-            $params['month']
290
-        );
291
-    }
292
-
293
-    /**
294
-     * Get the updates based on the current query.
295
-     */
296
-    public function FilteredUpdates($pageSize = 20)
297
-    {
298
-        $params = $this->parseParams();
299
-
300
-        $items = $this->Updates(
301
-            $params['tag'],
302
-            $params['from'],
303
-            $params['to'],
304
-            $params['year'],
305
-            $params['month']
306
-        );
307
-
308
-        // Apply pagination
309
-        $list = PaginatedList::create($items, $this->getRequest());
310
-        $list->setPageLength($pageSize);
311
-        return $list;
312
-    }
313
-
314
-    /**
315
-     * @return Form
316
-     */
317
-    public function DateRangeForm()
318
-    {
319
-        $dateFromTitle = DBField::create_field('HTMLText', sprintf(
320
-            '%s <span class="field-note">%s</span>',
321
-            _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FROM_DATE', 'From date'),
322
-            _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.DATE_EXAMPLE', '(example: 30/12/2017)')
323
-        ));
324
-        $dateToTitle = DBField::create_field('HTMLText', sprintf(
325
-            '%s <span class="field-note">%s</span>',
326
-            _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.TO_DATE', 'To date'),
327
-            _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.DATE_EXAMPLE', '(example: 30/12/2017)')
328
-        ));
329
-
330
-        $fields = FieldList::create(
331
-            DateField::create('from', $dateFromTitle),
332
-            DateField::create('to', $dateToTitle),
333
-            HiddenField::create('tag')
334
-        );
335
-
336
-        $actions = FieldList::create(
337
-            FormAction::create("doDateFilter")
338
-                ->setTitle(_t(__CLASS__ . '.Filter', 'Filter'))
339
-                ->addExtraClass('btn btn-primary primary'),
340
-            FormAction::create("doDateReset")
341
-                ->setTitle(_t(__CLASS__ . '.Clear', 'Clear'))
342
-                ->addExtraClass('btn')
343
-        );
344
-
345
-        $form = Form::create($this, 'DateRangeForm', $fields, $actions);
346
-        $form->loadDataFrom($this->request->getVars());
347
-        $form->setFormMethod('get');
348
-
349
-        // Add any locally stored form messages before returning
350
-        if ($formMessage = $this->getRequest()->getSession()->get(self::TEMP_FORM_MESSAGE)) {
351
-            $form->setMessage($formMessage, ValidationResult::TYPE_WARNING);
352
-            $this->getRequest()->getSession()->clear(self::TEMP_FORM_MESSAGE);
353
-        }
354
-
355
-        return $form;
356
-    }
357
-
358
-    public function doDateFilter()
359
-    {
360
-        $params = $this->parseParams();
361
-
362
-        // Build the link - keep the tag, but reset month, year and pagination.
363
-        $link = HTTP::setGetVar('from', $params['from'], $this->AbsoluteLink(), '&');
364
-        $link = HTTP::setGetVar('to', $params['to'], $link, '&');
365
-        if (isset($params['tag'])) {
366
-            $link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
367
-        }
368
-
369
-        $this->redirect($link);
370
-    }
371
-
372
-    public function doDateReset()
373
-    {
374
-        $params = $this->parseParams(false);
375
-
376
-        // Reset the link - only include the tag.
377
-        $link = $this->AbsoluteLink();
378
-        if (isset($params['tag'])) {
379
-            $link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
380
-        }
381
-
382
-        $this->redirect($link);
383
-    }
384
-
385
-    public function rss()
386
-    {
387
-        $rss = RSSFeed::create(
388
-            $this->Updates()->sort('Created DESC')->limit(20),
389
-            $this->Link('rss'),
390
-            $this->getSubscriptionTitle()
391
-        );
392
-        return $rss->outputToBrowser();
393
-    }
394
-
395
-    public function atom()
396
-    {
397
-        $atom = CwpAtomFeed::create(
398
-            $this->Updates()->sort('Created DESC')->limit(20),
399
-            $this->Link('atom'),
400
-            $this->getSubscriptionTitle()
401
-        );
402
-        return $atom->outputToBrowser();
403
-    }
38
+	private static $allowed_actions = [
39
+		'rss',
40
+		'atom',
41
+		'DateRangeForm',
42
+	];
43
+
44
+	private static $casting = [
45
+		'MetaTitle' => 'Text',
46
+		'FilterDescription' => 'Text',
47
+	];
48
+
49
+	/**
50
+	 * The session key for storing temporary form messages
51
+	 *
52
+	 * @var string
53
+	 */
54
+	const TEMP_FORM_MESSAGE = __CLASS__ . '.TempFormMessage';
55
+
56
+	/**
57
+	 * Get the meta title for the current action
58
+	 *
59
+	 * @return string
60
+	 */
61
+	public function getMetaTitle()
62
+	{
63
+		$title = $this->data()->getTitle();
64
+		$filter = $this->FilterDescription();
65
+		if ($filter) {
66
+			$title = "{$title} - {$filter}";
67
+		}
68
+
69
+		$this->extend('updateMetaTitle', $title);
70
+		return $title;
71
+	}
72
+
73
+	/**
74
+	 * Returns a description of the current filter
75
+	 *
76
+	 * @return string
77
+	 */
78
+	public function FilterDescription()
79
+	{
80
+		$params = $this->parseParams();
81
+
82
+		$filters = array();
83
+		if ($params['tag']) {
84
+			$term = TaxonomyTerm::get_by_id(TaxonomyTerm::class, $params['tag']);
85
+			if ($term) {
86
+				$filters[] = _t(
87
+					'CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_WITHIN',
88
+					'within'
89
+				) . ' "' . $term->Name . '"';
90
+			}
91
+		}
92
+
93
+		if ($params['from'] || $params['to']) {
94
+			if ($params['from']) {
95
+				$from = strtotime($params['from']);
96
+				if ($params['to']) {
97
+					$to = strtotime($params['to']);
98
+					$filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_BETWEEN', 'between') . ' '
99
+						. date('j/m/Y', $from) . ' and ' . date('j/m/Y', $to);
100
+				} else {
101
+					$filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_ON', 'on')
102
+						. ' ' . date('j/m/Y', $from);
103
+				}
104
+			} else {
105
+				$to = strtotime($params['to']);
106
+				$filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_ON', 'on')
107
+					. ' ' . date('j/m/Y', $to);
108
+			}
109
+		}
110
+
111
+		if ($params['year'] && $params['month']) {
112
+			$timestamp = mktime(1, 1, 1, $params['month'], 1, $params['year']);
113
+			$filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_IN', 'in')
114
+				. ' ' . date('F', $timestamp) . ' ' . $params['year'];
115
+		}
116
+
117
+		if ($filters) {
118
+			return $this->getUpdateName() . ' ' . implode(' ', $filters);
119
+		}
120
+	}
121
+
122
+	public function getUpdateName()
123
+	{
124
+		return Config::inst()->get($this->data()->ClassName, 'update_name');
125
+	}
126
+
127
+	protected function init()
128
+	{
129
+		parent::init();
130
+		RSSFeed::linkToFeed($this->Link() . 'rss', $this->getSubscriptionTitle());
131
+	}
132
+
133
+	/**
134
+	 * Parse URL parameters.
135
+	 *
136
+	 * @param bool $produceErrorMessages Set to false to omit session messages.
137
+	 */
138
+	public function parseParams($produceErrorMessages = true)
139
+	{
140
+		$tag = $this->request->getVar('tag');
141
+		$from = $this->request->getVar('from');
142
+		$to = $this->request->getVar('to');
143
+		$year = $this->request->getVar('year');
144
+		$month = $this->request->getVar('month');
145
+
146
+		if ($tag == '') {
147
+			$tag = null;
148
+		}
149
+		if ($from == '') {
150
+			$from = null;
151
+		}
152
+		if ($to == '') {
153
+			$to = null;
154
+		}
155
+		if ($year == '') {
156
+			$year = null;
157
+		}
158
+		if ($month == '') {
159
+			$month = null;
160
+		}
161
+
162
+		if (isset($tag)) {
163
+			$tag = (int)$tag;
164
+		}
165
+		try {
166
+			if (isset($from)) {
167
+				$from = urldecode($from);
168
+				$parser = DBDatetime::create();
169
+				$parser->setValue($from);
170
+				$from = $parser->Format('y-MM-dd');
171
+			}
172
+			if (isset($to)) {
173
+				$to = urldecode($to);
174
+				$parser = DBDatetime::create();
175
+				$parser->setValue($to);
176
+				$to = $parser->Format('y-MM-dd');
177
+			}
178
+		} catch (InvalidArgumentException $e) {
179
+			if ($produceErrorMessages) {
180
+				$this->getRequest()->getSession()->set(self::TEMP_FORM_MESSAGE, _t(
181
+					__CLASS__ . '.InvalidDateFormat',
182
+					'Dates must be in "y-MM-dd" format.'
183
+				));
184
+			}
185
+		}
186
+		if (isset($year)) {
187
+			$year = (int)$year;
188
+		}
189
+		if (isset($month)) {
190
+			$month = (int)$month;
191
+		}
192
+
193
+		// If only "To" has been provided filter by single date. Normalise by swapping with "From".
194
+		if (isset($to) && !isset($from)) {
195
+			list($to, $from) = [$from, $to];
196
+		}
197
+
198
+		// Flip the dates if the order is wrong.
199
+		if (isset($to) && isset($from) && strtotime($from) > strtotime($to)) {
200
+			list($to, $from) = [$from, $to];
201
+
202
+			if ($produceErrorMessages) {
203
+				$this->getRequest()->getSession()->set(self::TEMP_FORM_MESSAGE, _t(
204
+					__CLASS__ . '.FilterAppliedMessage',
205
+					'Filter has been applied with the dates reversed.'
206
+				));
207
+			}
208
+		}
209
+
210
+		// Notify the user that filtering by single date is taking place.
211
+		if (isset($from) && !isset($to)) {
212
+			if ($produceErrorMessages) {
213
+				$this->getRequest()->getSession()->set(self::TEMP_FORM_MESSAGE, _t(
214
+					__CLASS__ . '.DateRangeFilterMessage',
215
+					'Filtered by a single date.'
216
+				));
217
+			}
218
+		}
219
+
220
+		return [
221
+			'tag' => $tag,
222
+			'from' => $from,
223
+			'to' => $to,
224
+			'year' => $year,
225
+			'month' => $month,
226
+		];
227
+	}
228
+
229
+	/**
230
+	 * Build the link - keep the date range, reset the rest.
231
+	 */
232
+	public function AllTagsLink()
233
+	{
234
+		$link = HTTP::setGetVar('tag', null, null, '&');
235
+		$link = HTTP::setGetVar('month', null, $link, '&');
236
+		$link = HTTP::setGetVar('year', null, $link, '&');
237
+		$link = HTTP::setGetVar('start', null, $link, '&');
238
+
239
+		return $link;
240
+	}
241
+
242
+	/**
243
+	 * List tags and attach links.
244
+	 */
245
+	public function UpdateTagsWithLinks()
246
+	{
247
+		$tags = $this->UpdateTags();
248
+
249
+		$processed = ArrayList::create();
250
+
251
+		foreach ($tags as $tag) {
252
+			// Build the link - keep the tag, and date range, but reset month, year and pagination.
253
+			$link = HTTP::setGetVar('tag', $tag->ID, null, '&');
254
+			$link = HTTP::setGetVar('month', null, $link, '&');
255
+			$link = HTTP::setGetVar('year', null, $link, '&');
256
+			$link = HTTP::setGetVar('start', null, $link, '&');
257
+
258
+			$tag->Link = $link;
259
+			$processed->push($tag);
260
+		}
261
+
262
+		return $processed;
263
+	}
264
+
265
+	/**
266
+	 * Get the TaxonomyTerm related to the current tag GET parameter.
267
+	 */
268
+	public function CurrentTag()
269
+	{
270
+		$tagID = $this->request->getVar('tag');
271
+
272
+		if (isset($tagID)) {
273
+			return TaxonomyTerm::get_by_id(TaxonomyTerm::class, (int)$tagID);
274
+		}
275
+	}
276
+
277
+	/**
278
+	 * Extract the available months based on the current query.
279
+	 * Only tag is respected. Pagination and months are ignored.
280
+	 */
281
+	public function AvailableMonths()
282
+	{
283
+		$params = $this->parseParams();
284
+
285
+		return DatedUpdateHolder::ExtractMonths(
286
+			$this->Updates($params['tag'], $params['from'], $params['to']),
287
+			Director::makeRelative($_SERVER['REQUEST_URI']),
288
+			$params['year'],
289
+			$params['month']
290
+		);
291
+	}
292
+
293
+	/**
294
+	 * Get the updates based on the current query.
295
+	 */
296
+	public function FilteredUpdates($pageSize = 20)
297
+	{
298
+		$params = $this->parseParams();
299
+
300
+		$items = $this->Updates(
301
+			$params['tag'],
302
+			$params['from'],
303
+			$params['to'],
304
+			$params['year'],
305
+			$params['month']
306
+		);
307
+
308
+		// Apply pagination
309
+		$list = PaginatedList::create($items, $this->getRequest());
310
+		$list->setPageLength($pageSize);
311
+		return $list;
312
+	}
313
+
314
+	/**
315
+	 * @return Form
316
+	 */
317
+	public function DateRangeForm()
318
+	{
319
+		$dateFromTitle = DBField::create_field('HTMLText', sprintf(
320
+			'%s <span class="field-note">%s</span>',
321
+			_t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FROM_DATE', 'From date'),
322
+			_t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.DATE_EXAMPLE', '(example: 30/12/2017)')
323
+		));
324
+		$dateToTitle = DBField::create_field('HTMLText', sprintf(
325
+			'%s <span class="field-note">%s</span>',
326
+			_t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.TO_DATE', 'To date'),
327
+			_t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.DATE_EXAMPLE', '(example: 30/12/2017)')
328
+		));
329
+
330
+		$fields = FieldList::create(
331
+			DateField::create('from', $dateFromTitle),
332
+			DateField::create('to', $dateToTitle),
333
+			HiddenField::create('tag')
334
+		);
335
+
336
+		$actions = FieldList::create(
337
+			FormAction::create("doDateFilter")
338
+				->setTitle(_t(__CLASS__ . '.Filter', 'Filter'))
339
+				->addExtraClass('btn btn-primary primary'),
340
+			FormAction::create("doDateReset")
341
+				->setTitle(_t(__CLASS__ . '.Clear', 'Clear'))
342
+				->addExtraClass('btn')
343
+		);
344
+
345
+		$form = Form::create($this, 'DateRangeForm', $fields, $actions);
346
+		$form->loadDataFrom($this->request->getVars());
347
+		$form->setFormMethod('get');
348
+
349
+		// Add any locally stored form messages before returning
350
+		if ($formMessage = $this->getRequest()->getSession()->get(self::TEMP_FORM_MESSAGE)) {
351
+			$form->setMessage($formMessage, ValidationResult::TYPE_WARNING);
352
+			$this->getRequest()->getSession()->clear(self::TEMP_FORM_MESSAGE);
353
+		}
354
+
355
+		return $form;
356
+	}
357
+
358
+	public function doDateFilter()
359
+	{
360
+		$params = $this->parseParams();
361
+
362
+		// Build the link - keep the tag, but reset month, year and pagination.
363
+		$link = HTTP::setGetVar('from', $params['from'], $this->AbsoluteLink(), '&');
364
+		$link = HTTP::setGetVar('to', $params['to'], $link, '&');
365
+		if (isset($params['tag'])) {
366
+			$link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
367
+		}
368
+
369
+		$this->redirect($link);
370
+	}
371
+
372
+	public function doDateReset()
373
+	{
374
+		$params = $this->parseParams(false);
375
+
376
+		// Reset the link - only include the tag.
377
+		$link = $this->AbsoluteLink();
378
+		if (isset($params['tag'])) {
379
+			$link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
380
+		}
381
+
382
+		$this->redirect($link);
383
+	}
384
+
385
+	public function rss()
386
+	{
387
+		$rss = RSSFeed::create(
388
+			$this->Updates()->sort('Created DESC')->limit(20),
389
+			$this->Link('rss'),
390
+			$this->getSubscriptionTitle()
391
+		);
392
+		return $rss->outputToBrowser();
393
+	}
394
+
395
+	public function atom()
396
+	{
397
+		$atom = CwpAtomFeed::create(
398
+			$this->Updates()->sort('Created DESC')->limit(20),
399
+			$this->Link('atom'),
400
+			$this->getSubscriptionTitle()
401
+		);
402
+		return $atom->outputToBrowser();
403
+	}
404 404
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
         }
161 161
 
162 162
         if (isset($tag)) {
163
-            $tag = (int)$tag;
163
+            $tag = (int) $tag;
164 164
         }
165 165
         try {
166 166
             if (isset($from)) {
@@ -184,10 +184,10 @@  discard block
 block discarded – undo
184 184
             }
185 185
         }
186 186
         if (isset($year)) {
187
-            $year = (int)$year;
187
+            $year = (int) $year;
188 188
         }
189 189
         if (isset($month)) {
190
-            $month = (int)$month;
190
+            $month = (int) $month;
191 191
         }
192 192
 
193 193
         // If only "To" has been provided filter by single date. Normalise by swapping with "From".
@@ -270,7 +270,7 @@  discard block
 block discarded – undo
270 270
         $tagID = $this->request->getVar('tag');
271 271
 
272 272
         if (isset($tagID)) {
273
-            return TaxonomyTerm::get_by_id(TaxonomyTerm::class, (int)$tagID);
273
+            return TaxonomyTerm::get_by_id(TaxonomyTerm::class, (int) $tagID);
274 274
         }
275 275
     }
276 276
 
Please login to merge, or discard this patch.
tests/PageTypes/DatedUpdateHolderControllerTest.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -9,44 +9,44 @@
 block discarded – undo
9 9
 
10 10
 class DatedUpdateHolderControllerTest extends FunctionalTest
11 11
 {
12
-    protected static $fixture_file = 'EventHolderTest.yml';
12
+	protected static $fixture_file = 'EventHolderTest.yml';
13 13
 
14
-    protected static $use_draft_site = true;
14
+	protected static $use_draft_site = true;
15 15
 
16
-    protected function setUp()
17
-    {
18
-        parent::setUp();
16
+	protected function setUp()
17
+	{
18
+		parent::setUp();
19 19
 
20
-        // Note: this test requires the starter theme to be installed
21
-        Config::modify()->set(SSViewer::class, 'themes', ['starter', '$default']);
22
-        Config::modify()->set(SSViewer::class, 'theme', 'starter');
23
-    }
20
+		// Note: this test requires the starter theme to be installed
21
+		Config::modify()->set(SSViewer::class, 'themes', ['starter', '$default']);
22
+		Config::modify()->set(SSViewer::class, 'theme', 'starter');
23
+	}
24 24
 
25
-    public function testSettingDateFiltersInReverseOrderShowsMessage()
26
-    {
27
-        /** @var EventHolder $holder */
28
-        $holder = $this->objFromFixture(EventHolder::class, 'EventHolder1');
25
+	public function testSettingDateFiltersInReverseOrderShowsMessage()
26
+	{
27
+		/** @var EventHolder $holder */
28
+		$holder = $this->objFromFixture(EventHolder::class, 'EventHolder1');
29 29
 
30
-        $result = $this->get($holder->Link() . '?from=2018-01-10&to=2018-01-01');
30
+		$result = $this->get($holder->Link() . '?from=2018-01-10&to=2018-01-01');
31 31
 
32
-        $this->assertContains('Filter has been applied with the dates reversed', $result->getBody());
33
-    }
32
+		$this->assertContains('Filter has been applied with the dates reversed', $result->getBody());
33
+	}
34 34
 
35
-    public function testSettingFromButNotToDateShowsMessage()
36
-    {
37
-        /** @var EventHolder $holder */
38
-        $holder = $this->objFromFixture(EventHolder::class, 'EventHolder1');
35
+	public function testSettingFromButNotToDateShowsMessage()
36
+	{
37
+		/** @var EventHolder $holder */
38
+		$holder = $this->objFromFixture(EventHolder::class, 'EventHolder1');
39 39
 
40
-        $result = $this->get($holder->Link() . '?from=2018-01-10');
40
+		$result = $this->get($holder->Link() . '?from=2018-01-10');
41 41
 
42
-        $this->assertContains('Filtered by a single date', $result->getBody());
43
-    }
42
+		$this->assertContains('Filtered by a single date', $result->getBody());
43
+	}
44 44
 
45
-    public function testInvalidDateFormat()
46
-    {
47
-        /** @var EventHolder $holder */
48
-        $holder = $this->objFromFixture(EventHolder::class, 'EventHolder1');
49
-        $result = $this->get($holder->Link() . '?from=christmas&to=2018-01-10');
50
-        $this->assertContains(htmlentities('Dates must be in "y-MM-dd" format.'), $result->getBody());
51
-    }
45
+	public function testInvalidDateFormat()
46
+	{
47
+		/** @var EventHolder $holder */
48
+		$holder = $this->objFromFixture(EventHolder::class, 'EventHolder1');
49
+		$result = $this->get($holder->Link() . '?from=christmas&to=2018-01-10');
50
+		$this->assertContains(htmlentities('Dates must be in "y-MM-dd" format.'), $result->getBody());
51
+	}
52 52
 }
Please login to merge, or discard this patch.