Completed
Pull Request — master (#38)
by Philippe
05:00
created

ImageToAssetMigrateCommand   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 152
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 70
c 1
b 0
f 0
dl 0
loc 152
rs 10
wmc 17

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getResultsFromDatabase() 0 13 2
A setArguments() 0 8 1
B handle() 0 50 8
A mapResults() 0 19 3
A handleResetFlag() 0 12 3
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Commands;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Support\Facades\DB;
7
use Thinktomorrow\AssetLibrary\Models\AssetUploader;
8
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\UnreachableUrl;
9
10
class ImageToAssetMigrateCommand extends Command
11
{
12
    /**
13
     * The name and signature of the console command.
14
     *
15
     * @var string
16
     */
17
    protected $signature = 'assetlibrary:migrate-image
18
                                    {table}
19
                                    {urlcolumn}
20
                                    {linkedmodel}
21
                                    {idcolumn=id}
22
                                    {ordercolumn?}
23
                                    {localecolumn?}
24
                                    {--force}
25
                                    {--reset}
26
                                    {--dry}';
27
28
    /**
29
     * The console command description.
30
     *
31
     * @var string
32
     */
33
    protected $description = 'Import images from imageurl on a model to assets managed by assetlibrary.';
34
35
    private $table;
36
    private $urlcolumn;
37
    private $linkedmodel;
38
    private $idcolumn;
39
    private $ordercolumn;
40
    private $localecolumn;
41
42
    private $nomodel     = 0;
43
    private $unreachable = 0;
44
    private $files       = 0;
45
46
    /**
47
     * Execute the console command.
48
     *
49
     * @return mixed
50
     */
51
    public function handle()
52
    {
53
        \ini_set('memory_limit', '256M');
54
55
        $this->setArguments();
56
57
        $results        = $this->getResultsFromDatabase();
58
        $bar            = $this->output->createProgressBar(count($results));
59
        $orderedResults = $this->mapResults($results);
60
61
        $this->handleResetFlag($orderedResults);
62
63
        $this->info("\n".'Migrating images.');
64
65
        foreach ($orderedResults as $result) {
66
            foreach ($result['images'] as $line) {
67
                $bar->advance();
68
69
                if (! $line || $this->option('dry')) {
70
                    $line ?? $this->unreachable++;
71
                    $this->option('dry') ? $this->files++ : '';
72
                    continue;
73
                }
74
75
                try {
76
                    $asset = AssetUploader::uploadFromUrl(public_path($line));
77
                } catch (UnreachableUrl $ex) {
78
                    // increment the amount of unreachable files counter
79
                    $this->unreachable++;
80
81
                    continue;
82
                }
83
84
                $asset->setOrder($result['order'] ?? null)->attachToModel($result['model']);
85
86
                if ($this->option('force')) {
87
                    unlink(public_path($line));
88
                }
89
90
                // increment the amount of files migrated counter
91
                $this->files++;
92
            }
93
        }
94
95
        $bar->finish();
96
97
        $this->info('Migrating done.');
98
        $this->info('Migrated '.$this->files.' files.');
99
        $this->info('Couldn\'t reach '.$this->unreachable.' files.');
100
        $this->info('Couldn\'t find '.$this->nomodel.' model(s).');
101
    }
102
103
    private function getResultsFromDatabase()
104
    {
105
        $columns = [$this->urlcolumn, $this->idcolumn, $this->ordercolumn, $this->localecolumn];
106
107
        $builder = DB::table($this->table)->select($columns);
108
109
        if (! $this->ordercolumn) {
110
            $builder = $builder->orderBy($this->idcolumn);
111
        }
112
113
        $results = $builder->get();
114
115
        return $results;
116
    }
117
118
    private function setArguments()
119
    {
120
        $this->table        = $this->argument('table');
121
        $this->urlcolumn    = $this->argument('urlcolumn');
122
        $this->linkedmodel  = $this->argument('linkedmodel');
123
        $this->idcolumn     = $this->argument('idcolumn');
124
        $this->ordercolumn  = $this->argument('ordercolumn');
125
        $this->localecolumn = $this->argument('localecolumn');
126
    }
127
128
    private function handleResetFlag($orderedResults)
129
    {
130
        if ($this->option('reset') && ! $this->option('dry')) {
131
            $this->info('Resetting the assets on the models');
132
            $resetbar = $this->output->createProgressBar(count($orderedResults));
133
134
            $orderedResults->each(function ($entry) use ($resetbar) {
135
                $entry['model']->deleteAllAssets();
136
                $resetbar->advance();
137
            });
138
139
            $resetbar->finish();
140
        }
141
    }
142
143
    private function mapResults($results)
144
    {
145
        return $results->map(function ($result) {
146
            $formattedResults = [];
147
148
            $formattedResults['images'][] = $result->{$this->urlcolumn};
149
            $formattedResults['model']    = $this->linkedmodel::find($result->{$this->idcolumn});
150
151
            if ($this->ordercolumn) {
152
                $formattedResults['order'] = $result->{$this->ordercolumn};
153
            }
154
155
            return $formattedResults;
156
        })->reject(function ($value) {
157
            if ($result = $value['model'] == null) {
158
                $this->nomodel++;
159
            }
160
161
            return $result;
162
        });
163
    }
164
}
165