Passed
Push — 0.6 ( b34ac2...2a9301 )
by Philippe
04:04
created

ImageToAssetMigrateCommand::processLines()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6

Importance

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