migratePostSeries()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
c 0
b 0
f 0
rs 9.0648
cc 5
nc 3
nop 0
1
<?php
2
3
namespace GinoPane\BlogTaxonomy\Classes\MigrationCommand\Migrations;
4
5
use Exception;
6
use Illuminate\Support\Facades\DB;
7
use October\Rain\Database\Collection;
8
use October\Rain\Support\Facades\Schema;
9
use October\Rain\Database\ModelException;
10
use PKleindienst\BlogSeries\Models\Series;
11
use GinoPane\BlogTaxonomy\Models\Series as BlogTaxonomySeries;
12
use GinoPane\BlogTaxonomy\Classes\MigrationCommand\Exceptions\NoDataException;
13
14
/**
15
 * Class PkleindienstBlogSeriesMigration
16
 *
17
 * @package GinoPane\BlogTaxonomy\Classes\MigrationCommand\Migrations
18
 */
19
class PkleindienstBlogSeriesMigration extends AbstractMigration
20
{
21
    const PLUGIN_NAME = 'PKleindienst.BlogSeries';
22
23
    private $migratedSeriesIds = [];
24
25
    /**
26
     * Migrate plugin data
27
     */
28
    protected function migratePlugin()
29
    {
30
        try {
31
            $this->migrateSeries();
32
33
            $this->migrateRelatedSeries();
34
35
            $this->migratePostSeries();
36
        } catch (Exception $exception) {
37
            $this->command->error($exception->getMessage());
38
39
            $this->rollbackSeries();
40
        }
41
    }
42
43
    /**
44
     * Rolls back the migration process
45
     */
46
    private function rollbackSeries()
47
    {
48
        if (!empty($this->migratedSeriesIds)) {
49
            $this->command->warn('Rolling back migration');
50
51
            BlogTaxonomySeries::whereIn('id', array_keys($this->migratedSeriesIds))->delete();
52
53
            $this->command->warn('Roll back complete');
54
        }
55
    }
56
57
    /**
58
     * Migrate general series data
59
     *
60
     * @throws NoDataException
61
     */
62
    private function migrateSeries()
63
    {
64
        $this->command->info('Migrating series');
65
66
        $series = $this->getSeries();
67
68
        foreach ($series as $seriesRecord) {
69
            $blogTaxonomySeries = new BlogTaxonomySeries();
70
71
            $blogTaxonomySeries->slug = $seriesRecord->slug;
72
            $blogTaxonomySeries->title = $seriesRecord->title;
73
            $blogTaxonomySeries->description = $seriesRecord->description;
74
75
            try {
76
                $blogTaxonomySeries->save();
77
            } catch (ModelException $exception) {
0 ignored issues
show
Bug introduced by
The class October\Rain\Database\ModelException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
78
                $blogTaxonomySeries->slug .= '-migrated';
79
                $blogTaxonomySeries->title .= ' (migrated)';
80
81
                $blogTaxonomySeries->save();
82
            }
83
84
            $this->command->line(
85
                sprintf(
86
                    'Series "%s" => Blog Taxonomy Series "%s" (#%d)',
87
                    $seriesRecord->title,
88
                    $blogTaxonomySeries->title,
89
                    $blogTaxonomySeries->id
90
                )
91
            );
92
93
            $this->migratedSeriesIds[$blogTaxonomySeries->id] = $seriesRecord->id;
94
        }
95
96
        $this->command->info('All series have been migrated' . PHP_EOL);
97
    }
98
99
    /**
100
     * Migrate related series
101
     */
102
    private function migrateRelatedSeries()
103
    {
104
        if (empty($this->migratedSeriesIds) || !Schema::hasTable('pkleindienst_blogseries_related')) {
105
            return;
106
        }
107
108
        $this->command->info('Migrating related series');
109
110
        $relatedSeries = DB::table('pkleindienst_blogseries_related')->get();
111
112
        if (!count($relatedSeries)) {
113
            $this->command->warn('No related series found' . PHP_EOL);
114
115
            return;
116
        }
117
118
        $migratedSeries = array_flip($this->migratedSeriesIds);
119
120
        DB::transaction(function () use ($relatedSeries, $migratedSeries) {
121
            foreach ($relatedSeries as $relationRecord) {
122
                $seriesId = $migratedSeries[$relationRecord->series_id];
123
                $relatedSeriesId = $migratedSeries[$relationRecord->related_id];
124
125
                DB::table('ginopane_blogtaxonomy_related_series')->insert(
126
                    ['series_id' => $seriesId, 'related_series_id' => $relatedSeriesId]
127
                );
128
129
                $this->command->line(
130
                    sprintf(
131
                        'Relation "#%d" => "#%d" added',
132
                        $seriesId,
133
                        $relatedSeriesId
134
                    )
135
                );
136
            }
137
        });
138
139
        $this->command->info('Related series have been migrated' . PHP_EOL);
140
    }
141
142
    /**
143
     * Migrate series assigned to posts
144
     */
145
    private function migratePostSeries()
146
    {
147
        if (empty($this->migratedSeriesIds)) {
148
            return;
149
        }
150
151
        if (!$this->command->confirm(
152
            'Do you want to assign newly created series to posts (already assigned Blog Taxonomy series will be overwritten)'
153
        )) {
154
            return;
155
        }
156
157
        $this->command->info('Migrating series assigned to posts');
158
159
        $migratedSeries = array_flip($this->migratedSeriesIds);
160
161
        DB::transaction(function () use ($migratedSeries) {
162
            foreach ($migratedSeries as $oldSeriesId => $newSeriesId) {
163
                if (DB::table('rainlab_blog_posts')
164
                    ->where('series_id', $oldSeriesId)
165
                    ->update(['ginopane_blogtaxonomy_series_id' => $newSeriesId])
166
                ) {
167
                    $this->command->line(
168
                        sprintf(
169
                            'Series "#%d" has been assigned to a post',
170
                            $newSeriesId
171
                        )
172
                    );
173
                };
174
            }
175
        });
176
177
        $this->command->info('Migrated series has been assigned' . PHP_EOL);
178
    }
179
180
    /**
181
     * @return Collection|Series[]
182
     *
183
     * @throws NoDataException
184
     */
185
    private function getSeries()
186
    {
187
        $series = Series::all();
188
189
        if (!count($series)) {
190
            throw new NoDataException('No series records found');
191
        }
192
193
        $this->command->warn(sprintf('%d series found', count($series)));
194
195
        return $series;
196
    }
197
}