Passed
Branch 0.6 (b58a0f)
by Philippe
03:08
created

ImageToAssetMigrateCommand::mapResults()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

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