Passed
Pull Request — master (#223)
by Nic
02:21
created
src/bulkloader/LocationCsvBulkLoader.php 2 patches
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -13,89 +13,89 @@
 block discarded – undo
13 13
 class LocationCsvBulkLoader extends CsvBulkLoader
14 14
 {
15 15
 
16
-    /**
17
-     * @var array
18
-     */
19
-    public $columnMap = array(
20
-        'Name' => 'Title',
21
-        'EmailAddress' => 'Email',
22
-        'Categories' => '->getCategoryByName',
23
-        'Import_ID' => 'Import_ID',
24
-        'Country' => '->getCountryByName',
25
-    );
16
+	/**
17
+	 * @var array
18
+	 */
19
+	public $columnMap = array(
20
+		'Name' => 'Title',
21
+		'EmailAddress' => 'Email',
22
+		'Categories' => '->getCategoryByName',
23
+		'Import_ID' => 'Import_ID',
24
+		'Country' => '->getCountryByName',
25
+	);
26 26
 
27
-    /**
28
-     * @var array
29
-     */
30
-    public $duplicateChecks = array(
31
-        'Import_ID' => 'Import_ID'
32
-    );
27
+	/**
28
+	 * @var array
29
+	 */
30
+	public $duplicateChecks = array(
31
+		'Import_ID' => 'Import_ID'
32
+	);
33 33
 
34
-    /**
35
-     * @param $val
36
-     * @return string|string[]|null
37
-     */
38
-    public function getEscape($val)
39
-    {
40
-        return preg_replace("/\r|\n/", "", $val);
41
-    }
34
+	/**
35
+	 * @param $val
36
+	 * @return string|string[]|null
37
+	 */
38
+	public function getEscape($val)
39
+	{
40
+		return preg_replace("/\r|\n/", "", $val);
41
+	}
42 42
 
43
-    /**
44
-     * @param $obj
45
-     * @param $val
46
-     * @param $record
47
-     * @throws \SilverStripe\ORM\ValidationException
48
-     */
49
-    public static function getCategoryByName(&$obj, $val, $record)
50
-    {
51
-        $val = Convert::raw2sql($val);
52
-        $parts = explode(', ', $val);
43
+	/**
44
+	 * @param $obj
45
+	 * @param $val
46
+	 * @param $record
47
+	 * @throws \SilverStripe\ORM\ValidationException
48
+	 */
49
+	public static function getCategoryByName(&$obj, $val, $record)
50
+	{
51
+		$val = Convert::raw2sql($val);
52
+		$parts = explode(', ', $val);
53 53
 
54
-        foreach ($parts as $part) {
55
-            $category = LocationCategory::get()->filter(array('Name' => $part))->first();
56
-            if (!$category) {
57
-                $category = LocationCategory::create();
58
-                $category->Name = $part;
59
-                $category->write();
60
-            }
61
-            $obj->Categories()->add($category);
62
-        }
63
-    }
54
+		foreach ($parts as $part) {
55
+			$category = LocationCategory::get()->filter(array('Name' => $part))->first();
56
+			if (!$category) {
57
+				$category = LocationCategory::create();
58
+				$category->Name = $part;
59
+				$category->write();
60
+			}
61
+			$obj->Categories()->add($category);
62
+		}
63
+	}
64 64
 
65
-    /**
66
-     * @param $obj
67
-     * @param $val
68
-     * @param $record
69
-     */
70
-    public function getCountryByName(&$obj, $val, $record)
71
-    {
72
-        $val = $this->getEscape($val);
73
-        $countries = IntlLocales::singleton()->getCountries();
65
+	/**
66
+	 * @param $obj
67
+	 * @param $val
68
+	 * @param $record
69
+	 */
70
+	public function getCountryByName(&$obj, $val, $record)
71
+	{
72
+		$val = $this->getEscape($val);
73
+		$countries = IntlLocales::singleton()->getCountries();
74 74
 
75
-        if (strlen((string)$val) == 2) {
76
-            $val = strtolower($val);
77
-            if (array_key_exists($val, $countries)) {
78
-                $obj->Country = $val;
79
-            }
80
-        }
75
+		if (strlen((string)$val) == 2) {
76
+			$val = strtolower($val);
77
+			if (array_key_exists($val, $countries)) {
78
+				$obj->Country = $val;
79
+			}
80
+		}
81 81
 
82
-        if (in_array($val, $countries)) {
83
-            $obj->Country = array_search($val, $countries);
84
-        }
85
-    }
82
+		if (in_array($val, $countries)) {
83
+			$obj->Country = array_search($val, $countries);
84
+		}
85
+	}
86 86
 
87
-    /**
88
-     * @param array $record
89
-     * @param array $columnMap
90
-     * @param \SilverStripe\Dev\BulkLoader_Result $results
91
-     * @param bool $preview
92
-     * @return int|void
93
-     */
94
-    protected function processRecord($record, $columnMap, &$results, $preview = false)
95
-    {
96
-        $objID = parent::processRecord($record, $columnMap, $results, $preview = false);
87
+	/**
88
+	 * @param array $record
89
+	 * @param array $columnMap
90
+	 * @param \SilverStripe\Dev\BulkLoader_Result $results
91
+	 * @param bool $preview
92
+	 * @return int|void
93
+	 */
94
+	protected function processRecord($record, $columnMap, &$results, $preview = false)
95
+	{
96
+		$objID = parent::processRecord($record, $columnMap, $results, $preview = false);
97 97
 
98
-        $location = Location::get()->byID($objID);
99
-        $location->publishSingle();
100
-    }
98
+		$location = Location::get()->byID($objID);
99
+		$location->publishSingle();
100
+	}
101 101
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -72,7 +72,7 @@
 block discarded – undo
72 72
         $val = $this->getEscape($val);
73 73
         $countries = IntlLocales::singleton()->getCountries();
74 74
 
75
-        if (strlen((string)$val) == 2) {
75
+        if (strlen((string) $val) == 2) {
76 76
             $val = strtolower($val);
77 77
             if (array_key_exists($val, $countries)) {
78 78
                 $obj->Country = $val;
Please login to merge, or discard this patch.
src/Page/Locator.php 2 patches
Indentation   +242 added lines, -242 removed lines patch added patch discarded remove patch
@@ -27,246 +27,246 @@
 block discarded – undo
27 27
  */
28 28
 class Locator extends \Page
29 29
 {
30
-    /**
31
-     * @var string
32
-     */
33
-    private static $singular_name = 'Locator';
34
-
35
-    /**
36
-     * @var string
37
-     */
38
-    private static $plural_name = 'Locators';
39
-
40
-    /**
41
-     * @var string
42
-     */
43
-    private static $description = 'Display locations on a map';
44
-
45
-    /**
46
-     * @var array
47
-     */
48
-    private static $db = array(
49
-        'Unit' => 'Enum("m,km","m")',
50
-    );
51
-
52
-    /**
53
-     * @var array
54
-     */
55
-    private static $many_many = array(
56
-        'Categories' => LocationCategory::class,
57
-    );
58
-
59
-    /**
60
-     * @var string
61
-     */
62
-    private static $table_name = 'Locator';
63
-
64
-    /**
65
-     * @var string
66
-     */
67
-    private static $location_class = LocationPage::class;
68
-
69
-    /**
70
-     * @return FieldList
71
-     */
72
-    public function getCMSFields()
73
-    {
74
-        $this->beforeUpdateCMSFields(function ($fields) {
75
-            // Settings
76
-            $fields->addFieldsToTab('Root.Settings', array(
77
-                HeaderField::create('DisplayOptions', 'Display Options', 3),
78
-                OptionsetField::create('Unit', 'Unit of measure', array('m' => 'Miles', 'km' => 'Kilometers')),
79
-            ));
80
-
81
-            // Filter categories
82
-            $config = GridFieldConfig_RelationEditor::create();
83
-            $config->removeComponentsByType(GridFieldAddExistingAutocompleter::class);
84
-            $config->addComponent(new GridFieldAddExistingSearchButton());
85
-            $categories = $this->Categories();
86
-            $categoriesField = GridField::create('Categories', 'Categories', $categories, $config)
87
-                ->setDescription('only show locations from the selected category');
88
-
89
-            // Filter
90
-            $fields->addFieldsToTab('Root.Filter', array(
91
-                HeaderField::create('CategoryOptionsHeader', 'Location Filtering', 3),
92
-                $categoriesField,
93
-            ));
94
-        });
95
-
96
-        return parent::getCMSFields();
97
-    }
98
-
99
-    /**
100
-     * @param array $filter
101
-     * @param array $filterAny
102
-     * @param array $exclude
103
-     * @param null|callable $callback
104
-     *
105
-     * @return DataList|ArrayList
106
-     */
107
-    public static function get_locations(
108
-        $filter = [],
109
-        $filterAny = [],
110
-        $exclude = [],
111
-        $callback = null
112
-    ) {
113
-        $locationClass = Config::inst()->get(static::class, 'location_class');
114
-        $locations = $locationClass::get()->filter($filter)->exclude($exclude);
115
-
116
-        if (!empty($filterAny)) {
117
-            $locations = $locations->filterAny($filterAny);
118
-        }
119
-        if (!empty($exclude)) {
120
-            $locations = $locations->exclude($exclude);
121
-        }
122
-
123
-        if ($callback !== null && is_callable($callback)) {
124
-            $locations->filterByCallback($callback);
125
-        }
126
-
127
-        return $locations;
128
-    }
129
-
130
-    /**
131
-     * @return DataList
132
-     */
133
-    public static function get_all_categories()
134
-    {
135
-        return LocationCategory::get();
136
-    }
137
-
138
-    /**
139
-     * @return bool
140
-     */
141
-    public function getPageCategories()
142
-    {
143
-        return self::locator_categories_by_locator($this->ID);
144
-    }
145
-
146
-    /**
147
-     * @param int $id
148
-     *
149
-     * @return bool|
150
-     */
151
-    public static function locator_categories_by_locator($id = 0)
152
-    {
153
-        if ($id == 0) {
154
-            return false;
155
-        }
156
-
157
-        return static::get()->byID($id)->getUsedCategories();
158
-    }
159
-
160
-    /**
161
-     * Gets the list of radii
162
-     *
163
-     * @return ArrayList
164
-     */
165
-    public function getRadii()
166
-    {
167
-        $radii = [
168
-            '0' => '25',
169
-            '1' => '50',
170
-            '2' => '75',
171
-            '3' => '100',
172
-        ];
173
-        $config_radii = $this->config()->get('radii');
174
-        if ($config_radii) {
175
-            $radii = $config_radii;
176
-        }
177
-
178
-        return $radii;
179
-    }
180
-
181
-    public function getRadiiArrayList()
182
-    {
183
-        $list = [];
184
-
185
-        foreach ($this->getRadii() as $radius) {
186
-            $list[] = new ArrayData(array(
187
-                'Radius' => $radius,
188
-            ));
189
-        }
190
-
191
-        return new ArrayList($list);
192
-    }
193
-
194
-    /**
195
-     * Gets the limit of locations
196
-     * @return mixed
197
-     */
198
-    public function getLimit()
199
-    {
200
-        return $this->config()->get('limit');
201
-    }
202
-
203
-    /**
204
-     * Gets if the radius drop down should be shown
205
-     * @return mixed
206
-     */
207
-    public function getShowRadius()
208
-    {
209
-        return $this->config()->get('show_radius');
210
-    }
211
-
212
-    /**
213
-     * @return mixed
214
-     */
215
-    public function getUsedCategories()
216
-    {
217
-        return $this->Categories()->filter([
218
-            'LocationSet.ID:GreaterThan' => 0,
219
-        ]);
220
-    }
221
-
222
-    /**
223
-     * Gets the path of the info window template
224
-     *
225
-     * @return string
226
-     */
227
-    public function getInfoWindowTemplate()
228
-    {
229
-        return ModuleResourceLoader::singleton()->resolveURL(
230
-            Config::inst()->get(
231
-                static::class,
232
-                'infoWindowTemplate'
233
-            )
234
-        );
235
-    }
236
-
237
-    /**
238
-     * Gets the path of the list template
239
-     *
240
-     * @return string
241
-     */
242
-    public function getListTemplate()
243
-    {
244
-        return ModuleResourceLoader::singleton()->resolveURL(
245
-            Config::inst()->get(
246
-                static::class,
247
-                'listTemplate'
248
-            )
249
-        );
250
-    }
251
-
252
-    /**
253
-     * @return null|string
254
-     */
255
-    public function getMapStyle()
256
-    {
257
-        return AddressDataExtension::getMapStyleJSON();
258
-    }
259
-
260
-    public function getMapStyleJSONPath()
261
-    {
262
-        return AddressDataExtension::getMapStyleJSONPath();
263
-    }
264
-
265
-    /**
266
-     * @return null|string
267
-     */
268
-    public function getMarkerIcon()
269
-    {
270
-        return AddressDataExtension::getIconImage();
271
-    }
30
+	/**
31
+	 * @var string
32
+	 */
33
+	private static $singular_name = 'Locator';
34
+
35
+	/**
36
+	 * @var string
37
+	 */
38
+	private static $plural_name = 'Locators';
39
+
40
+	/**
41
+	 * @var string
42
+	 */
43
+	private static $description = 'Display locations on a map';
44
+
45
+	/**
46
+	 * @var array
47
+	 */
48
+	private static $db = array(
49
+		'Unit' => 'Enum("m,km","m")',
50
+	);
51
+
52
+	/**
53
+	 * @var array
54
+	 */
55
+	private static $many_many = array(
56
+		'Categories' => LocationCategory::class,
57
+	);
58
+
59
+	/**
60
+	 * @var string
61
+	 */
62
+	private static $table_name = 'Locator';
63
+
64
+	/**
65
+	 * @var string
66
+	 */
67
+	private static $location_class = LocationPage::class;
68
+
69
+	/**
70
+	 * @return FieldList
71
+	 */
72
+	public function getCMSFields()
73
+	{
74
+		$this->beforeUpdateCMSFields(function ($fields) {
75
+			// Settings
76
+			$fields->addFieldsToTab('Root.Settings', array(
77
+				HeaderField::create('DisplayOptions', 'Display Options', 3),
78
+				OptionsetField::create('Unit', 'Unit of measure', array('m' => 'Miles', 'km' => 'Kilometers')),
79
+			));
80
+
81
+			// Filter categories
82
+			$config = GridFieldConfig_RelationEditor::create();
83
+			$config->removeComponentsByType(GridFieldAddExistingAutocompleter::class);
84
+			$config->addComponent(new GridFieldAddExistingSearchButton());
85
+			$categories = $this->Categories();
86
+			$categoriesField = GridField::create('Categories', 'Categories', $categories, $config)
87
+				->setDescription('only show locations from the selected category');
88
+
89
+			// Filter
90
+			$fields->addFieldsToTab('Root.Filter', array(
91
+				HeaderField::create('CategoryOptionsHeader', 'Location Filtering', 3),
92
+				$categoriesField,
93
+			));
94
+		});
95
+
96
+		return parent::getCMSFields();
97
+	}
98
+
99
+	/**
100
+	 * @param array $filter
101
+	 * @param array $filterAny
102
+	 * @param array $exclude
103
+	 * @param null|callable $callback
104
+	 *
105
+	 * @return DataList|ArrayList
106
+	 */
107
+	public static function get_locations(
108
+		$filter = [],
109
+		$filterAny = [],
110
+		$exclude = [],
111
+		$callback = null
112
+	) {
113
+		$locationClass = Config::inst()->get(static::class, 'location_class');
114
+		$locations = $locationClass::get()->filter($filter)->exclude($exclude);
115
+
116
+		if (!empty($filterAny)) {
117
+			$locations = $locations->filterAny($filterAny);
118
+		}
119
+		if (!empty($exclude)) {
120
+			$locations = $locations->exclude($exclude);
121
+		}
122
+
123
+		if ($callback !== null && is_callable($callback)) {
124
+			$locations->filterByCallback($callback);
125
+		}
126
+
127
+		return $locations;
128
+	}
129
+
130
+	/**
131
+	 * @return DataList
132
+	 */
133
+	public static function get_all_categories()
134
+	{
135
+		return LocationCategory::get();
136
+	}
137
+
138
+	/**
139
+	 * @return bool
140
+	 */
141
+	public function getPageCategories()
142
+	{
143
+		return self::locator_categories_by_locator($this->ID);
144
+	}
145
+
146
+	/**
147
+	 * @param int $id
148
+	 *
149
+	 * @return bool|
150
+	 */
151
+	public static function locator_categories_by_locator($id = 0)
152
+	{
153
+		if ($id == 0) {
154
+			return false;
155
+		}
156
+
157
+		return static::get()->byID($id)->getUsedCategories();
158
+	}
159
+
160
+	/**
161
+	 * Gets the list of radii
162
+	 *
163
+	 * @return ArrayList
164
+	 */
165
+	public function getRadii()
166
+	{
167
+		$radii = [
168
+			'0' => '25',
169
+			'1' => '50',
170
+			'2' => '75',
171
+			'3' => '100',
172
+		];
173
+		$config_radii = $this->config()->get('radii');
174
+		if ($config_radii) {
175
+			$radii = $config_radii;
176
+		}
177
+
178
+		return $radii;
179
+	}
180
+
181
+	public function getRadiiArrayList()
182
+	{
183
+		$list = [];
184
+
185
+		foreach ($this->getRadii() as $radius) {
186
+			$list[] = new ArrayData(array(
187
+				'Radius' => $radius,
188
+			));
189
+		}
190
+
191
+		return new ArrayList($list);
192
+	}
193
+
194
+	/**
195
+	 * Gets the limit of locations
196
+	 * @return mixed
197
+	 */
198
+	public function getLimit()
199
+	{
200
+		return $this->config()->get('limit');
201
+	}
202
+
203
+	/**
204
+	 * Gets if the radius drop down should be shown
205
+	 * @return mixed
206
+	 */
207
+	public function getShowRadius()
208
+	{
209
+		return $this->config()->get('show_radius');
210
+	}
211
+
212
+	/**
213
+	 * @return mixed
214
+	 */
215
+	public function getUsedCategories()
216
+	{
217
+		return $this->Categories()->filter([
218
+			'LocationSet.ID:GreaterThan' => 0,
219
+		]);
220
+	}
221
+
222
+	/**
223
+	 * Gets the path of the info window template
224
+	 *
225
+	 * @return string
226
+	 */
227
+	public function getInfoWindowTemplate()
228
+	{
229
+		return ModuleResourceLoader::singleton()->resolveURL(
230
+			Config::inst()->get(
231
+				static::class,
232
+				'infoWindowTemplate'
233
+			)
234
+		);
235
+	}
236
+
237
+	/**
238
+	 * Gets the path of the list template
239
+	 *
240
+	 * @return string
241
+	 */
242
+	public function getListTemplate()
243
+	{
244
+		return ModuleResourceLoader::singleton()->resolveURL(
245
+			Config::inst()->get(
246
+				static::class,
247
+				'listTemplate'
248
+			)
249
+		);
250
+	}
251
+
252
+	/**
253
+	 * @return null|string
254
+	 */
255
+	public function getMapStyle()
256
+	{
257
+		return AddressDataExtension::getMapStyleJSON();
258
+	}
259
+
260
+	public function getMapStyleJSONPath()
261
+	{
262
+		return AddressDataExtension::getMapStyleJSONPath();
263
+	}
264
+
265
+	/**
266
+	 * @return null|string
267
+	 */
268
+	public function getMarkerIcon()
269
+	{
270
+		return AddressDataExtension::getIconImage();
271
+	}
272 272
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@
 block discarded – undo
70 70
      */
71 71
     public function getCMSFields()
72 72
     {
73
-        $this->beforeUpdateCMSFields(function ($fields) {
73
+        $this->beforeUpdateCMSFields(function($fields) {
74 74
             // Settings
75 75
             $fields->addFieldsToTab('Root.Settings', array(
76 76
                 HeaderField::create('DisplayOptions', 'Display Options', 3),
Please login to merge, or discard this patch.
src/Page/LocatorController.php 2 patches
Indentation   +337 added lines, -337 removed lines patch added patch discarded remove patch
@@ -21,345 +21,345 @@
 block discarded – undo
21 21
  */
22 22
 class LocatorController extends \PageController
23 23
 {
24
-    /**
25
-     * @var array
26
-     */
27
-    private static $allowed_actions = [
28
-        'xml',
29
-        'json',
30
-    ];
31
-
32
-    /**
33
-     * @var array
34
-     */
35
-    private static $base_filter = [];
36
-
37
-    /**
38
-     * @var array
39
-     */
40
-    private static $base_exclude = [
41
-        'Lat' => 0,
42
-        'Lng' => 0,
43
-    ];
44
-
45
-    /**
46
-     * @var array
47
-     */
48
-    private static $base_filter_any = [];
49
-
50
-    /**
51
-     * @var bool
52
-     */
53
-    private static $bootstrapify = true;
54
-
55
-    /**
56
-     * ID of map container
57
-     *
58
-     * @var string
59
-     */
60
-    private static $map_container = 'map';
61
-
62
-    /**
63
-     * class of location list container
64
-     *
65
-     * @var string
66
-     */
67
-    private static $list_container = 'loc-list';
68
-
69
-    /**
70
-     * GET variable which, if isset, will trigger storeLocator init and return XML
71
-     *
72
-     * @var string
73
-     */
74
-    private static $query_trigger = 'action_doFilterLocations';
75
-
76
-    /**
77
-     * @var DataList|ArrayList
78
-     */
79
-    protected $locations;
80
-
81
-    /**
82
-     * Set Requirements based on input from CMS
83
-     */
84
-    public function init()
85
-    {
86
-        parent::init();
87
-
88
-        // prevent init of map if no query
89
-        $request = Controller::curr()->getRequest();
90
-        if (!$this->getTrigger($request)) {
91
-            return;
92
-        }
93
-
94
-        $locations = $this->getLocations();
95
-
96
-        // prevent init of map if there are no locations
97
-        if (!$locations) {
98
-            return;
99
-        }
100
-
101
-        // google maps api key
102
-        $key = Config::inst()->get(GoogleGeocoder::class, 'map_api_key');
103
-        Requirements::javascript('https://maps.google.com/maps/api/js?key=' . $key);
104
-
105
-        $mapSettings = [
106
-            'fullMapStart' => true,
107
-            'maxDistance' => true,
108
-            'storeLimit' => -1,
109
-            'originMarker' => true,
110
-            'slideMap' => false,
111
-            'distanceAlert' => -1,
112
-            'featuredLocations' => false,
113
-            'defaultLat' => 0,
114
-            'defaultLng' => 0,
115
-            'mapSettings' => [
116
-                'zoom' => 12,
117
-                'mapTypeId' => 'google.maps.MapTypeId.ROADMAP',
118
-                'disableDoubleClickZoom' => true,
119
-                'scrollwheel' => false,
120
-                'navigationControl' => false,
121
-                'draggable' => false,
122
-            ],
123
-        ];
124
-
125
-        $mapSettings['listTemplatePath'] = $this->getListTemplate();
126
-        $mapSettings['infowindowTemplatePath'] = $this->getInfoWindowTemplate();
127
-        $mapSettings['lengthUnit'] = $this->data()->Unit == 'km' ? 'km' : 'm';
128
-        $mapSettings['mapID'] = Config::inst()->get(LocatorController::class, 'map_container');
129
-        $mapSettings['locationList'] = Config::inst()->get(LocatorController::class, 'list_container');
130
-
131
-        if ($locations->filter('Featured', true)->count() > 0) {
132
-            $mapSettings['featuredLocations'] = true;
133
-        }
134
-
135
-        // map config based on user input in Settings tab
136
-        $limit = Config::inst()->get(LocatorController::class, 'limit');
137
-        if (0 < $limit) {
138
-            $mapSettings['storeLimit'] = $limit;
139
-        }
140
-
141
-        if ($coords = $this->getAddressSearchCoords()) {
142
-            $mapSettings['defaultLat'] = $coords->getField("Lat");
143
-            $mapSettings['defaultLat'] = $coords->getField("Lng");
144
-        }
145
-
146
-        // pass GET variables to xml action
147
-        $vars = $this->request->getVars();
148
-        unset($vars['url']);
149
-        $url = '';
150
-        if (count($vars)) {
151
-            $url .= '?' . http_build_query($vars);
152
-        }
153
-        $mapSettings['dataLocation'] = Controller::join_links($this->Link(), 'xml.xml', $url);
154
-
155
-        if ($stylePath = $this->getMapStyleJSONPath()) {
156
-            if ($style = file_get_contents($stylePath)) {
157
-                $mapSettings['mapSettings']['styles'] = json_decode($style);
158
-            }
159
-        }
160
-
161
-        if ($imagePath = $this->getMarkerIcon()) {
162
-            $mapSettings['markerImg'] = $imagePath;
163
-        }
164
-
165
-        $this->extend('modifyMapSettings', $mapSettings);
166
-
167
-        $encoded = json_encode($mapSettings, JSON_UNESCAPED_SLASHES);
168
-        // mapTypeId is a javascript object
169
-        $encoded = preg_replace('/("mapTypeId"\s*:\s*)"(.+?)"/i', '$1$2', $encoded);
170
-
171
-        $this->extend('modifyMapSettingsEncoded', $encoded);
172
-        // init map
173
-        Requirements::customScript("
24
+	/**
25
+	 * @var array
26
+	 */
27
+	private static $allowed_actions = [
28
+		'xml',
29
+		'json',
30
+	];
31
+
32
+	/**
33
+	 * @var array
34
+	 */
35
+	private static $base_filter = [];
36
+
37
+	/**
38
+	 * @var array
39
+	 */
40
+	private static $base_exclude = [
41
+		'Lat' => 0,
42
+		'Lng' => 0,
43
+	];
44
+
45
+	/**
46
+	 * @var array
47
+	 */
48
+	private static $base_filter_any = [];
49
+
50
+	/**
51
+	 * @var bool
52
+	 */
53
+	private static $bootstrapify = true;
54
+
55
+	/**
56
+	 * ID of map container
57
+	 *
58
+	 * @var string
59
+	 */
60
+	private static $map_container = 'map';
61
+
62
+	/**
63
+	 * class of location list container
64
+	 *
65
+	 * @var string
66
+	 */
67
+	private static $list_container = 'loc-list';
68
+
69
+	/**
70
+	 * GET variable which, if isset, will trigger storeLocator init and return XML
71
+	 *
72
+	 * @var string
73
+	 */
74
+	private static $query_trigger = 'action_doFilterLocations';
75
+
76
+	/**
77
+	 * @var DataList|ArrayList
78
+	 */
79
+	protected $locations;
80
+
81
+	/**
82
+	 * Set Requirements based on input from CMS
83
+	 */
84
+	public function init()
85
+	{
86
+		parent::init();
87
+
88
+		// prevent init of map if no query
89
+		$request = Controller::curr()->getRequest();
90
+		if (!$this->getTrigger($request)) {
91
+			return;
92
+		}
93
+
94
+		$locations = $this->getLocations();
95
+
96
+		// prevent init of map if there are no locations
97
+		if (!$locations) {
98
+			return;
99
+		}
100
+
101
+		// google maps api key
102
+		$key = Config::inst()->get(GoogleGeocoder::class, 'map_api_key');
103
+		Requirements::javascript('https://maps.google.com/maps/api/js?key=' . $key);
104
+
105
+		$mapSettings = [
106
+			'fullMapStart' => true,
107
+			'maxDistance' => true,
108
+			'storeLimit' => -1,
109
+			'originMarker' => true,
110
+			'slideMap' => false,
111
+			'distanceAlert' => -1,
112
+			'featuredLocations' => false,
113
+			'defaultLat' => 0,
114
+			'defaultLng' => 0,
115
+			'mapSettings' => [
116
+				'zoom' => 12,
117
+				'mapTypeId' => 'google.maps.MapTypeId.ROADMAP',
118
+				'disableDoubleClickZoom' => true,
119
+				'scrollwheel' => false,
120
+				'navigationControl' => false,
121
+				'draggable' => false,
122
+			],
123
+		];
124
+
125
+		$mapSettings['listTemplatePath'] = $this->getListTemplate();
126
+		$mapSettings['infowindowTemplatePath'] = $this->getInfoWindowTemplate();
127
+		$mapSettings['lengthUnit'] = $this->data()->Unit == 'km' ? 'km' : 'm';
128
+		$mapSettings['mapID'] = Config::inst()->get(LocatorController::class, 'map_container');
129
+		$mapSettings['locationList'] = Config::inst()->get(LocatorController::class, 'list_container');
130
+
131
+		if ($locations->filter('Featured', true)->count() > 0) {
132
+			$mapSettings['featuredLocations'] = true;
133
+		}
134
+
135
+		// map config based on user input in Settings tab
136
+		$limit = Config::inst()->get(LocatorController::class, 'limit');
137
+		if (0 < $limit) {
138
+			$mapSettings['storeLimit'] = $limit;
139
+		}
140
+
141
+		if ($coords = $this->getAddressSearchCoords()) {
142
+			$mapSettings['defaultLat'] = $coords->getField("Lat");
143
+			$mapSettings['defaultLat'] = $coords->getField("Lng");
144
+		}
145
+
146
+		// pass GET variables to xml action
147
+		$vars = $this->request->getVars();
148
+		unset($vars['url']);
149
+		$url = '';
150
+		if (count($vars)) {
151
+			$url .= '?' . http_build_query($vars);
152
+		}
153
+		$mapSettings['dataLocation'] = Controller::join_links($this->Link(), 'xml.xml', $url);
154
+
155
+		if ($stylePath = $this->getMapStyleJSONPath()) {
156
+			if ($style = file_get_contents($stylePath)) {
157
+				$mapSettings['mapSettings']['styles'] = json_decode($style);
158
+			}
159
+		}
160
+
161
+		if ($imagePath = $this->getMarkerIcon()) {
162
+			$mapSettings['markerImg'] = $imagePath;
163
+		}
164
+
165
+		$this->extend('modifyMapSettings', $mapSettings);
166
+
167
+		$encoded = json_encode($mapSettings, JSON_UNESCAPED_SLASHES);
168
+		// mapTypeId is a javascript object
169
+		$encoded = preg_replace('/("mapTypeId"\s*:\s*)"(.+?)"/i', '$1$2', $encoded);
170
+
171
+		$this->extend('modifyMapSettingsEncoded', $encoded);
172
+		// init map
173
+		Requirements::customScript("
174 174
                 $(function(){
175 175
                     $('#map-container').storeLocator({$encoded});
176 176
                 });
177 177
             ", 'jquery-locator');
178
-    }
179
-
180
-    /**
181
-     * @param HTTPRequest $request
182
-     *
183
-     * @return bool
184
-     */
185
-    public function getTrigger(HTTPRequest $request = null)
186
-    {
187
-        if ($request === null) {
188
-            $request = $this->getRequest();
189
-        }
190
-        $trigger = $request->getVar(Config::inst()->get(LocatorController::class, 'query_trigger'));
191
-
192
-        return isset($trigger);
193
-    }
194
-
195
-    /**
196
-     * @return ArrayList|DataList
197
-     */
198
-    public function getLocations()
199
-    {
200
-        if (!$this->locations) {
201
-            $this->setLocations($this->request);
202
-        }
203
-
204
-        return $this->locations;
205
-    }
206
-
207
-    /**
208
-     * @param HTTPRequest|null $request
209
-     *
210
-     * @return $this
211
-     */
212
-    public function setLocations(HTTPRequest $request = null)
213
-    {
214
-
215
-        if ($request === null) {
216
-            $request = $this->request;
217
-        }
218
-        $filter = $this->config()->get('base_filter');
219
-
220
-        $categoryVar = $this->data()->config()->get('category_var');
221
-        if ($request->getVar($categoryVar)) {
222
-            $filter['Categories.ID'] = $request->getVar($categoryVar);
223
-        } else {
224
-            if ($this->getPageCategories()->exists()) {
225
-                foreach ($this->getPageCategories() as $category) {
226
-                    $filter['Categories.ID'][] = $category->ID;
227
-                }
228
-            }
229
-        }
230
-
231
-        $this->extend('updateLocatorFilter', $filter, $request);
232
-
233
-        $filterAny = $this->config()->get('base_filter_any');
234
-        $this->extend('updateLocatorFilterAny', $filterAny, $request);
235
-
236
-        $exclude = $this->config()->get('base_exclude');
237
-        $this->extend('updateLocatorExclude', $exclude, $request);
238
-
239
-        $class = $this->data()->ClassName;
240
-        $locations = $class::get_locations($filter, $filterAny, $exclude);
241
-        $locations = DataToArrayListHelper::to_array_list($locations);
242
-
243
-        //allow for adjusting list post possible distance calculation
244
-        $this->extend('updateLocationList', $locations);
245
-
246
-        if ($locations->canSortBy('Distance')) {
247
-            $locations = $locations->sort('Distance');
248
-        }
249
-
250
-        if ($this->getShowRadius()) {
251
-            $radiusVar = $this->data()->config()->get('radius_var');
252
-
253
-            if ($radius = (int)$request->getVar($radiusVar)) {
254
-                $locations = $locations->filterByCallback(function ($location) use (&$radius) {
255
-                    return $location->Distance <= $radius;
256
-                });
257
-            }
258
-        }
259
-
260
-        //allow for returning list to be set as
261
-        $this->extend('updateListType', $locations);
262
-
263
-        $limit = $this->getLimit();
264
-        if ($limit > 0) {
265
-            $locations = $locations->limit($limit);
266
-        }
267
-
268
-        $this->locations = $locations;
269
-
270
-        return $this;
271
-    }
272
-
273
-    /**
274
-     * @return ArrayData|boolean
275
-     */
276
-    public function getAddressSearchCoords()
277
-    {
278
-        $addressVar = Config::inst()->get(DistanceDataExtension::class, 'address_var');
279
-        if (!$this->request->getVar($addressVar)) {
280
-            return false;
281
-        }
282
-        if (class_exists(GoogleGeocoder::class)) {
283
-            $geocoder = new GoogleGeocoder($this->request->getVar($addressVar));
284
-            $response = $geocoder->getResult();
285
-            $lat = $response->getLatitude();
286
-            $lng = $response->getLongitude();
287
-
288
-            return new ArrayData([
289
-                "Lat" => $lat,
290
-                "Lng" => $lng,
291
-            ]);
292
-        }
293
-    }
294
-
295
-    /**
296
-     * @param HTTPRequest $request
297
-     *
298
-     * @return \SilverStripe\View\ViewableData_Customised
299
-     */
300
-    public function index(HTTPRequest $request)
301
-    {
302
-        if ($this->getTrigger($request)) {
303
-            $locations = $this->getLocations();
304
-        } else {
305
-            $locations = ArrayList::create();
306
-        }
307
-
308
-        return $this->customise([
309
-            'Locations' => $locations,
310
-        ]);
311
-    }
312
-
313
-    /**
314
-     * Renders locations in xml format
315
-     *
316
-     * @return \SilverStripe\ORM\FieldType\DBHTMLText
317
-     */
318
-    public function xml()
319
-    {
320
-        $this->getResponse()->addHeader("Content-Type", "application/xml");
321
-        $data = new ArrayData([
322
-            "Locations" => $this->getLocations(),
323
-            "AddressCoords" => $this->getAddressSearchCoords(),
324
-        ]);
325
-
326
-        return $data->renderWith('Dynamic/Locator/Data/XML');
327
-    }
328
-
329
-    /**
330
-     * Renders locations in json format
331
-     *
332
-     * @return \SilverStripe\ORM\FieldType\DBHTMLText
333
-     */
334
-    public function json()
335
-    {
336
-        $this->getResponse()->addHeader("Content-Type", "application/json");
337
-        $data = new ArrayData([
338
-            "Locations" => $this->getLocations(),
339
-            "AddressCoords" => $this->getAddressSearchCoords(),
340
-        ]);
341
-
342
-        return $data->renderWith('Dynamic/Locator/Data/JSON');
343
-    }
344
-
345
-    /**
346
-     * LocationSearch form.
347
-     *
348
-     * Search form for locations, updates map and results list via AJAX
349
-     *
350
-     * @return \SilverStripe\Forms\Form
351
-     */
352
-    public function LocationSearch()
353
-    {
354
-
355
-        $form = LocatorForm::create($this, 'LocationSearch');
356
-
357
-        $this->extend('updateLocationSearch', $form);
358
-
359
-        return $form
360
-            ->setFormMethod('GET')
361
-            ->setFormAction($this->Link())
362
-            ->disableSecurityToken()
363
-            ->loadDataFrom($this->request->getVars());
364
-    }
178
+	}
179
+
180
+	/**
181
+	 * @param HTTPRequest $request
182
+	 *
183
+	 * @return bool
184
+	 */
185
+	public function getTrigger(HTTPRequest $request = null)
186
+	{
187
+		if ($request === null) {
188
+			$request = $this->getRequest();
189
+		}
190
+		$trigger = $request->getVar(Config::inst()->get(LocatorController::class, 'query_trigger'));
191
+
192
+		return isset($trigger);
193
+	}
194
+
195
+	/**
196
+	 * @return ArrayList|DataList
197
+	 */
198
+	public function getLocations()
199
+	{
200
+		if (!$this->locations) {
201
+			$this->setLocations($this->request);
202
+		}
203
+
204
+		return $this->locations;
205
+	}
206
+
207
+	/**
208
+	 * @param HTTPRequest|null $request
209
+	 *
210
+	 * @return $this
211
+	 */
212
+	public function setLocations(HTTPRequest $request = null)
213
+	{
214
+
215
+		if ($request === null) {
216
+			$request = $this->request;
217
+		}
218
+		$filter = $this->config()->get('base_filter');
219
+
220
+		$categoryVar = $this->data()->config()->get('category_var');
221
+		if ($request->getVar($categoryVar)) {
222
+			$filter['Categories.ID'] = $request->getVar($categoryVar);
223
+		} else {
224
+			if ($this->getPageCategories()->exists()) {
225
+				foreach ($this->getPageCategories() as $category) {
226
+					$filter['Categories.ID'][] = $category->ID;
227
+				}
228
+			}
229
+		}
230
+
231
+		$this->extend('updateLocatorFilter', $filter, $request);
232
+
233
+		$filterAny = $this->config()->get('base_filter_any');
234
+		$this->extend('updateLocatorFilterAny', $filterAny, $request);
235
+
236
+		$exclude = $this->config()->get('base_exclude');
237
+		$this->extend('updateLocatorExclude', $exclude, $request);
238
+
239
+		$class = $this->data()->ClassName;
240
+		$locations = $class::get_locations($filter, $filterAny, $exclude);
241
+		$locations = DataToArrayListHelper::to_array_list($locations);
242
+
243
+		//allow for adjusting list post possible distance calculation
244
+		$this->extend('updateLocationList', $locations);
245
+
246
+		if ($locations->canSortBy('Distance')) {
247
+			$locations = $locations->sort('Distance');
248
+		}
249
+
250
+		if ($this->getShowRadius()) {
251
+			$radiusVar = $this->data()->config()->get('radius_var');
252
+
253
+			if ($radius = (int)$request->getVar($radiusVar)) {
254
+				$locations = $locations->filterByCallback(function ($location) use (&$radius) {
255
+					return $location->Distance <= $radius;
256
+				});
257
+			}
258
+		}
259
+
260
+		//allow for returning list to be set as
261
+		$this->extend('updateListType', $locations);
262
+
263
+		$limit = $this->getLimit();
264
+		if ($limit > 0) {
265
+			$locations = $locations->limit($limit);
266
+		}
267
+
268
+		$this->locations = $locations;
269
+
270
+		return $this;
271
+	}
272
+
273
+	/**
274
+	 * @return ArrayData|boolean
275
+	 */
276
+	public function getAddressSearchCoords()
277
+	{
278
+		$addressVar = Config::inst()->get(DistanceDataExtension::class, 'address_var');
279
+		if (!$this->request->getVar($addressVar)) {
280
+			return false;
281
+		}
282
+		if (class_exists(GoogleGeocoder::class)) {
283
+			$geocoder = new GoogleGeocoder($this->request->getVar($addressVar));
284
+			$response = $geocoder->getResult();
285
+			$lat = $response->getLatitude();
286
+			$lng = $response->getLongitude();
287
+
288
+			return new ArrayData([
289
+				"Lat" => $lat,
290
+				"Lng" => $lng,
291
+			]);
292
+		}
293
+	}
294
+
295
+	/**
296
+	 * @param HTTPRequest $request
297
+	 *
298
+	 * @return \SilverStripe\View\ViewableData_Customised
299
+	 */
300
+	public function index(HTTPRequest $request)
301
+	{
302
+		if ($this->getTrigger($request)) {
303
+			$locations = $this->getLocations();
304
+		} else {
305
+			$locations = ArrayList::create();
306
+		}
307
+
308
+		return $this->customise([
309
+			'Locations' => $locations,
310
+		]);
311
+	}
312
+
313
+	/**
314
+	 * Renders locations in xml format
315
+	 *
316
+	 * @return \SilverStripe\ORM\FieldType\DBHTMLText
317
+	 */
318
+	public function xml()
319
+	{
320
+		$this->getResponse()->addHeader("Content-Type", "application/xml");
321
+		$data = new ArrayData([
322
+			"Locations" => $this->getLocations(),
323
+			"AddressCoords" => $this->getAddressSearchCoords(),
324
+		]);
325
+
326
+		return $data->renderWith('Dynamic/Locator/Data/XML');
327
+	}
328
+
329
+	/**
330
+	 * Renders locations in json format
331
+	 *
332
+	 * @return \SilverStripe\ORM\FieldType\DBHTMLText
333
+	 */
334
+	public function json()
335
+	{
336
+		$this->getResponse()->addHeader("Content-Type", "application/json");
337
+		$data = new ArrayData([
338
+			"Locations" => $this->getLocations(),
339
+			"AddressCoords" => $this->getAddressSearchCoords(),
340
+		]);
341
+
342
+		return $data->renderWith('Dynamic/Locator/Data/JSON');
343
+	}
344
+
345
+	/**
346
+	 * LocationSearch form.
347
+	 *
348
+	 * Search form for locations, updates map and results list via AJAX
349
+	 *
350
+	 * @return \SilverStripe\Forms\Form
351
+	 */
352
+	public function LocationSearch()
353
+	{
354
+
355
+		$form = LocatorForm::create($this, 'LocationSearch');
356
+
357
+		$this->extend('updateLocationSearch', $form);
358
+
359
+		return $form
360
+			->setFormMethod('GET')
361
+			->setFormAction($this->Link())
362
+			->disableSecurityToken()
363
+			->loadDataFrom($this->request->getVars());
364
+	}
365 365
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 
100 100
         // google maps api key
101 101
         $key = Config::inst()->get(GoogleGeocoder::class, 'map_api_key');
102
-        Requirements::javascript('https://maps.google.com/maps/api/js?key=' . $key);
102
+        Requirements::javascript('https://maps.google.com/maps/api/js?key='.$key);
103 103
 
104 104
         $mapSettings = [
105 105
             'fullMapStart' => true,
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
         unset($vars['url']);
148 148
         $url = '';
149 149
         if (count($vars)) {
150
-            $url .= '?' . http_build_query($vars);
150
+            $url .= '?'.http_build_query($vars);
151 151
         }
152 152
         $mapSettings['dataLocation'] = Controller::join_links($this->Link(), 'xml.xml', $url);
153 153
 
@@ -249,8 +249,8 @@  discard block
 block discarded – undo
249 249
         if ($this->getShowRadius()) {
250 250
             $radiusVar = $this->data()->config()->get('radius_var');
251 251
 
252
-            if ($radius = (int)$request->getVar($radiusVar)) {
253
-                $locations = $locations->filterByCallback(function ($location) use (&$radius) {
252
+            if ($radius = (int) $request->getVar($radiusVar)) {
253
+                $locations = $locations->filterByCallback(function($location) use (&$radius) {
254 254
                     return $location->Distance <= $radius;
255 255
                 });
256 256
             }
Please login to merge, or discard this patch.
src/Page/LocationPage.php 2 patches
Indentation   +256 added lines, -256 removed lines patch added patch discarded remove patch
@@ -31,260 +31,260 @@
 block discarded – undo
31 31
  */
32 32
 class LocationPage extends \Page implements PermissionProvider
33 33
 {
34
-    /**
35
-     * @var string
36
-     */
37
-    private static $singular_name = 'Location';
38
-
39
-    /**
40
-     * @var string
41
-     */
42
-    private static $plural_name = 'Locations';
43
-
44
-    /**
45
-     * @var array
46
-     */
47
-    private static $db = [
48
-        'Title' => 'Varchar(255)',
49
-        'Featured' => 'Boolean',
50
-        'Website' => 'Varchar(255)',
51
-        'Phone' => 'Varchar(40)',
52
-        'Email' => 'Varchar(255)',
53
-        'Fax' => 'Varchar(45)',
54
-        'Import_ID' => 'Int',
55
-        'LegacyObjectID' => 'Int',
56
-    ];
57
-
58
-    private static $many_many = [
59
-        'Categories' => LocationCategory::class,
60
-    ];
61
-
62
-    /**
63
-     * @var string
64
-     */
65
-    private static $table_name = 'LocationPage';
66
-
67
-    /**
68
-     * @var array
69
-     */
70
-    private static $casting = [
71
-        'distance' => 'Decimal(9,3)',
72
-    ];
73
-
74
-    /**
75
-     * @var string
76
-     */
77
-    private static $default_sort = 'Title';
78
-
79
-    /**
80
-     * api access via Restful Server module
81
-     *
82
-     * @var bool
83
-     */
84
-    private static $api_access = true;
85
-
86
-    /**
87
-     * search fields for Model Admin
88
-     *
89
-     * @var array
90
-     */
91
-    private static $searchable_fields = [
92
-        'Title',
93
-        'Address',
94
-        'City',
95
-        'State',
96
-        'PostalCode',
97
-        'Country',
98
-        'Website',
99
-        'Phone',
100
-        'Email',
101
-        'Featured',
102
-    ];
103
-
104
-    /**
105
-     * columns for grid field
106
-     *
107
-     * @var array
108
-     */
109
-    private static $summary_fields = [
110
-        'Title',
111
-        'Address',
112
-        'Address2',
113
-        'City',
114
-        'State',
115
-        'PostalCode',
116
-        'CountryCode',
117
-        'Phone' => 'Phone',
118
-        'Fax' => 'Fax',
119
-        'Email' => 'Email',
120
-        'Website' => 'Website',
121
-        'Featured',
122
-        'CategoryList',
123
-        'Lat',
124
-        'Lng',
125
-        'Import_ID',
126
-    ];
127
-
128
-    /**
129
-     * Coords status for $summary_fields
130
-     *
131
-     * @return string
132
-     */
133
-    public function getCoords()
134
-    {
135
-        return ($this->Lat != 0 && $this->Lng != 0) ? 'true' : 'false';
136
-    }
137
-
138
-    /**
139
-     * @return string
140
-     */
141
-    public function getCategoryList()
142
-    {
143
-        if ($this->Categories()->count()) {
144
-            return implode(', ', $this->Categories()->column('Name'));
145
-        }
146
-
147
-        return '';
148
-    }
149
-
150
-    /**
151
-     * @return bool|string
152
-     */
153
-    public function getCountryCode()
154
-    {
155
-        if ($this->Country) {
156
-            return strtoupper($this->Country);
157
-        }
158
-
159
-        return false;
160
-    }
161
-
162
-    /**
163
-     * custom labels for fields
164
-     *
165
-     * @param bool $includerelations
166
-     * @return array|string
167
-     */
168
-    public function fieldLabels($includerelations = true)
169
-    {
170
-        $labels = parent::fieldLabels($includerelations);
171
-
172
-        $labels['Title'] = 'Name';
173
-        $labels['Address2'] = 'Address 2';
174
-        $labels['PostalCode'] = 'Postal Code';
175
-        $labels['Categories.Name'] = 'Categories';
176
-        $labels['Featured.NiceAsBoolean'] = 'Featured';
177
-
178
-        return $labels;
179
-    }
180
-
181
-    /**
182
-     * @return FieldList
183
-     */
184
-    public function getCMSFields()
185
-    {
186
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
187
-            $fields->addFieldsToTab(
188
-                'Root.Main',
189
-                [
190
-                    CheckboxField::create('Featured')
191
-                        ->setTitle('Featured'),
192
-                    TextField::create('Website')
193
-                        ->setTitle('Website')
194
-                        ->setDescription('Include the http/https (example: https://google.com)'),
195
-                    TextField::create('Phone')
196
-                        ->setTitle('Phone'),
197
-                    EmailField::create('Email')
198
-                        ->setTitle('Email'),
199
-                    TextField::create('Fax')
200
-                        ->setTitle('Fax'),
201
-                ],
202
-                'Content'
203
-            );
204
-
205
-            if ($this->exists()) {
206
-                $fields->addFieldToTab(
207
-                    'Root.Categories',
208
-                    GridField::create(
209
-                        'Categories',
210
-                        'Categories',
211
-                        $this->Categories(),
212
-                        $catConfig = GridFieldConfig_RelationEditor::create()
213
-                    )
214
-                );
215
-
216
-                $catConfig->removeComponentsByType([
217
-                    GridFieldAddExistingAutocompleter::class,
218
-                ])->addComponents([
219
-                    new GridFieldAddExistingSearchButton()
220
-                ]);
221
-            }
222
-        });
223
-
224
-        return parent::getCMSFields();
225
-    }
226
-
227
-    /**
228
-     * @param null $member
229
-     * @param array $context
230
-     * @return bool
231
-     */
232
-    public function canView($member = null, $context = [])
233
-    {
234
-        return true;
235
-    }
236
-
237
-    /**
238
-     * @param null $member
239
-     * @param array $context
240
-     * @return bool|int
241
-     */
242
-    public function canEdit($member = null, $context = [])
243
-    {
244
-        return Permission::check('Location_EDIT', 'any', $member);
245
-    }
246
-
247
-    /**
248
-     * @param null $member
249
-     * @param array $context
250
-     * @return bool|int
251
-     */
252
-    public function canDelete($member = null, $context = [])
253
-    {
254
-        return Permission::check('Location_DELETE', 'any', $member);
255
-    }
256
-
257
-    /**
258
-     * @param null $member
259
-     * @param array $context
260
-     * @return bool|int
261
-     */
262
-    public function canCreate($member = null, $context = [])
263
-    {
264
-        return Permission::check('Location_CREATE', 'any', $member);
265
-    }
266
-
267
-    /**
268
-     * @return array
269
-     */
270
-    public function providePermissions()
271
-    {
272
-        return [
273
-            'Location_EDIT' => 'Edit a Location',
274
-            'Location_DELETE' => 'Delete a Location',
275
-            'Location_CREATE' => 'Create a Location',
276
-        ];
277
-    }
278
-
279
-    /**
280
-     * @return string
281
-     */
282
-    public function getWebsiteURL()
283
-    {
284
-        $url = $this->Website;
285
-
286
-        $this->extend('updateWebsiteURL', $url);
287
-
288
-        return $url;
289
-    }
34
+	/**
35
+	 * @var string
36
+	 */
37
+	private static $singular_name = 'Location';
38
+
39
+	/**
40
+	 * @var string
41
+	 */
42
+	private static $plural_name = 'Locations';
43
+
44
+	/**
45
+	 * @var array
46
+	 */
47
+	private static $db = [
48
+		'Title' => 'Varchar(255)',
49
+		'Featured' => 'Boolean',
50
+		'Website' => 'Varchar(255)',
51
+		'Phone' => 'Varchar(40)',
52
+		'Email' => 'Varchar(255)',
53
+		'Fax' => 'Varchar(45)',
54
+		'Import_ID' => 'Int',
55
+		'LegacyObjectID' => 'Int',
56
+	];
57
+
58
+	private static $many_many = [
59
+		'Categories' => LocationCategory::class,
60
+	];
61
+
62
+	/**
63
+	 * @var string
64
+	 */
65
+	private static $table_name = 'LocationPage';
66
+
67
+	/**
68
+	 * @var array
69
+	 */
70
+	private static $casting = [
71
+		'distance' => 'Decimal(9,3)',
72
+	];
73
+
74
+	/**
75
+	 * @var string
76
+	 */
77
+	private static $default_sort = 'Title';
78
+
79
+	/**
80
+	 * api access via Restful Server module
81
+	 *
82
+	 * @var bool
83
+	 */
84
+	private static $api_access = true;
85
+
86
+	/**
87
+	 * search fields for Model Admin
88
+	 *
89
+	 * @var array
90
+	 */
91
+	private static $searchable_fields = [
92
+		'Title',
93
+		'Address',
94
+		'City',
95
+		'State',
96
+		'PostalCode',
97
+		'Country',
98
+		'Website',
99
+		'Phone',
100
+		'Email',
101
+		'Featured',
102
+	];
103
+
104
+	/**
105
+	 * columns for grid field
106
+	 *
107
+	 * @var array
108
+	 */
109
+	private static $summary_fields = [
110
+		'Title',
111
+		'Address',
112
+		'Address2',
113
+		'City',
114
+		'State',
115
+		'PostalCode',
116
+		'CountryCode',
117
+		'Phone' => 'Phone',
118
+		'Fax' => 'Fax',
119
+		'Email' => 'Email',
120
+		'Website' => 'Website',
121
+		'Featured',
122
+		'CategoryList',
123
+		'Lat',
124
+		'Lng',
125
+		'Import_ID',
126
+	];
127
+
128
+	/**
129
+	 * Coords status for $summary_fields
130
+	 *
131
+	 * @return string
132
+	 */
133
+	public function getCoords()
134
+	{
135
+		return ($this->Lat != 0 && $this->Lng != 0) ? 'true' : 'false';
136
+	}
137
+
138
+	/**
139
+	 * @return string
140
+	 */
141
+	public function getCategoryList()
142
+	{
143
+		if ($this->Categories()->count()) {
144
+			return implode(', ', $this->Categories()->column('Name'));
145
+		}
146
+
147
+		return '';
148
+	}
149
+
150
+	/**
151
+	 * @return bool|string
152
+	 */
153
+	public function getCountryCode()
154
+	{
155
+		if ($this->Country) {
156
+			return strtoupper($this->Country);
157
+		}
158
+
159
+		return false;
160
+	}
161
+
162
+	/**
163
+	 * custom labels for fields
164
+	 *
165
+	 * @param bool $includerelations
166
+	 * @return array|string
167
+	 */
168
+	public function fieldLabels($includerelations = true)
169
+	{
170
+		$labels = parent::fieldLabels($includerelations);
171
+
172
+		$labels['Title'] = 'Name';
173
+		$labels['Address2'] = 'Address 2';
174
+		$labels['PostalCode'] = 'Postal Code';
175
+		$labels['Categories.Name'] = 'Categories';
176
+		$labels['Featured.NiceAsBoolean'] = 'Featured';
177
+
178
+		return $labels;
179
+	}
180
+
181
+	/**
182
+	 * @return FieldList
183
+	 */
184
+	public function getCMSFields()
185
+	{
186
+		$this->beforeUpdateCMSFields(function (FieldList $fields) {
187
+			$fields->addFieldsToTab(
188
+				'Root.Main',
189
+				[
190
+					CheckboxField::create('Featured')
191
+						->setTitle('Featured'),
192
+					TextField::create('Website')
193
+						->setTitle('Website')
194
+						->setDescription('Include the http/https (example: https://google.com)'),
195
+					TextField::create('Phone')
196
+						->setTitle('Phone'),
197
+					EmailField::create('Email')
198
+						->setTitle('Email'),
199
+					TextField::create('Fax')
200
+						->setTitle('Fax'),
201
+				],
202
+				'Content'
203
+			);
204
+
205
+			if ($this->exists()) {
206
+				$fields->addFieldToTab(
207
+					'Root.Categories',
208
+					GridField::create(
209
+						'Categories',
210
+						'Categories',
211
+						$this->Categories(),
212
+						$catConfig = GridFieldConfig_RelationEditor::create()
213
+					)
214
+				);
215
+
216
+				$catConfig->removeComponentsByType([
217
+					GridFieldAddExistingAutocompleter::class,
218
+				])->addComponents([
219
+					new GridFieldAddExistingSearchButton()
220
+				]);
221
+			}
222
+		});
223
+
224
+		return parent::getCMSFields();
225
+	}
226
+
227
+	/**
228
+	 * @param null $member
229
+	 * @param array $context
230
+	 * @return bool
231
+	 */
232
+	public function canView($member = null, $context = [])
233
+	{
234
+		return true;
235
+	}
236
+
237
+	/**
238
+	 * @param null $member
239
+	 * @param array $context
240
+	 * @return bool|int
241
+	 */
242
+	public function canEdit($member = null, $context = [])
243
+	{
244
+		return Permission::check('Location_EDIT', 'any', $member);
245
+	}
246
+
247
+	/**
248
+	 * @param null $member
249
+	 * @param array $context
250
+	 * @return bool|int
251
+	 */
252
+	public function canDelete($member = null, $context = [])
253
+	{
254
+		return Permission::check('Location_DELETE', 'any', $member);
255
+	}
256
+
257
+	/**
258
+	 * @param null $member
259
+	 * @param array $context
260
+	 * @return bool|int
261
+	 */
262
+	public function canCreate($member = null, $context = [])
263
+	{
264
+		return Permission::check('Location_CREATE', 'any', $member);
265
+	}
266
+
267
+	/**
268
+	 * @return array
269
+	 */
270
+	public function providePermissions()
271
+	{
272
+		return [
273
+			'Location_EDIT' => 'Edit a Location',
274
+			'Location_DELETE' => 'Delete a Location',
275
+			'Location_CREATE' => 'Create a Location',
276
+		];
277
+	}
278
+
279
+	/**
280
+	 * @return string
281
+	 */
282
+	public function getWebsiteURL()
283
+	{
284
+		$url = $this->Website;
285
+
286
+		$this->extend('updateWebsiteURL', $url);
287
+
288
+		return $url;
289
+	}
290 290
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -183,7 +183,7 @@
 block discarded – undo
183 183
      */
184 184
     public function getCMSFields()
185 185
     {
186
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
186
+        $this->beforeUpdateCMSFields(function(FieldList $fields) {
187 187
             $fields->addFieldsToTab(
188 188
                 'Root.Main',
189 189
                 [
Please login to merge, or discard this patch.
src/admin/LocationAdmin.php 1 patch
Indentation   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -17,83 +17,83 @@
 block discarded – undo
17 17
 class LocationAdmin extends ModelAdmin
18 18
 {
19 19
 
20
-    /**
21
-     * @var array
22
-     */
23
-    private static $managed_models = [
24
-        Location::class,
25
-        LocationCategory::class,
26
-    ];
20
+	/**
21
+	 * @var array
22
+	 */
23
+	private static $managed_models = [
24
+		Location::class,
25
+		LocationCategory::class,
26
+	];
27 27
 
28
-    /**
29
-     * @var array
30
-     */
31
-    private static $model_importers = [
32
-        Location::class => LocationCsvBulkLoader::class,
33
-        LocationCategory::class => CsvBulkLoader::class,
34
-    ];
28
+	/**
29
+	 * @var array
30
+	 */
31
+	private static $model_importers = [
32
+		Location::class => LocationCsvBulkLoader::class,
33
+		LocationCategory::class => CsvBulkLoader::class,
34
+	];
35 35
 
36
-    /**
37
-     * @var string
38
-     */
39
-    private static $menu_title = 'Locator';
40
-    /**
41
-     * @var string
42
-     */
43
-    private static $url_segment = 'locator';
36
+	/**
37
+	 * @var string
38
+	 */
39
+	private static $menu_title = 'Locator';
40
+	/**
41
+	 * @var string
42
+	 */
43
+	private static $url_segment = 'locator';
44 44
 
45
-    /**
46
-     * @return array
47
-     */
48
-    public function getExportFields()
49
-    {
50
-        if ($this->modelClass == Location::class) {
51
-            $fields = [
52
-                'Title' => 'Name',
53
-                'Address' => 'Address',
54
-                'Address2' => 'Address2',
55
-                'City' => 'City',
56
-                'State' => 'State',
57
-                'PostalCode' => 'PostalCode',
58
-                'CountryCode' => 'Country',
59
-                'Phone' => 'Phone',
60
-                'Fax' => 'Fax',
61
-                'Email' => 'Email',
62
-                'Website' => 'Website',
63
-                'Featured' => 'Featured',
64
-                'CategoryList' => 'Categories',
65
-                'Lat' => 'Lat',
66
-                'Lng' => 'Lng',
67
-                'Import_ID' => 'Import_ID',
68
-            ];
69
-        }
45
+	/**
46
+	 * @return array
47
+	 */
48
+	public function getExportFields()
49
+	{
50
+		if ($this->modelClass == Location::class) {
51
+			$fields = [
52
+				'Title' => 'Name',
53
+				'Address' => 'Address',
54
+				'Address2' => 'Address2',
55
+				'City' => 'City',
56
+				'State' => 'State',
57
+				'PostalCode' => 'PostalCode',
58
+				'CountryCode' => 'Country',
59
+				'Phone' => 'Phone',
60
+				'Fax' => 'Fax',
61
+				'Email' => 'Email',
62
+				'Website' => 'Website',
63
+				'Featured' => 'Featured',
64
+				'CategoryList' => 'Categories',
65
+				'Lat' => 'Lat',
66
+				'Lng' => 'Lng',
67
+				'Import_ID' => 'Import_ID',
68
+			];
69
+		}
70 70
 
71
-        if (!isset($fields)) {
72
-            $fields = parent::getExportFields();
73
-        }
71
+		if (!isset($fields)) {
72
+			$fields = parent::getExportFields();
73
+		}
74 74
 
75
-        $this->extend('updateGetExportFields', $fields);
75
+		$this->extend('updateGetExportFields', $fields);
76 76
 
77
-        return $fields;
78
-    }
77
+		return $fields;
78
+	}
79 79
 
80
-    /**
81
-     * @param null $id
82
-     * @param null $fields
83
-     * @return $this|Form
84
-     */
85
-    public function getEditForm($id = null, $fields = null)
86
-    {
87
-        $form = parent::getEditForm($id, $fields);
80
+	/**
81
+	 * @param null $id
82
+	 * @param null $fields
83
+	 * @return $this|Form
84
+	 */
85
+	public function getEditForm($id = null, $fields = null)
86
+	{
87
+		$form = parent::getEditForm($id, $fields);
88 88
 
89
-        if ($this->modelClass == Location::class) {
90
-            /** @var GridField $gridField */
91
-            if ($gridField = $form->Fields()->fieldByName($this->sanitiseClassName($this->modelClass))) {
92
-                $gridField->getConfig()
93
-                    ->removeComponentsByType('GridFieldDeleteAction');
94
-            }
95
-        }
89
+		if ($this->modelClass == Location::class) {
90
+			/** @var GridField $gridField */
91
+			if ($gridField = $form->Fields()->fieldByName($this->sanitiseClassName($this->modelClass))) {
92
+				$gridField->getConfig()
93
+					->removeComponentsByType('GridFieldDeleteAction');
94
+			}
95
+		}
96 96
 
97
-        return $form;
98
-    }
97
+		return $form;
98
+	}
99 99
 }
Please login to merge, or discard this patch.
src/Tasks/LocationToPageTask.php 1 patch
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -15,72 +15,72 @@
 block discarded – undo
15 15
  */
16 16
 class LocationToPageTask extends BuildTask
17 17
 {
18
-    /**
19
-     * @var string
20
-     */
21
-    protected $title = 'Locator - Location to Page Task';
18
+	/**
19
+	 * @var string
20
+	 */
21
+	protected $title = 'Locator - Location to Page Task';
22 22
 
23
-    /**
24
-     * @var string
25
-     */
26
-    private static $segment = 'locator-location-to-page-task';
23
+	/**
24
+	 * @var string
25
+	 */
26
+	private static $segment = 'locator-location-to-page-task';
27 27
 
28
-    /**
29
-     * @var bool
30
-     */
31
-    private static $auto_publish_location = false;
28
+	/**
29
+	 * @var bool
30
+	 */
31
+	private static $auto_publish_location = false;
32 32
 
33
-    /**
34
-     * @param \SilverStripe\Control\HTTPRequest $request
35
-     */
36
-    public function run($request)
37
-    {
38
-        $this->migrateLocations();
39
-    }
33
+	/**
34
+	 * @param \SilverStripe\Control\HTTPRequest $request
35
+	 */
36
+	public function run($request)
37
+	{
38
+		$this->migrateLocations();
39
+	}
40 40
 
41
-    /**
42
-     *
43
-     */
44
-    protected function migrateLocations()
45
-    {
46
-        if (!$parent = Locator::get()->first()) {
47
-            $parent = Locator::create();
48
-            $parent->Title = "Locator";
49
-            $parent->writeToStage(Versioned::DRAFT);
50
-        }
41
+	/**
42
+	 *
43
+	 */
44
+	protected function migrateLocations()
45
+	{
46
+		if (!$parent = Locator::get()->first()) {
47
+			$parent = Locator::create();
48
+			$parent->Title = "Locator";
49
+			$parent->writeToStage(Versioned::DRAFT);
50
+		}
51 51
 
52
-        /** @var Location $location */
53
-        foreach ($this->getLocations() as $location) {
54
-            if (!LocationPage::get()->filter('LegacyObjectID', $location->ID)->first()) {
55
-                if ($location->hasMethod('isPublished')) {
56
-                    $published = $location->isPublished();
57
-                }
52
+		/** @var Location $location */
53
+		foreach ($this->getLocations() as $location) {
54
+			if (!LocationPage::get()->filter('LegacyObjectID', $location->ID)->first()) {
55
+				if ($location->hasMethod('isPublished')) {
56
+					$published = $location->isPublished();
57
+				}
58 58
 
59
-                /** @var LocationPage $newLocation */
60
-                $newLocation = Injector::inst()->create(LocationPage::class, $location->toMap(), false);
61
-                $newLocation->setClassName(LocationPage::class);
62
-                $newLocation->ID = null;
63
-                $newLocation->ParentID = $parent->ID;
64
-                $newLocation->LegacyObjectID = $location->ID;
59
+				/** @var LocationPage $newLocation */
60
+				$newLocation = Injector::inst()->create(LocationPage::class, $location->toMap(), false);
61
+				$newLocation->setClassName(LocationPage::class);
62
+				$newLocation->ID = null;
63
+				$newLocation->ParentID = $parent->ID;
64
+				$newLocation->LegacyObjectID = $location->ID;
65 65
 
66
-                $this->extend('preLocationMigrationUpdate', $location, $newLocation);
66
+				$this->extend('preLocationMigrationUpdate', $location, $newLocation);
67 67
 
68
-                $newLocation->writeToStage(Versioned::DRAFT);
68
+				$newLocation->writeToStage(Versioned::DRAFT);
69 69
 
70
-                if ((isset($published) && $published) || $this->config()->get('auto_publish_location')) {
71
-                    $newLocation->publishSingle();
72
-                }
73
-            }
74
-        }
75
-    }
70
+				if ((isset($published) && $published) || $this->config()->get('auto_publish_location')) {
71
+					$newLocation->publishSingle();
72
+				}
73
+			}
74
+		}
75
+	}
76 76
 
77
-    /**
78
-     * @return \Generator
79
-     */
80
-    protected function getLocations()
81
-    {
82
-        foreach (Location::get() as $location) {
83
-            yield $location;
84
-        }
85
-    }
77
+	/**
78
+	 * @return \Generator
79
+	 */
80
+	protected function getLocations()
81
+	{
82
+		foreach (Location::get() as $location) {
83
+			yield $location;
84
+		}
85
+	}
86 86
 }
Please login to merge, or discard this patch.
src/Tasks/LocationPublishTask.php 2 patches
Indentation   +66 added lines, -66 removed lines patch added patch discarded remove patch
@@ -11,76 +11,76 @@
 block discarded – undo
11 11
  */
12 12
 class LocationPublishTask extends BuildTask
13 13
 {
14
-    /**
15
-     * @var string
16
-     */
17
-    protected $title = 'Publish all Locations';
18
-    /**
19
-     * @var string
20
-     */
21
-    protected $description = 'Migration task - pre versioning on Location';
22
-    /**
23
-     * @var bool
24
-     */
25
-    protected $enabled = true;
14
+	/**
15
+	 * @var string
16
+	 */
17
+	protected $title = 'Publish all Locations';
18
+	/**
19
+	 * @var string
20
+	 */
21
+	protected $description = 'Migration task - pre versioning on Location';
22
+	/**
23
+	 * @var bool
24
+	 */
25
+	protected $enabled = true;
26 26
 
27
-    /**
28
-     * @param $request
29
-     */
30
-    public function run($request)
31
-    {
32
-        $class = ($request->getVar('locationclass')) ? $request->getVar('locationclass') : 'Location';
33
-        $this->publishLocations($class);
34
-    }
27
+	/**
28
+	 * @param $request
29
+	 */
30
+	public function run($request)
31
+	{
32
+		$class = ($request->getVar('locationclass')) ? $request->getVar('locationclass') : 'Location';
33
+		$this->publishLocations($class);
34
+	}
35 35
 
36
-    /**
37
-     * @param string $class
38
-     * @return \Generator
39
-     */
40
-    protected function iterateLocations($class)
41
-    {
42
-        foreach ($class::get()->filter('ShowInLocator', true) as $location) {
43
-            yield $location;
44
-        }
45
-    }
36
+	/**
37
+	 * @param string $class
38
+	 * @return \Generator
39
+	 */
40
+	protected function iterateLocations($class)
41
+	{
42
+		foreach ($class::get()->filter('ShowInLocator', true) as $location) {
43
+			yield $location;
44
+		}
45
+	}
46 46
 
47
-    /**
48
-     * mark all ProductDetail records as ShowInMenus = 0.
49
-     *
50
-     * @param string $class
51
-     */
52
-    public function publishLocations($class)
53
-    {
54
-        if (!isset($class) || !class_exists($class) || !$class instanceof Location) {
55
-            $class = 'Location';
56
-        }
57
-        $ct = 0;
58
-        $publish = function ($location) use (&$ct) {
59
-            if (!$location->isPublished()) {
60
-                $title = $location->Title;
61
-                $location->writeToStage('Stage');
62
-                $location->publish('Stage', 'Live');
63
-                static::write_message($title);
64
-                ++$ct;
65
-            }
66
-        };
47
+	/**
48
+	 * mark all ProductDetail records as ShowInMenus = 0.
49
+	 *
50
+	 * @param string $class
51
+	 */
52
+	public function publishLocations($class)
53
+	{
54
+		if (!isset($class) || !class_exists($class) || !$class instanceof Location) {
55
+			$class = 'Location';
56
+		}
57
+		$ct = 0;
58
+		$publish = function ($location) use (&$ct) {
59
+			if (!$location->isPublished()) {
60
+				$title = $location->Title;
61
+				$location->writeToStage('Stage');
62
+				$location->publish('Stage', 'Live');
63
+				static::write_message($title);
64
+				++$ct;
65
+			}
66
+		};
67 67
 
68
-        foreach ($this->iterateLocations($class) as $location) {
69
-            $publish($location);
70
-        }
68
+		foreach ($this->iterateLocations($class) as $location) {
69
+			$publish($location);
70
+		}
71 71
 
72
-        static::write_message("{$ct} locations updated.");
73
-    }
72
+		static::write_message("{$ct} locations updated.");
73
+	}
74 74
 
75
-    /**
76
-     * @param $message
77
-     */
78
-    protected static function write_message($message)
79
-    {
80
-        if (Director::is_cli()) {
81
-            echo "{$message}\n";
82
-        } else {
83
-            echo "{$message}<br><br>";
84
-        }
85
-    }
75
+	/**
76
+	 * @param $message
77
+	 */
78
+	protected static function write_message($message)
79
+	{
80
+		if (Director::is_cli()) {
81
+			echo "{$message}\n";
82
+		} else {
83
+			echo "{$message}<br><br>";
84
+		}
85
+	}
86 86
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -55,7 +55,7 @@
 block discarded – undo
55 55
             $class = 'Location';
56 56
         }
57 57
         $ct = 0;
58
-        $publish = function ($location) use (&$ct) {
58
+        $publish = function($location) use (&$ct) {
59 59
             if (!$location->isPublished()) {
60 60
                 $title = $location->Title;
61 61
                 $location->writeToStage('Stage');
Please login to merge, or discard this patch.
src/Tasks/LocationCategoriesTask.php 2 patches
Indentation   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -14,72 +14,72 @@
 block discarded – undo
14 14
 class LocationCategoriesTask extends BuildTask
15 15
 {
16 16
 
17
-    /**
18
-     * @var string
19
-     */
20
-    protected $title = 'Location categories to many_many';
21
-
22
-    /**
23
-     * @var string
24
-     */
25
-    protected $description = 'Migration task - Converts locations to have multiple categories';
26
-
27
-    /**
28
-     * @var bool
29
-     */
30
-    protected $enabled = true;
31
-
32
-    /**
33
-     * @param $request
34
-     */
35
-    public function run($request)
36
-    {
37
-        /** @var DataObject $class */
38
-        $class = ($request->getVar('locationclass')) ? $request->getVar('locationclass') : Location::class;
39
-        $class::add_extension(LocationCategoryExtension::class);
40
-
41
-
42
-        $categories = [];
43
-
44
-        $convert = function (DataObject $location) use (&$categories) {
45
-            /** @var Location $location */
46
-            // skip if no category
47
-            if ($location->CategoryID > 0) {
48
-                $categories[$location->CategoryID][] = $location->ID;
49
-            }
50
-        };
51
-
52
-        foreach ($this->iterateLocations($class) as $location) {
53
-            $convert($location);
54
-        }
55
-
56
-        $catCt = 0;
57
-        $locCT = 0;
58
-
59
-        foreach ($categories as $categoryID => $locations) {
60
-            /** @var LocationCategory $category */
61
-            $category = LocationCategory::get()->byID($categoryID);
62
-            $category->Locations()->addMany($locations);
63
-
64
-            $catCt++;
65
-            $locCT += count($locations);
66
-        }
67
-
68
-        echo "{$catCt} categories converted<br />";
69
-        echo "{$locCT} location relations converted<br />";
70
-
71
-        $time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
72
-        echo "Process Time: {$time} seconds";
73
-    }
74
-
75
-    /**
76
-     * @param string $class
77
-     * @return \Generator
78
-     */
79
-    protected function iterateLocations($class)
80
-    {
81
-        foreach ($class::get() as $location) {
82
-            yield $location;
83
-        }
84
-    }
17
+	/**
18
+	 * @var string
19
+	 */
20
+	protected $title = 'Location categories to many_many';
21
+
22
+	/**
23
+	 * @var string
24
+	 */
25
+	protected $description = 'Migration task - Converts locations to have multiple categories';
26
+
27
+	/**
28
+	 * @var bool
29
+	 */
30
+	protected $enabled = true;
31
+
32
+	/**
33
+	 * @param $request
34
+	 */
35
+	public function run($request)
36
+	{
37
+		/** @var DataObject $class */
38
+		$class = ($request->getVar('locationclass')) ? $request->getVar('locationclass') : Location::class;
39
+		$class::add_extension(LocationCategoryExtension::class);
40
+
41
+
42
+		$categories = [];
43
+
44
+		$convert = function (DataObject $location) use (&$categories) {
45
+			/** @var Location $location */
46
+			// skip if no category
47
+			if ($location->CategoryID > 0) {
48
+				$categories[$location->CategoryID][] = $location->ID;
49
+			}
50
+		};
51
+
52
+		foreach ($this->iterateLocations($class) as $location) {
53
+			$convert($location);
54
+		}
55
+
56
+		$catCt = 0;
57
+		$locCT = 0;
58
+
59
+		foreach ($categories as $categoryID => $locations) {
60
+			/** @var LocationCategory $category */
61
+			$category = LocationCategory::get()->byID($categoryID);
62
+			$category->Locations()->addMany($locations);
63
+
64
+			$catCt++;
65
+			$locCT += count($locations);
66
+		}
67
+
68
+		echo "{$catCt} categories converted<br />";
69
+		echo "{$locCT} location relations converted<br />";
70
+
71
+		$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
72
+		echo "Process Time: {$time} seconds";
73
+	}
74
+
75
+	/**
76
+	 * @param string $class
77
+	 * @return \Generator
78
+	 */
79
+	protected function iterateLocations($class)
80
+	{
81
+		foreach ($class::get() as $location) {
82
+			yield $location;
83
+		}
84
+	}
85 85
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -41,7 +41,7 @@
 block discarded – undo
41 41
 
42 42
         $categories = [];
43 43
 
44
-        $convert = function (DataObject $location) use (&$categories) {
44
+        $convert = function(DataObject $location) use (&$categories) {
45 45
             /** @var Location $location */
46 46
             // skip if no category
47 47
             if ($location->CategoryID > 0) {
Please login to merge, or discard this patch.
src/Tasks/LocationCategoryExtension.php 1 patch
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -13,7 +13,7 @@
 block discarded – undo
13 13
  */
14 14
 class LocationCategoryExtension extends DataExtension
15 15
 {
16
-    private static $has_one = [
17
-        'Category' => LocationCategory::class,
18
-    ];
16
+	private static $has_one = [
17
+		'Category' => LocationCategory::class,
18
+	];
19 19
 }
Please login to merge, or discard this patch.