Completed
Pull Request — master (#38)
by Philippe
17:02 queued 07:30
created

ImageToAssetMigrateCommand::handleResetFlag()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 12
ccs 8
cts 8
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 1
crap 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 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 12
    public function handle()
53
    {
54 12
        \ini_set('memory_limit', '256M');
55
56 12
        $this->setArguments();
57
58 12
        $results        = $this->getResultsFromDatabase();
59 12
        $bar            = $this->output->createProgressBar(count($results));
60 12
        $orderedResults = $this->mapResults($results);
61
62 12
        $this->handleResetFlag($orderedResults);
63
64 12
        $this->info("\n".'Migrating images.');
65
66 12
        foreach ($orderedResults as $result) {
67 12
            foreach ($result['images'] as $line) {
68 12
                $bar->advance();
69
70 12
                if (! $line || $this->option('dry')) {
71 1
                    $line ?? $this->unreachable++;
72 1
                    $this->option('dry') ? $this->files++ : '';
73 1
                    continue;
74
                }
75
76
                try {
77 11
                    $asset = AssetUploader::uploadFromUrl(public_path($line));
78 1
                } catch (UnreachableUrl $ex) {
79
                    // increment the amount of unreachable files counter
80 1
                    $this->unreachable++;
81
82 1
                    continue;
83
                }
84
85 11
                $asset->setOrder($result['order'] ?? null)->attachToModel($result['model']);
86
87 11
                if ($this->option('force')) {
88 1
                    unlink(public_path($line));
89
                }
90
91
                // increment the amount of files migrated counter
92 12
                $this->files++;
93
            }
94
        }
95
96 12
        $bar->finish();
97
98 12
        $this->info('Migrating done.');
99 12
        $this->info('Migrated '.$this->files.' files.');
100 12
        $this->info('Couldn\'t reach '.$this->unreachable.' files.');
101 12
        $this->info('Couldn\'t find '.$this->nomodel.' model(s).');
102 12
    }
103
104 12
    private function getResultsFromDatabase()
105
    {
106 12
        $columns = [$this->urlcolumn, $this->idcolumn, $this->ordercolumn, $this->localecolumn];
107
108 12
        $builder = DB::table($this->table)->select($columns);
109
110 12
        if (! $this->ordercolumn) {
111 11
            $builder = $builder->orderBy($this->idcolumn);
112
        }
113
114 12
        $results = $builder->get();
115
116 12
        return $results;
117
    }
118
119 12
    private function setArguments()
120
    {
121 12
        $this->table        = $this->argument('table');
122 12
        $this->urlcolumn    = $this->argument('urlcolumn');
123 12
        $this->linkedmodel  = $this->argument('linkedmodel');
124 12
        $this->idcolumn     = $this->argument('idcolumn');
125 12
        $this->ordercolumn  = $this->argument('ordercolumn');
126 12
        $this->localecolumn = $this->argument('localecolumn');
127 12
    }
128
129 12
    private function handleResetFlag($orderedResults)
130
    {
131 12
        if ($this->option('reset') && ! $this->option('dry')) {
132 1
            $this->info('Resetting the assets on the models');
133 1
            $resetbar = $this->output->createProgressBar(count($orderedResults));
134
135
            $orderedResults->each(function ($entry) use ($resetbar) {
136 1
                app(DeleteAsset::class)->deleteAll($entry['model']);
137 1
                $resetbar->advance();
138 1
            });
139
140 1
            $resetbar->finish();
141
        }
142 12
    }
143
144 12
    private function mapResults($results)
145
    {
146
        return $results->map(function ($result) {
147 12
            $formattedResults = [];
148
149 12
            $formattedResults['images'][] = $result->{$this->urlcolumn};
150 12
            $formattedResults['model']    = $this->linkedmodel::find($result->{$this->idcolumn});
151
152 12
            if ($this->ordercolumn) {
153 1
                $formattedResults['order'] = $result->{$this->ordercolumn};
154
            }
155
156 12
            return $formattedResults;
157
        })->reject(function ($value) {
158 12
            if ($result = $value['model'] == null) {
159 1
                $this->nomodel++;
160
            }
161
162 12
            return $result;
163 12
        });
164
    }
165
}
166