Completed
Push — master ( cb292b...347229 )
by Robbie
18s queued 10s
created

FixBlogDuplicatesTask::run()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace SilverStripe\Blog\Tasks;
4
5
use SilverStripe\Blog\Model\BlogCategory;
6
use SilverStripe\Blog\Model\BlogTag;
7
use SilverStripe\Control\Director;
8
use SilverStripe\Core\Convert;
9
use SilverStripe\Dev\BuildTask;
10
use SilverStripe\ORM\DataObject;
11
use SilverStripe\ORM\DB;
12
use SilverStripe\ORM\Queries\SQLSelect;
13
use SilverStripe\View\HTML;
14
15
class FixBlogDuplicatesTask extends BuildTask
16
{
17
    private static $segment = 'FixBlogDuplicatesTask';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
18
19
    protected $title = 'Fix blog duplicate categories / tags';
20
21
    protected $description = 'Merge categories and tags with the same title';
22
23
    public function run($request)
24
    {
25
        $this->dedupe(BlogTag::class, 'BlogPost_Tags', 'BlogTagID');
26
        $this->dedupe(BlogCategory::class, 'BlogPost_Categories', 'BlogCategoryID');
27
    }
28
29
    /**
30
     * Log message to console / page
31
     *
32
     * @param string $message
33
     */
34
    protected function message($message)
35
    {
36
        if (Director::is_cli()) {
37
            echo "{$message}\n";
38
        } else {
39
            echo HTML::createTag('p', [], Convert::raw2xml($message));
0 ignored issues
show
Bug introduced by
It seems like \SilverStripe\Core\Convert::raw2xml($message) targeting SilverStripe\Core\Convert::raw2xml() can also be of type array; however, SilverStripe\View\HTML::createTag() does only seem to accept string|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
40
        }
41
    }
42
43
    /**
44
     * Progress used for CLI output
45
     *
46
     * @var int
47
     */
48
    protected $printedDots = 0;
49
50
    /**
51
     * Render progress dots (20 dots per column)
52
     *
53
     * @param        $current
54
     * @param int    $total
55
     * @param string $character
56
     */
57
    protected function progress($current, $total = 0, $character = '.')
58
    {
59
        if (!Director::is_cli()) {
60
            return;
61
        }
62
        while ($this->printedDots < $current) {
63
            echo $character;
64
            $this->printedDots++;
65
            if ($this->printedDots % 80 === 0) {
66
                if ($total) {
67
                    $len = strlen($total);
68
                    echo str_pad("{$this->printedDots}/{$total}", $len * 2 + 2, ' ', STR_PAD_LEFT);
69
                }
70
                echo "\n";
71
            }
72
        }
73
    }
74
75
    /**
76
     * Deduplicate the given class
77
     *
78
     * @param string $class         Class name to dedupe
79
     * @param string $mappingTable  Table name mapping
80
     * @param string $relationField Name of foreign key relation field on mapping table
81
     */
82
    protected function dedupe($class, $mappingTable, $relationField)
83
    {
84
        $this->printedDots = 0;
85
86
        // Find all duplicates
87
        $itemTable = DataObject::getSchema()->tableName($class);
88
        $duplicates = SQLSelect::create()
89
            ->setSelect([
90
                'Title' => '"Title"',
91
                'Count' => 'COUNT(*)',
92
                'UseID' => 'MIN("ID")',
93
            ])
94
            ->setFrom($itemTable)
95
            ->setGroupBy('"Title"')
96
            ->setHaving('"Count" > 1');
97
98
        $count = $duplicates->count();
99
100
        $this->message("Found {$count} items with duplicates for type {$class}");
101
102
        if (!$count) {
103
            return;
104
        }
105
106
        $done = 0;
107
        foreach ($duplicates->execute() as $duplicate) {
108
            $title = $duplicate['Title'];
109
            $id = $duplicate['UseID'];
110
111
            DB::prepared_query(
112
                <<<SQL
113
UPDATE "{$mappingTable}"
114
INNER JOIN "{$itemTable}" ON "{$mappingTable}"."{$relationField}" = "{$itemTable}"."ID"
115
SET "{$mappingTable}"."{$relationField}" = ? 
116
WHERE "{$itemTable}"."Title" = ? 
117
SQL
118
                ,
119
                [$id, $title]
120
            );
121
122
            // Delete duplicates
123
            $duplicateItems = DataObject::get($class)->filter([
124
                'Title'  => $title,
125
                'ID:not' => $id,
126
            ]);
127
            /** @var DataObject $duplicateItem */
128
            foreach ($duplicateItems as $duplicateItem) {
129
                $duplicateItem->delete();
130
            }
131
132
            // Update progress bar
133
            $done++;
134
            $this->progress($done, $count);
135
        }
136
137
        $this->progress("");
138
        $this->progress("Completed cleaning duplicates for {$class}");
139
    }
140
}
141