Completed
Pull Request — master (#15)
by Robbie
04:45
created
src/PageTypes/BaseHomePageController.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -6,20 +6,20 @@
 block discarded – undo
6 6
 
7 7
 class BaseHomePageController extends PageController
8 8
 {
9
-    public function getNewsPage()
10
-    {
11
-        return NewsHolder::get_one(NewsHolder::class);
12
-    }
9
+	public function getNewsPage()
10
+	{
11
+		return NewsHolder::get_one(NewsHolder::class);
12
+	}
13 13
 
14
-    /**
15
-     * @param int $amount The amount of items to provide.
16
-     */
17
-    public function getNewsItems($amount = 2)
18
-    {
19
-        $newsHolder = $this->getNewsPage();
20
-        if ($newsHolder) {
21
-            $controller = NewsHolderController::create($newsHolder);
22
-            return $controller->Updates()->limit($amount);
23
-        }
24
-    }
14
+	/**
15
+	 * @param int $amount The amount of items to provide.
16
+	 */
17
+	public function getNewsItems($amount = 2)
18
+	{
19
+		$newsHolder = $this->getNewsPage();
20
+		if ($newsHolder) {
21
+			$controller = NewsHolderController::create($newsHolder);
22
+			return $controller->Updates()->limit($amount);
23
+		}
24
+	}
25 25
 }
Please login to merge, or discard this patch.
src/PageTypes/DatedUpdateHolder.php 2 patches
Indentation   +243 added lines, -243 removed lines patch added patch discarded remove patch
@@ -17,247 +17,247 @@
 block discarded – undo
17 17
 
18 18
 class DatedUpdateHolder extends Page
19 19
 {
20
-    /**
21
-     * Meant as an abstract base class.
22
-     *
23
-     * {@inheritDoc}
24
-     */
25
-    private static $hide_ancestor = DatedUpdateHolder::class;
26
-
27
-    private static $update_name = 'Updates';
28
-
29
-    private static $update_class = DatedUpdatePage::class;
30
-
31
-    private static $singular_name = 'Dated Update Holder';
32
-
33
-    private static $plural_name = 'Dated Update Holders';
34
-
35
-    private static $table_name = 'DatedUpdateHolder';
36
-
37
-    /**
38
-     * Find all distinct tags (TaxonomyTerms) associated with the DatedUpdatePages under this holder.
39
-     */
40
-    public function UpdateTags()
41
-    {
42
-        $siteTree = DataObject::getSchema()->tableName(SiteTree::class);
43
-        $taxonomy = DataObject::getSchema()->tableName(TaxonomyTerm::class);
44
-
45
-        $tags = TaxonomyTerm::get()
46
-            ->innerJoin('BasePage_Terms', sprintf('"%s"."ID"="BasePage_Terms"."TaxonomyTermID"', $taxonomy))
47
-            ->innerJoin(
48
-                $siteTree,
49
-                sprintf(
50
-                    '"%s"."ID" = "BasePage_Terms"."BasePageID" AND "%s"."ParentID" = \'%d\'',
51
-                    $siteTree,
52
-                    $siteTree,
53
-                    $this->ID
54
-                )
55
-            )
56
-            ->sort('Name');
57
-
58
-        return $tags;
59
-    }
60
-
61
-    /**
62
-     * Wrapper to find all updates belonging to this holder, based on some filters.
63
-     */
64
-    public function Updates($tagID = null, $dateFrom = null, $dateTo = null, $year = null, $monthNumber = null)
65
-    {
66
-        $className = Config::inst()->get($this->ClassName, 'update_class');
67
-        return static::AllUpdates($className, $this->ID, $tagID, $dateFrom, $dateTo, $year, $monthNumber);
68
-    }
69
-
70
-    /**
71
-     * Find all site's updates, based on some filters.
72
-     * Omitting parameters will prevent relevant filters from being applied. The filters are ANDed together.
73
-     *
74
-     * @param string $className The name of the class to fetch.
75
-     * @param int|null $parentID The ID of the holder to extract the updates from.
76
-     * @param int|null $tagID The ID of the tag to filter the updates by.
77
-     * @param string|null $dateFrom The beginning of a date filter range.
78
-     * @param string|null $dateTo The end of the date filter range. If empty, only one day will be searched for.
79
-     * @param int|null $year Numeric value of the year to show.
80
-     * @param int|null $monthNumber Numeric value of the month to show.
81
-     *
82
-     * @returns DataList | PaginatedList
83
-     */
84
-    public static function AllUpdates(
85
-        $className = DatedUpdatePage::class,
86
-        $parentID = null,
87
-        $tagID = null,
88
-        $dateFrom = null,
89
-        $dateTo = null,
90
-        $year = null,
91
-        $monthNumber = null
92
-    ) {
93
-
94
-        $items = $className::get();
95
-        $dbTableName = DataObject::getSchema()->tableForField($className, 'Date');
96
-        if (!$dbTableName) {
97
-            $dbTableName = DatedUpdatePage::class;
98
-        }
99
-
100
-        // Filter by parent holder.
101
-        if (isset($parentID)) {
102
-            $items = $items->filter(['ParentID'=>$parentID]);
103
-        }
104
-
105
-        // Filter down to a single tag.
106
-        if (isset($tagID)) {
107
-            $taxonomy = DataObject::getSchema()->tableName(TaxonomyTerm::class);
108
-            $tableName = DataObject::getSchema()->tableName($className);
109
-
110
-            $items = $items->innerJoin(
111
-                'BasePage_Terms',
112
-                sprintf('"%s"."ID" = "BasePage_Terms"."BasePageID"', $tableName)
113
-            )->innerJoin(
114
-                $taxonomy,
115
-                sprintf(
116
-                    '"BasePage_Terms"."TaxonomyTermID" = "%s"."ID" AND "TaxonomyTerm"."ID" = \'%d\'',
117
-                    $taxonomy,
118
-                    $tagID
119
-                )
120
-            );
121
-        }
122
-
123
-        // Filter by date
124
-        if (isset($dateFrom)) {
125
-            if (!isset($dateTo)) {
126
-                $dateTo = $dateFrom;
127
-            }
128
-
129
-            $items = $items->where([
130
-                sprintf('"%s"."Date" >= \'%s\'', $dbTableName, Convert::raw2sql("$dateFrom 00:00:00")),
131
-                sprintf('"%s"."Date" <= \'%s\'', $dbTableName, Convert::raw2sql("$dateTo 23:59:59"))
132
-            ]);
133
-        }
134
-
135
-        // Filter down to single month.
136
-        if (isset($year) && isset($monthNumber)) {
137
-            $year = (int)$year;
138
-            $monthNumber = (int)$monthNumber;
139
-
140
-            $beginDate = sprintf("%04d-%02d-01 00:00:00", $year, $monthNumber);
141
-            $endDate = date('Y-m-d H:i:s', strtotime("{$beginDate} +1 month"));
142
-
143
-            $items = $items->where(array(
144
-                sprintf('"%s"."Date" >= \'%s\'', $dbTableName, Convert::raw2sql($beginDate)),
145
-                sprintf('"%s"."Date" < \'%s\'', $dbTableName, Convert::raw2sql($endDate))
146
-            ));
147
-        }
148
-
149
-        // Unpaginated DataList.
150
-        return $items;
151
-    }
152
-
153
-    /**
154
-     * Produce an ArrayList of available months out of the updates contained in the DataList.
155
-     *
156
-     * Here is an example of the returned structure:
157
-     * ArrayList:
158
-     *   ArrayData:
159
-     *     YearName => 2013
160
-     *     Months => ArrayList:
161
-     *       MonthName => Jan
162
-     *       MonthNumber => 1
163
-     *       MonthLink => (page URL)year=2012&month=1
164
-     *       Active => true
165
-     *   ArrayData:
166
-     *     YearName => 2012
167
-     *     Months => ArrayList:
168
-     *     ...
169
-     *
170
-     * @param DataList $updates DataList DataList to extract months from.
171
-     * @param string $link Link used as abase to construct the MonthLink.
172
-     * @param int $currentYear Currently selected year, for computing the link active state.
173
-     * @param int $currentMonthNumber Currently selected month, for computing the link active state.
174
-     *
175
-     * @returns ArrayList
176
-     */
177
-    public static function ExtractMonths(
178
-        DataList $updates,
179
-        $link = null,
180
-        $currentYear = null,
181
-        $currentMonthNumber = null
182
-    ) {
183
-        // Set the link to current URL in the same way the HTTP::setGetVar does it.
184
-        if (!isset($link)) {
185
-            $link = Director::makeRelative($_SERVER['REQUEST_URI']);
186
-        }
187
-
188
-        $dates = $updates->dataQuery()
189
-            ->groupby('YEAR("Date")')
190
-            ->groupby('MONTH("Date")')
191
-            ->query()
192
-            ->setSelect([
193
-                'Year' => 'YEAR("Date")',
194
-                'Month' => 'MONTH("Date")',
195
-            ])
196
-            ->addWhere('"Date" IS NOT NULL')
197
-            ->setOrderBy([
198
-                'YEAR("Date")' => 'DESC',
199
-                'MONTH("Date")' => 'DESC',
200
-            ])
201
-            ->execute();
202
-
203
-        $years = [];
204
-        foreach ($dates as $date) {
205
-            $monthNumber = $date['Month'];
206
-            $year = $date['Year'];
207
-            $dateObj = new DateTime(implode('-', [$year, $monthNumber, 1]));
208
-            $monthName = $dateObj->Format('M');
209
-
210
-            // Set up the relevant year array, if not yet available.
211
-            if (!isset($years[$year])) {
212
-                $years[$year] = ['YearName'=>$year, 'Months' => []];
213
-            }
214
-
215
-            // Check if the currently processed month is the one that is selected via GET params.
216
-            $active = false;
217
-            if (isset($year) && isset($monthNumber)) {
218
-                $active = (((int)$currentYear)==$year && ((int)$currentMonthNumber)==$monthNumber);
219
-            }
220
-
221
-            // Build the link - keep the tag and date filter, but reset the pagination.
222
-            if ($active) {
223
-                // Allow clicking to deselect the month.
224
-                $link = HTTP::setGetVar('month', null, $link, '&');
225
-                $link = HTTP::setGetVar('year', null, $link, '&');
226
-            } else {
227
-                $link = HTTP::setGetVar('month', $monthNumber, $link, '&');
228
-                $link = HTTP::setGetVar('year', $year, $link, '&');
229
-            }
230
-            $link = HTTP::setGetVar('start', null, $link, '&');
231
-
232
-            $years[$year]['Months'][$monthNumber] = array(
233
-                'MonthName'=>$monthName,
234
-                'MonthNumber'=>$monthNumber,
235
-                'MonthLink'=>$link,
236
-                'Active'=>$active
237
-            );
238
-        }
239
-
240
-        // ArrayList will not recursively walk through the supplied array, so manually build nested ArrayLists.
241
-        foreach ($years as &$year) {
242
-            $year['Months'] = new ArrayList($year['Months']);
243
-        }
244
-
245
-        // Reverse the list so the most recent years appear first.
246
-        return new ArrayList($years);
247
-    }
248
-
249
-    public function getDefaultRSSLink()
250
-    {
251
-        return $this->Link('rss');
252
-    }
253
-
254
-    public function getDefaultAtomLink()
255
-    {
256
-        return $this->Link('atom');
257
-    }
258
-
259
-    public function getSubscriptionTitle()
260
-    {
261
-        return $this->Title;
262
-    }
20
+	/**
21
+	 * Meant as an abstract base class.
22
+	 *
23
+	 * {@inheritDoc}
24
+	 */
25
+	private static $hide_ancestor = DatedUpdateHolder::class;
26
+
27
+	private static $update_name = 'Updates';
28
+
29
+	private static $update_class = DatedUpdatePage::class;
30
+
31
+	private static $singular_name = 'Dated Update Holder';
32
+
33
+	private static $plural_name = 'Dated Update Holders';
34
+
35
+	private static $table_name = 'DatedUpdateHolder';
36
+
37
+	/**
38
+	 * Find all distinct tags (TaxonomyTerms) associated with the DatedUpdatePages under this holder.
39
+	 */
40
+	public function UpdateTags()
41
+	{
42
+		$siteTree = DataObject::getSchema()->tableName(SiteTree::class);
43
+		$taxonomy = DataObject::getSchema()->tableName(TaxonomyTerm::class);
44
+
45
+		$tags = TaxonomyTerm::get()
46
+			->innerJoin('BasePage_Terms', sprintf('"%s"."ID"="BasePage_Terms"."TaxonomyTermID"', $taxonomy))
47
+			->innerJoin(
48
+				$siteTree,
49
+				sprintf(
50
+					'"%s"."ID" = "BasePage_Terms"."BasePageID" AND "%s"."ParentID" = \'%d\'',
51
+					$siteTree,
52
+					$siteTree,
53
+					$this->ID
54
+				)
55
+			)
56
+			->sort('Name');
57
+
58
+		return $tags;
59
+	}
60
+
61
+	/**
62
+	 * Wrapper to find all updates belonging to this holder, based on some filters.
63
+	 */
64
+	public function Updates($tagID = null, $dateFrom = null, $dateTo = null, $year = null, $monthNumber = null)
65
+	{
66
+		$className = Config::inst()->get($this->ClassName, 'update_class');
67
+		return static::AllUpdates($className, $this->ID, $tagID, $dateFrom, $dateTo, $year, $monthNumber);
68
+	}
69
+
70
+	/**
71
+	 * Find all site's updates, based on some filters.
72
+	 * Omitting parameters will prevent relevant filters from being applied. The filters are ANDed together.
73
+	 *
74
+	 * @param string $className The name of the class to fetch.
75
+	 * @param int|null $parentID The ID of the holder to extract the updates from.
76
+	 * @param int|null $tagID The ID of the tag to filter the updates by.
77
+	 * @param string|null $dateFrom The beginning of a date filter range.
78
+	 * @param string|null $dateTo The end of the date filter range. If empty, only one day will be searched for.
79
+	 * @param int|null $year Numeric value of the year to show.
80
+	 * @param int|null $monthNumber Numeric value of the month to show.
81
+	 *
82
+	 * @returns DataList | PaginatedList
83
+	 */
84
+	public static function AllUpdates(
85
+		$className = DatedUpdatePage::class,
86
+		$parentID = null,
87
+		$tagID = null,
88
+		$dateFrom = null,
89
+		$dateTo = null,
90
+		$year = null,
91
+		$monthNumber = null
92
+	) {
93
+
94
+		$items = $className::get();
95
+		$dbTableName = DataObject::getSchema()->tableForField($className, 'Date');
96
+		if (!$dbTableName) {
97
+			$dbTableName = DatedUpdatePage::class;
98
+		}
99
+
100
+		// Filter by parent holder.
101
+		if (isset($parentID)) {
102
+			$items = $items->filter(['ParentID'=>$parentID]);
103
+		}
104
+
105
+		// Filter down to a single tag.
106
+		if (isset($tagID)) {
107
+			$taxonomy = DataObject::getSchema()->tableName(TaxonomyTerm::class);
108
+			$tableName = DataObject::getSchema()->tableName($className);
109
+
110
+			$items = $items->innerJoin(
111
+				'BasePage_Terms',
112
+				sprintf('"%s"."ID" = "BasePage_Terms"."BasePageID"', $tableName)
113
+			)->innerJoin(
114
+				$taxonomy,
115
+				sprintf(
116
+					'"BasePage_Terms"."TaxonomyTermID" = "%s"."ID" AND "TaxonomyTerm"."ID" = \'%d\'',
117
+					$taxonomy,
118
+					$tagID
119
+				)
120
+			);
121
+		}
122
+
123
+		// Filter by date
124
+		if (isset($dateFrom)) {
125
+			if (!isset($dateTo)) {
126
+				$dateTo = $dateFrom;
127
+			}
128
+
129
+			$items = $items->where([
130
+				sprintf('"%s"."Date" >= \'%s\'', $dbTableName, Convert::raw2sql("$dateFrom 00:00:00")),
131
+				sprintf('"%s"."Date" <= \'%s\'', $dbTableName, Convert::raw2sql("$dateTo 23:59:59"))
132
+			]);
133
+		}
134
+
135
+		// Filter down to single month.
136
+		if (isset($year) && isset($monthNumber)) {
137
+			$year = (int)$year;
138
+			$monthNumber = (int)$monthNumber;
139
+
140
+			$beginDate = sprintf("%04d-%02d-01 00:00:00", $year, $monthNumber);
141
+			$endDate = date('Y-m-d H:i:s', strtotime("{$beginDate} +1 month"));
142
+
143
+			$items = $items->where(array(
144
+				sprintf('"%s"."Date" >= \'%s\'', $dbTableName, Convert::raw2sql($beginDate)),
145
+				sprintf('"%s"."Date" < \'%s\'', $dbTableName, Convert::raw2sql($endDate))
146
+			));
147
+		}
148
+
149
+		// Unpaginated DataList.
150
+		return $items;
151
+	}
152
+
153
+	/**
154
+	 * Produce an ArrayList of available months out of the updates contained in the DataList.
155
+	 *
156
+	 * Here is an example of the returned structure:
157
+	 * ArrayList:
158
+	 *   ArrayData:
159
+	 *     YearName => 2013
160
+	 *     Months => ArrayList:
161
+	 *       MonthName => Jan
162
+	 *       MonthNumber => 1
163
+	 *       MonthLink => (page URL)year=2012&month=1
164
+	 *       Active => true
165
+	 *   ArrayData:
166
+	 *     YearName => 2012
167
+	 *     Months => ArrayList:
168
+	 *     ...
169
+	 *
170
+	 * @param DataList $updates DataList DataList to extract months from.
171
+	 * @param string $link Link used as abase to construct the MonthLink.
172
+	 * @param int $currentYear Currently selected year, for computing the link active state.
173
+	 * @param int $currentMonthNumber Currently selected month, for computing the link active state.
174
+	 *
175
+	 * @returns ArrayList
176
+	 */
177
+	public static function ExtractMonths(
178
+		DataList $updates,
179
+		$link = null,
180
+		$currentYear = null,
181
+		$currentMonthNumber = null
182
+	) {
183
+		// Set the link to current URL in the same way the HTTP::setGetVar does it.
184
+		if (!isset($link)) {
185
+			$link = Director::makeRelative($_SERVER['REQUEST_URI']);
186
+		}
187
+
188
+		$dates = $updates->dataQuery()
189
+			->groupby('YEAR("Date")')
190
+			->groupby('MONTH("Date")')
191
+			->query()
192
+			->setSelect([
193
+				'Year' => 'YEAR("Date")',
194
+				'Month' => 'MONTH("Date")',
195
+			])
196
+			->addWhere('"Date" IS NOT NULL')
197
+			->setOrderBy([
198
+				'YEAR("Date")' => 'DESC',
199
+				'MONTH("Date")' => 'DESC',
200
+			])
201
+			->execute();
202
+
203
+		$years = [];
204
+		foreach ($dates as $date) {
205
+			$monthNumber = $date['Month'];
206
+			$year = $date['Year'];
207
+			$dateObj = new DateTime(implode('-', [$year, $monthNumber, 1]));
208
+			$monthName = $dateObj->Format('M');
209
+
210
+			// Set up the relevant year array, if not yet available.
211
+			if (!isset($years[$year])) {
212
+				$years[$year] = ['YearName'=>$year, 'Months' => []];
213
+			}
214
+
215
+			// Check if the currently processed month is the one that is selected via GET params.
216
+			$active = false;
217
+			if (isset($year) && isset($monthNumber)) {
218
+				$active = (((int)$currentYear)==$year && ((int)$currentMonthNumber)==$monthNumber);
219
+			}
220
+
221
+			// Build the link - keep the tag and date filter, but reset the pagination.
222
+			if ($active) {
223
+				// Allow clicking to deselect the month.
224
+				$link = HTTP::setGetVar('month', null, $link, '&');
225
+				$link = HTTP::setGetVar('year', null, $link, '&');
226
+			} else {
227
+				$link = HTTP::setGetVar('month', $monthNumber, $link, '&');
228
+				$link = HTTP::setGetVar('year', $year, $link, '&');
229
+			}
230
+			$link = HTTP::setGetVar('start', null, $link, '&');
231
+
232
+			$years[$year]['Months'][$monthNumber] = array(
233
+				'MonthName'=>$monthName,
234
+				'MonthNumber'=>$monthNumber,
235
+				'MonthLink'=>$link,
236
+				'Active'=>$active
237
+			);
238
+		}
239
+
240
+		// ArrayList will not recursively walk through the supplied array, so manually build nested ArrayLists.
241
+		foreach ($years as &$year) {
242
+			$year['Months'] = new ArrayList($year['Months']);
243
+		}
244
+
245
+		// Reverse the list so the most recent years appear first.
246
+		return new ArrayList($years);
247
+	}
248
+
249
+	public function getDefaultRSSLink()
250
+	{
251
+		return $this->Link('rss');
252
+	}
253
+
254
+	public function getDefaultAtomLink()
255
+	{
256
+		return $this->Link('atom');
257
+	}
258
+
259
+	public function getSubscriptionTitle()
260
+	{
261
+		return $this->Title;
262
+	}
263 263
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -134,8 +134,8 @@  discard block
 block discarded – undo
134 134
 
135 135
         // Filter down to single month.
136 136
         if (isset($year) && isset($monthNumber)) {
137
-            $year = (int)$year;
138
-            $monthNumber = (int)$monthNumber;
137
+            $year = (int) $year;
138
+            $monthNumber = (int) $monthNumber;
139 139
 
140 140
             $beginDate = sprintf("%04d-%02d-01 00:00:00", $year, $monthNumber);
141 141
             $endDate = date('Y-m-d H:i:s', strtotime("{$beginDate} +1 month"));
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
             // Check if the currently processed month is the one that is selected via GET params.
216 216
             $active = false;
217 217
             if (isset($year) && isset($monthNumber)) {
218
-                $active = (((int)$currentYear)==$year && ((int)$currentMonthNumber)==$monthNumber);
218
+                $active = (((int) $currentYear) == $year && ((int) $currentMonthNumber) == $monthNumber);
219 219
             }
220 220
 
221 221
             // Build the link - keep the tag and date filter, but reset the pagination.
Please login to merge, or discard this patch.
src/PageTypes/SitemapPageController.php 1 patch
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -9,51 +9,51 @@
 block discarded – undo
9 9
 
10 10
 class SitemapPageController extends PageController
11 11
 {
12
-    private static $allowed_actions = [
13
-        'showpage',
14
-    ];
15
-
16
-    private static $url_handlers = [
17
-        'page/$ID' => 'showpage',
18
-    ];
19
-
20
-    public function Page($link)
21
-    {
22
-        if ($link instanceof HTTPRequest) {
23
-            Deprecation::notice('2.0', 'Using page() as a url handler is deprecated. Use showpage() action instead');
24
-            return $this->showpage($link);
25
-        }
26
-        return parent::Page($link);
27
-    }
28
-
29
-    public function showpage($request)
30
-    {
31
-        $id = (int) $request->param('ID');
32
-        if (!$id) {
33
-            return false;
34
-        }
35
-        $page = SiteTree::get()->byId($id);
36
-
37
-        // does the page exist?
38
-        if (!($page && $page->exists())) {
39
-            return $this->httpError(404);
40
-        }
41
-
42
-        // can the page be viewed?
43
-        if (!$page->canView()) {
44
-            return $this->httpError(403);
45
-        }
46
-
47
-        $viewer = $this->customise([
48
-            'IsAjax' => $request->isAjax(),
49
-            'SelectedPage' => $page,
50
-            'Children' => $page->Children(),
51
-        ]);
52
-
53
-        if ($request->isAjax()) {
54
-            return $viewer->renderWith('SitemapNodeChildren');
55
-        }
56
-
57
-        return $viewer;
58
-    }
12
+	private static $allowed_actions = [
13
+		'showpage',
14
+	];
15
+
16
+	private static $url_handlers = [
17
+		'page/$ID' => 'showpage',
18
+	];
19
+
20
+	public function Page($link)
21
+	{
22
+		if ($link instanceof HTTPRequest) {
23
+			Deprecation::notice('2.0', 'Using page() as a url handler is deprecated. Use showpage() action instead');
24
+			return $this->showpage($link);
25
+		}
26
+		return parent::Page($link);
27
+	}
28
+
29
+	public function showpage($request)
30
+	{
31
+		$id = (int) $request->param('ID');
32
+		if (!$id) {
33
+			return false;
34
+		}
35
+		$page = SiteTree::get()->byId($id);
36
+
37
+		// does the page exist?
38
+		if (!($page && $page->exists())) {
39
+			return $this->httpError(404);
40
+		}
41
+
42
+		// can the page be viewed?
43
+		if (!$page->canView()) {
44
+			return $this->httpError(403);
45
+		}
46
+
47
+		$viewer = $this->customise([
48
+			'IsAjax' => $request->isAjax(),
49
+			'SelectedPage' => $page,
50
+			'Children' => $page->Children(),
51
+		]);
52
+
53
+		if ($request->isAjax()) {
54
+			return $viewer->renderWith('SitemapNodeChildren');
55
+		}
56
+
57
+		return $viewer;
58
+	}
59 59
 }
Please login to merge, or discard this patch.
src/Tasks/CleanupGeneratedPdfDailyTask.php 1 patch
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -7,9 +7,9 @@
 block discarded – undo
7 7
 // @todo replace with QueuedJobs
8 8
 class CleanupGeneratedPdfDailyTask // extends DailyTask
9 9
 {
10
-    public function process()
11
-    {
12
-        $task = new CleanupGeneratedPdfBuildTask();
13
-        $task->run(null);
14
-    }
10
+	public function process()
11
+	{
12
+		$task = new CleanupGeneratedPdfBuildTask();
13
+		$task->run(null);
14
+	}
15 15
 }
Please login to merge, or discard this patch.
src/Tasks/PopulateThemeSampleDataTask.php 1 patch
Indentation   +126 added lines, -126 removed lines patch added patch discarded remove patch
@@ -17,130 +17,130 @@
 block discarded – undo
17 17
  */
18 18
 class PopulateThemeSampleDataTask extends BuildTask
19 19
 {
20
-    protected $title = 'Populate sample data for theme demo';
21
-
22
-    protected $description = 'Populates some sample data for showcasing the functionality of the '
23
-        . 'starter and Wātea themes';
24
-
25
-    /**
26
-     * A series of method calls to create sample data
27
-     *
28
-     * @param HTTPRequest $request
29
-     */
30
-    public function run($request)
31
-    {
32
-        $this->handleContactForm();
33
-    }
34
-
35
-    /**
36
-     * Decide whether to create a contact user defined form, and call it to be be created if so
37
-     *
38
-     * @return $this
39
-     */
40
-    protected function handleContactForm()
41
-    {
42
-        if (!$this->getContactFormExists()) {
43
-            $this->createContactForm();
44
-        }
45
-        return $this;
46
-    }
47
-
48
-    /**
49
-     * Determine whether a "contact us" userform exists yet
50
-     *
51
-     * @return bool
52
-     */
53
-    protected function getContactFormExists()
54
-    {
55
-        $exists = false;
56
-        foreach (UserDefinedForm::get()->column('ID') as $formId) {
57
-            $count = Versioned::get_all_versions(UserDefinedForm::class, $formId)
58
-                ->filter('URLSegment', 'contact')
59
-                ->count();
60
-
61
-            if ($count >= 1) {
62
-                $exists = true;
63
-                break;
64
-            }
65
-        }
66
-        return $exists;
67
-    }
68
-
69
-    /**
70
-     * Create a "contact us" userform. Please note that this form does not have any recipients by default, so
71
-     * no emails will be sent. To add recipients - edit the page in the CMS and add a recipient via the "Recipients"
72
-     * tab.
73
-     *
74
-     * @return $this
75
-     */
76
-    protected function createContactForm()
77
-    {
78
-        $form = UserDefinedForm::create(array(
79
-            'Title' => 'Contact',
80
-            'URLSegment' => 'contact',
81
-            'Content' => '<p>$UserDefinedForm</p>',
82
-            'SubmitButtonText' => 'Submit',
83
-            'ClearButtonText' => 'Clear',
84
-            'OnCompleteMessage' => "<p>Thanks, we've received your submission and will be in touch shortly.</p>",
85
-            'EnableLiveValidation' => true
86
-        ));
87
-
88
-        $form->write();
89
-
90
-        // Add form fields
91
-        $fields = array(
92
-            EditableFormStep::create(array(
93
-                'Title' => _t('EditableFormStep.TITLE_FIRST', 'First Page')
94
-            )),
95
-            EditableTextField::create(array(
96
-                'Title' => 'Name',
97
-                'Required' => true,
98
-                'RightTitle' => 'Please enter your first and last name'
99
-            )),
100
-            EditableEmailField::create(array(
101
-                'Title' => Email::class,
102
-                'Required' => true,
103
-                'Placeholder' => '[email protected]'
104
-            )),
105
-            EditableTextField::create(array(
106
-                'Title' => 'Subject'
107
-            )),
108
-            EditableTextField::create(array(
109
-                'Title' => 'Message',
110
-                'Required' => true,
111
-                'Rows' => 5
112
-            ))
113
-        );
114
-
115
-        foreach ($fields as $field) {
116
-            $field->write();
117
-            $form->Fields()->add($field);
118
-            $field->publish('Stage', 'Live');
119
-        }
120
-
121
-        $form->publish('Stage', 'Live');
122
-        $form->flushCache();
123
-
124
-        $this->output(' + Created "contact" UserDefinedForm page');
125
-
126
-        return $this;
127
-    }
128
-
129
-    /**
130
-     * Output a message either to the console or browser
131
-     *
132
-     * @param  string $message
133
-     * @return $this
134
-     */
135
-    protected function output($message)
136
-    {
137
-        if (Director::is_cli()) {
138
-            $message .= PHP_EOL;
139
-        } else {
140
-            $message = sprintf('<p>%s</p>', $message);
141
-        }
142
-        echo $message;
143
-
144
-        return $this;
145
-    }
20
+	protected $title = 'Populate sample data for theme demo';
21
+
22
+	protected $description = 'Populates some sample data for showcasing the functionality of the '
23
+		. 'starter and Wātea themes';
24
+
25
+	/**
26
+	 * A series of method calls to create sample data
27
+	 *
28
+	 * @param HTTPRequest $request
29
+	 */
30
+	public function run($request)
31
+	{
32
+		$this->handleContactForm();
33
+	}
34
+
35
+	/**
36
+	 * Decide whether to create a contact user defined form, and call it to be be created if so
37
+	 *
38
+	 * @return $this
39
+	 */
40
+	protected function handleContactForm()
41
+	{
42
+		if (!$this->getContactFormExists()) {
43
+			$this->createContactForm();
44
+		}
45
+		return $this;
46
+	}
47
+
48
+	/**
49
+	 * Determine whether a "contact us" userform exists yet
50
+	 *
51
+	 * @return bool
52
+	 */
53
+	protected function getContactFormExists()
54
+	{
55
+		$exists = false;
56
+		foreach (UserDefinedForm::get()->column('ID') as $formId) {
57
+			$count = Versioned::get_all_versions(UserDefinedForm::class, $formId)
58
+				->filter('URLSegment', 'contact')
59
+				->count();
60
+
61
+			if ($count >= 1) {
62
+				$exists = true;
63
+				break;
64
+			}
65
+		}
66
+		return $exists;
67
+	}
68
+
69
+	/**
70
+	 * Create a "contact us" userform. Please note that this form does not have any recipients by default, so
71
+	 * no emails will be sent. To add recipients - edit the page in the CMS and add a recipient via the "Recipients"
72
+	 * tab.
73
+	 *
74
+	 * @return $this
75
+	 */
76
+	protected function createContactForm()
77
+	{
78
+		$form = UserDefinedForm::create(array(
79
+			'Title' => 'Contact',
80
+			'URLSegment' => 'contact',
81
+			'Content' => '<p>$UserDefinedForm</p>',
82
+			'SubmitButtonText' => 'Submit',
83
+			'ClearButtonText' => 'Clear',
84
+			'OnCompleteMessage' => "<p>Thanks, we've received your submission and will be in touch shortly.</p>",
85
+			'EnableLiveValidation' => true
86
+		));
87
+
88
+		$form->write();
89
+
90
+		// Add form fields
91
+		$fields = array(
92
+			EditableFormStep::create(array(
93
+				'Title' => _t('EditableFormStep.TITLE_FIRST', 'First Page')
94
+			)),
95
+			EditableTextField::create(array(
96
+				'Title' => 'Name',
97
+				'Required' => true,
98
+				'RightTitle' => 'Please enter your first and last name'
99
+			)),
100
+			EditableEmailField::create(array(
101
+				'Title' => Email::class,
102
+				'Required' => true,
103
+				'Placeholder' => '[email protected]'
104
+			)),
105
+			EditableTextField::create(array(
106
+				'Title' => 'Subject'
107
+			)),
108
+			EditableTextField::create(array(
109
+				'Title' => 'Message',
110
+				'Required' => true,
111
+				'Rows' => 5
112
+			))
113
+		);
114
+
115
+		foreach ($fields as $field) {
116
+			$field->write();
117
+			$form->Fields()->add($field);
118
+			$field->publish('Stage', 'Live');
119
+		}
120
+
121
+		$form->publish('Stage', 'Live');
122
+		$form->flushCache();
123
+
124
+		$this->output(' + Created "contact" UserDefinedForm page');
125
+
126
+		return $this;
127
+	}
128
+
129
+	/**
130
+	 * Output a message either to the console or browser
131
+	 *
132
+	 * @param  string $message
133
+	 * @return $this
134
+	 */
135
+	protected function output($message)
136
+	{
137
+		if (Director::is_cli()) {
138
+			$message .= PHP_EOL;
139
+		} else {
140
+			$message = sprintf('<p>%s</p>', $message);
141
+		}
142
+		echo $message;
143
+
144
+		return $this;
145
+	}
146 146
 }
Please login to merge, or discard this patch.
src/Tasks/CleanupGeneratedPdfBuildTask.php 1 patch
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -7,24 +7,24 @@
 block discarded – undo
7 7
 
8 8
 class CleanupGeneratedPdfBuildTask extends BuildTask
9 9
 {
10
-    protected $title = 'Cleanup generated PDFs';
10
+	protected $title = 'Cleanup generated PDFs';
11 11
 
12
-    protected $description = 'Removes generated PDFs on the site, forcing a regeneration of all exports to PDF '
13
-        . 'when users go to download them. This is most useful when templates have been changed so users should '
14
-        . 'receive a new copy';
12
+	protected $description = 'Removes generated PDFs on the site, forcing a regeneration of all exports to PDF '
13
+		. 'when users go to download them. This is most useful when templates have been changed so users should '
14
+		. 'receive a new copy';
15 15
 
16
-    public function run($request)
17
-    {
18
-        $path = sprintf('%s/%s', BASE_PATH, BasePage::config()->generated_pdf_path);
19
-        if (!file_exists($path)) {
20
-            return false;
21
-        }
16
+	public function run($request)
17
+	{
18
+		$path = sprintf('%s/%s', BASE_PATH, BasePage::config()->generated_pdf_path);
19
+		if (!file_exists($path)) {
20
+			return false;
21
+		}
22 22
 
23
-        exec(sprintf('if [ "$(ls -A %s 2> /dev/null)" != "" ]; then rm %s/*; fi', $path, $path), $output, $return_val);
23
+		exec(sprintf('if [ "$(ls -A %s 2> /dev/null)" != "" ]; then rm %s/*; fi', $path, $path), $output, $return_val);
24 24
 
25
-        // output any errors
26
-        if ($return_val != 0) {
27
-            user_error(sprintf('%s failed: ', get_class($this)) . implode("\n", $output), E_USER_ERROR);
28
-        }
29
-    }
25
+		// output any errors
26
+		if ($return_val != 0) {
27
+			user_error(sprintf('%s failed: ', get_class($this)) . implode("\n", $output), E_USER_ERROR);
28
+		}
29
+	}
30 30
 }
Please login to merge, or discard this patch.
src/Model/QuickLink.php 1 patch
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -11,120 +11,120 @@
 block discarded – undo
11 11
 
12 12
 class Quicklink extends DataObject
13 13
 {
14
-    private static $db = [
15
-        'Name' => 'Varchar(255)',
16
-        'ExternalLink' => 'Varchar(255)',
17
-        'SortOrder' => 'Int',
18
-    ];
19
-
20
-    private static $has_one = [
21
-        'Parent' => BaseHomePage::class,
22
-        'InternalLink' => SiteTree::class,
23
-    ];
24
-
25
-    private static $summary_fields = [
26
-        'Name' => 'Name',
27
-        'InternalLink.Title' => 'Internal Link',
28
-        'ExternalLink' => 'External Link',
29
-    ];
30
-
31
-    private static $table_name = 'Quicklink';
32
-
33
-    public function fieldLabels($includerelations = true)
34
-    {
35
-        $labels = parent::fieldLabels($includerelations);
36
-        $labels['Name'] = _t('Quicklink.NameLabel', 'Name');
37
-        $labels['ExternalLink'] = _t('Quicklink.ExternalLinkLabel', 'External Link');
38
-        $labels['SortOrder'] = _t('Quicklink.SortOrderLabel', 'Sort Order');
39
-        $labels['ParentID'] = _t('Quicklink.ParentRelationLabel', 'Parent');
40
-        $labels['InternalLinkID'] = _t('Quicklink.InternalLinkLabel', 'Internal Link');
41
-
42
-        return $labels;
43
-    }
44
-
45
-    public function getLink()
46
-    {
47
-        if ($this->ExternalLink) {
48
-            $url = parse_url($this->ExternalLink);
49
-
50
-            // if no scheme set in the link, default to http
51
-            if (!isset($url['scheme'])) {
52
-                return 'http://' . $this->ExternalLink;
53
-            }
54
-
55
-            return $this->ExternalLink;
56
-        } elseif ($this->InternalLinkID) {
57
-            return $this->InternalLink()->Link();
58
-        }
59
-    }
60
-
61
-    public function canCreate($member = null, $context = [])
62
-    {
63
-        return $this->Parent()->canCreate($member, $context);
64
-    }
65
-
66
-    public function canEdit($member = null)
67
-    {
68
-        return $this->Parent()->canEdit($member);
69
-    }
70
-
71
-    public function canDelete($member = null)
72
-    {
73
-        return $this->Parent()->canDelete($member);
74
-    }
75
-
76
-    public function canView($member = null)
77
-    {
78
-        return $this->Parent()->canView($member);
79
-    }
80
-
81
-    public function getCMSFields()
82
-    {
83
-        $fields = parent::getCMSFields();
84
-
85
-        $fields->removeByName('ParentID');
86
-
87
-        $externalLinkField = $fields->fieldByName('Root.Main.ExternalLink');
88
-
89
-        $fields->removeByName('ExternalLink');
90
-        $fields->removeByName('InternalLinkID');
91
-        $fields->removeByName('SortOrder');
92
-        $externalLinkField->addExtraClass('noBorder');
93
-
94
-        $fields->addFieldToTab('Root.Main', CompositeField::create(
95
-            array(
96
-                TreeDropdownField::create(
97
-                    'InternalLinkID',
98
-                    $this->fieldLabel('InternalLinkID'),
99
-                    SiteTree::class
100
-                ),
101
-                $externalLinkField,
102
-                $wrap = CompositeField::create(
103
-                    $extraLabel = LiteralField::create(
104
-                        'NoteOverride',
105
-                        _t(
106
-                            __CLASS__ . '.Note',
107
-                            // @todo remove the HTML from this translation
108
-                            '<div class="message good notice">Note:  If you specify an External Link, '
109
-                            . 'the Internal Link will be ignored.</div>'
110
-                        )
111
-                    )
112
-                )
113
-            )
114
-        ));
115
-        $fields->insertBefore(
116
-            LiteralField::create(
117
-                'Note',
118
-                _t(
119
-                    __CLASS__ . '.Note2',
120
-                    // @todo remove the HTML from this translation
121
-                    '<p>Use this to specify a link to a page either on this site '
122
-                    . '(Internal Link) or another site (External Link).</p>'
123
-                )
124
-            ),
125
-            'Name'
126
-        );
127
-
128
-        return $fields;
129
-    }
14
+	private static $db = [
15
+		'Name' => 'Varchar(255)',
16
+		'ExternalLink' => 'Varchar(255)',
17
+		'SortOrder' => 'Int',
18
+	];
19
+
20
+	private static $has_one = [
21
+		'Parent' => BaseHomePage::class,
22
+		'InternalLink' => SiteTree::class,
23
+	];
24
+
25
+	private static $summary_fields = [
26
+		'Name' => 'Name',
27
+		'InternalLink.Title' => 'Internal Link',
28
+		'ExternalLink' => 'External Link',
29
+	];
30
+
31
+	private static $table_name = 'Quicklink';
32
+
33
+	public function fieldLabels($includerelations = true)
34
+	{
35
+		$labels = parent::fieldLabels($includerelations);
36
+		$labels['Name'] = _t('Quicklink.NameLabel', 'Name');
37
+		$labels['ExternalLink'] = _t('Quicklink.ExternalLinkLabel', 'External Link');
38
+		$labels['SortOrder'] = _t('Quicklink.SortOrderLabel', 'Sort Order');
39
+		$labels['ParentID'] = _t('Quicklink.ParentRelationLabel', 'Parent');
40
+		$labels['InternalLinkID'] = _t('Quicklink.InternalLinkLabel', 'Internal Link');
41
+
42
+		return $labels;
43
+	}
44
+
45
+	public function getLink()
46
+	{
47
+		if ($this->ExternalLink) {
48
+			$url = parse_url($this->ExternalLink);
49
+
50
+			// if no scheme set in the link, default to http
51
+			if (!isset($url['scheme'])) {
52
+				return 'http://' . $this->ExternalLink;
53
+			}
54
+
55
+			return $this->ExternalLink;
56
+		} elseif ($this->InternalLinkID) {
57
+			return $this->InternalLink()->Link();
58
+		}
59
+	}
60
+
61
+	public function canCreate($member = null, $context = [])
62
+	{
63
+		return $this->Parent()->canCreate($member, $context);
64
+	}
65
+
66
+	public function canEdit($member = null)
67
+	{
68
+		return $this->Parent()->canEdit($member);
69
+	}
70
+
71
+	public function canDelete($member = null)
72
+	{
73
+		return $this->Parent()->canDelete($member);
74
+	}
75
+
76
+	public function canView($member = null)
77
+	{
78
+		return $this->Parent()->canView($member);
79
+	}
80
+
81
+	public function getCMSFields()
82
+	{
83
+		$fields = parent::getCMSFields();
84
+
85
+		$fields->removeByName('ParentID');
86
+
87
+		$externalLinkField = $fields->fieldByName('Root.Main.ExternalLink');
88
+
89
+		$fields->removeByName('ExternalLink');
90
+		$fields->removeByName('InternalLinkID');
91
+		$fields->removeByName('SortOrder');
92
+		$externalLinkField->addExtraClass('noBorder');
93
+
94
+		$fields->addFieldToTab('Root.Main', CompositeField::create(
95
+			array(
96
+				TreeDropdownField::create(
97
+					'InternalLinkID',
98
+					$this->fieldLabel('InternalLinkID'),
99
+					SiteTree::class
100
+				),
101
+				$externalLinkField,
102
+				$wrap = CompositeField::create(
103
+					$extraLabel = LiteralField::create(
104
+						'NoteOverride',
105
+						_t(
106
+							__CLASS__ . '.Note',
107
+							// @todo remove the HTML from this translation
108
+							'<div class="message good notice">Note:  If you specify an External Link, '
109
+							. 'the Internal Link will be ignored.</div>'
110
+						)
111
+					)
112
+				)
113
+			)
114
+		));
115
+		$fields->insertBefore(
116
+			LiteralField::create(
117
+				'Note',
118
+				_t(
119
+					__CLASS__ . '.Note2',
120
+					// @todo remove the HTML from this translation
121
+					'<p>Use this to specify a link to a page either on this site '
122
+					. '(Internal Link) or another site (External Link).</p>'
123
+				)
124
+			),
125
+			'Name'
126
+		);
127
+
128
+		return $fields;
129
+	}
130 130
 }
Please login to merge, or discard this patch.
src/Search/CwpSearchPageController.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -11,25 +11,25 @@
 block discarded – undo
11 11
  */
12 12
 class CwpSearchPageController extends PageController
13 13
 {
14
-    /**
15
-     * Create the dummy search record for this page
16
-     *
17
-     * @return CwpSearchPage
18
-     */
19
-    protected function generateSearchRecord()
20
-    {
21
-        $searchPage = CwpSearchPage::create();
22
-        $searchPage->URLSegment = 'search';
23
-        $searchPage->Title = _t('SearchForm.SearchResults', 'Search Results');
24
-        $searchPage->ID = -1;
25
-        return $searchPage;
26
-    }
14
+	/**
15
+	 * Create the dummy search record for this page
16
+	 *
17
+	 * @return CwpSearchPage
18
+	 */
19
+	protected function generateSearchRecord()
20
+	{
21
+		$searchPage = CwpSearchPage::create();
22
+		$searchPage->URLSegment = 'search';
23
+		$searchPage->Title = _t('SearchForm.SearchResults', 'Search Results');
24
+		$searchPage->ID = -1;
25
+		return $searchPage;
26
+	}
27 27
 
28
-    public function __construct($dataRecord = null)
29
-    {
30
-        if (!$dataRecord) {
31
-            $dataRecord = $this->generateSearchRecord();
32
-        }
33
-        parent::__construct($dataRecord);
34
-    }
28
+	public function __construct($dataRecord = null)
29
+	{
30
+		if (!$dataRecord) {
31
+			$dataRecord = $this->generateSearchRecord();
32
+		}
33
+		parent::__construct($dataRecord);
34
+	}
35 35
 }
Please login to merge, or discard this patch.
src/Search/CwpSearchEngine.php 1 patch
Indentation   +134 added lines, -134 removed lines patch added patch discarded remove patch
@@ -16,138 +16,138 @@
 block discarded – undo
16 16
  */
17 17
 class CwpSearchEngine
18 18
 {
19
-    use Configurable;
20
-    use Extensible;
21
-    use Injectable;
22
-
23
-    /**
24
-     * Default search options
25
-     *
26
-     * @var array
27
-     * @config
28
-     */
29
-    private static $search_options = [
30
-        'hl' => 'true',
31
-    ];
32
-
33
-    /**
34
-     * Additional search options to send to search when spellcheck
35
-     * is included
36
-     *
37
-     * @var array
38
-     * @config
39
-     */
40
-    private static $spellcheck_options = [
41
-        'spellcheck' => 'true',
42
-        'spellcheck.collate' => 'true',
43
-        // spellcheck.dictionary can also be configured to use '_spellcheck'
44
-        // dictionary when indexing fields under the _spellcheckText column
45
-        'spellcheck.dictionary' => 'default',
46
-    ];
47
-
48
-    /**
49
-     * Build a SearchQuery for a new search
50
-     *
51
-     * @param string $keywords
52
-     * @param array $classes
53
-     * @return SearchQuery
54
-     */
55
-    protected function getSearchQuery($keywords, $classes)
56
-    {
57
-        $query = new SearchQuery();
58
-        $query->classes = $classes;
59
-        $query->search($keywords);
60
-        $query->exclude('SiteTree_ShowInSearch', 0);
61
-        $query->exclude('File_ShowInSearch', 0);
62
-
63
-        // Artificially lower the amount of results to prevent too high resource usage.
64
-        // on subsequent canView check loop.
65
-        $query->limit(100);
66
-        return $query;
67
-    }
68
-
69
-    /**
70
-     * Get solr search options for this query
71
-     *
72
-     * @param bool $spellcheck True if we should include spellcheck support
73
-     * @return array
74
-     */
75
-    protected function getSearchOptions($spellcheck)
76
-    {
77
-        $options = $this->config()->search_options;
78
-        if ($spellcheck) {
79
-            $options = array_merge($options, $this->config()->spellcheck_options);
80
-        }
81
-        return $options;
82
-    }
83
-
84
-    /**
85
-     * Get results for a search term
86
-     *
87
-     * @param string $keywords
88
-     * @param array $classes
89
-     * @param SolrIndex $searchIndex
90
-     * @param int $limit Max number of results for this page
91
-     * @param int $start Skip this number of records
92
-     * @param bool $spellcheck True to enable spellcheck
93
-     * @return CwpSearchResult
94
-     */
95
-    protected function getResult($keywords, $classes, $searchIndex, $limit = -1, $start = 0, $spellcheck = false)
96
-    {
97
-        // Prepare options
98
-        $query = $this->getSearchQuery($keywords, $classes);
99
-        $options = $this->getSearchOptions($spellcheck);
100
-
101
-        // Get results
102
-        $solrResult = $searchIndex->search(
103
-            $query,
104
-            $start,
105
-            $limit,
106
-            $options
107
-        );
108
-
109
-        return CwpSearchResult::create($keywords, $solrResult);
110
-    }
111
-
112
-    /**
113
-     * Get a CwpSearchResult for a given criterea
114
-     *
115
-     * @param string $keywords
116
-     * @param array $classes
117
-     * @param SolrIndex $searchIndex
118
-     * @param int $limit Max number of results for this page
119
-     * @param int $start Skip this number of records
120
-     * @param bool $followSuggestions True to enable suggested searches to be returned immediately
121
-     * @return CwpSearchResult|null
122
-     */
123
-    public function search($keywords, $classes, $searchIndex, $limit = -1, $start = 0, $followSuggestions = false)
124
-    {
125
-        if (empty($keywords)) {
126
-            return null;
127
-        }
128
-
129
-        try {
130
-            // Begin search
131
-            $result = $this->getResult($keywords, $classes, $searchIndex, $limit, $start, true);
132
-
133
-            // Return results if we don't need to refine this any further
134
-            if (!$followSuggestions || $result->hasResults() || !$result->getSuggestion()) {
135
-                return $result;
136
-            }
137
-
138
-            // Perform new search with the suggested terms
139
-            $suggested = $result->getSuggestion();
140
-            $newResult = $this->getResult($suggested, $classes, $searchIndex, $limit, $start, false);
141
-            $newResult->setOriginal($keywords);
142
-
143
-            // Compare new results to the original query
144
-            if ($newResult->hasResults()) {
145
-                return $newResult;
146
-            } else {
147
-                return $result;
148
-            }
149
-        } catch (Exception $e) {
150
-            Injector::inst()->get(LoggerInterface::class)->warning($e);
151
-        }
152
-    }
19
+	use Configurable;
20
+	use Extensible;
21
+	use Injectable;
22
+
23
+	/**
24
+	 * Default search options
25
+	 *
26
+	 * @var array
27
+	 * @config
28
+	 */
29
+	private static $search_options = [
30
+		'hl' => 'true',
31
+	];
32
+
33
+	/**
34
+	 * Additional search options to send to search when spellcheck
35
+	 * is included
36
+	 *
37
+	 * @var array
38
+	 * @config
39
+	 */
40
+	private static $spellcheck_options = [
41
+		'spellcheck' => 'true',
42
+		'spellcheck.collate' => 'true',
43
+		// spellcheck.dictionary can also be configured to use '_spellcheck'
44
+		// dictionary when indexing fields under the _spellcheckText column
45
+		'spellcheck.dictionary' => 'default',
46
+	];
47
+
48
+	/**
49
+	 * Build a SearchQuery for a new search
50
+	 *
51
+	 * @param string $keywords
52
+	 * @param array $classes
53
+	 * @return SearchQuery
54
+	 */
55
+	protected function getSearchQuery($keywords, $classes)
56
+	{
57
+		$query = new SearchQuery();
58
+		$query->classes = $classes;
59
+		$query->search($keywords);
60
+		$query->exclude('SiteTree_ShowInSearch', 0);
61
+		$query->exclude('File_ShowInSearch', 0);
62
+
63
+		// Artificially lower the amount of results to prevent too high resource usage.
64
+		// on subsequent canView check loop.
65
+		$query->limit(100);
66
+		return $query;
67
+	}
68
+
69
+	/**
70
+	 * Get solr search options for this query
71
+	 *
72
+	 * @param bool $spellcheck True if we should include spellcheck support
73
+	 * @return array
74
+	 */
75
+	protected function getSearchOptions($spellcheck)
76
+	{
77
+		$options = $this->config()->search_options;
78
+		if ($spellcheck) {
79
+			$options = array_merge($options, $this->config()->spellcheck_options);
80
+		}
81
+		return $options;
82
+	}
83
+
84
+	/**
85
+	 * Get results for a search term
86
+	 *
87
+	 * @param string $keywords
88
+	 * @param array $classes
89
+	 * @param SolrIndex $searchIndex
90
+	 * @param int $limit Max number of results for this page
91
+	 * @param int $start Skip this number of records
92
+	 * @param bool $spellcheck True to enable spellcheck
93
+	 * @return CwpSearchResult
94
+	 */
95
+	protected function getResult($keywords, $classes, $searchIndex, $limit = -1, $start = 0, $spellcheck = false)
96
+	{
97
+		// Prepare options
98
+		$query = $this->getSearchQuery($keywords, $classes);
99
+		$options = $this->getSearchOptions($spellcheck);
100
+
101
+		// Get results
102
+		$solrResult = $searchIndex->search(
103
+			$query,
104
+			$start,
105
+			$limit,
106
+			$options
107
+		);
108
+
109
+		return CwpSearchResult::create($keywords, $solrResult);
110
+	}
111
+
112
+	/**
113
+	 * Get a CwpSearchResult for a given criterea
114
+	 *
115
+	 * @param string $keywords
116
+	 * @param array $classes
117
+	 * @param SolrIndex $searchIndex
118
+	 * @param int $limit Max number of results for this page
119
+	 * @param int $start Skip this number of records
120
+	 * @param bool $followSuggestions True to enable suggested searches to be returned immediately
121
+	 * @return CwpSearchResult|null
122
+	 */
123
+	public function search($keywords, $classes, $searchIndex, $limit = -1, $start = 0, $followSuggestions = false)
124
+	{
125
+		if (empty($keywords)) {
126
+			return null;
127
+		}
128
+
129
+		try {
130
+			// Begin search
131
+			$result = $this->getResult($keywords, $classes, $searchIndex, $limit, $start, true);
132
+
133
+			// Return results if we don't need to refine this any further
134
+			if (!$followSuggestions || $result->hasResults() || !$result->getSuggestion()) {
135
+				return $result;
136
+			}
137
+
138
+			// Perform new search with the suggested terms
139
+			$suggested = $result->getSuggestion();
140
+			$newResult = $this->getResult($suggested, $classes, $searchIndex, $limit, $start, false);
141
+			$newResult->setOriginal($keywords);
142
+
143
+			// Compare new results to the original query
144
+			if ($newResult->hasResults()) {
145
+				return $newResult;
146
+			} else {
147
+				return $result;
148
+			}
149
+		} catch (Exception $e) {
150
+			Injector::inst()->get(LoggerInterface::class)->warning($e);
151
+		}
152
+	}
153 153
 }
Please login to merge, or discard this patch.