1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Dynamic\Locator\Tasks; |
4
|
|
|
|
5
|
|
|
use Dynamic\Locator\Model\Location; |
6
|
|
|
use Dynamic\Locator\Model\LocationCategory; |
7
|
|
|
use SilverStripe\Dev\BuildTask; |
8
|
|
|
use SilverStripe\ORM\DataObject; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class LocationCategoriesTask |
12
|
|
|
* @package Dynamic\Locator\Tasks |
13
|
|
|
*/ |
14
|
|
|
class LocationCategoriesTask extends BuildTask |
15
|
|
|
{ |
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
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|