Passed
Pull Request — master (#26)
by Philippe
05:12
created

ImageToAssetMigrateCommand   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 128
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 15
eloc 60
dl 0
loc 128
ccs 56
cts 56
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getResultsFromDatabase() 0 9 2
A setArguments() 0 7 1
B handle() 0 67 9
A handleResetFlag() 0 12 3
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Commands;
4
5
use Exception;
6
use Storage;
7
use Illuminate\Console\Command;
8
use Symfony\Component\Console\Helper\Table;
9
use Illuminate\Support\Facades\DB;
10
use Thinktomorrow\AssetLibrary\Models\AssetUploader;
11
use League\Flysystem\Filesystem;
12
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded;
13
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\UnreachableUrl;
14
15
class ImageToAssetMigrateCommand extends Command
16
{
17
    /**
18
     * The name and signature of the console command.
19
     *
20
     * @var string
21
     */
22
    protected $signature = 'assetlibrary:migrate-image {table} {urlcolumn} {linkedmodel} {idcolumn=id} {ordercolumn?} {--force} {--reset} {--dry}';
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 147 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
23
24
    /**
25
     * The console command description.
26
     *
27
     * @var string
28
     */
29
    protected $description = 'Import images from imageurl on a model to assets managed by assetlibrary.';
30
31
    private $table;
32
    private $urlcolumn;
33
    private $linkedmodel;
34
    private $idcolumn;
35
    private $ordercolumn;
36
37
    /**
38
     * Execute the console command.
39
     *
40
     * @return mixed
41
     */
42 10
    public function handle()
43
    {
44 10
        \ini_set('memory_limit', '256M');
45
        
46 10
        $unreachable    = 0;
47 10
        $files          = 0;
48
49 10
        $this->setArguments();
50
51 10
        $results = $this->getResultsFromDatabase();
52
53
        $orderedResults = $results->map(function ($result){
54 10
            $formattedResults['images'][] = $result->{$this->urlcolumn};
0 ignored issues
show
Comprehensibility Best Practice introduced by
$formattedResults was never initialized. Although not strictly required by PHP, it is generally a good practice to add $formattedResults = array(); before regardless.
Loading history...
55 10
            $formattedResults['model']    = $this->linkedmodel::find($result->{$this->idcolumn});
56
57 10
            if ($this->ordercolumn) {
58 1
                $formattedResults['order'] = $result->{$this->ordercolumn};
59
            }
60
61 10
            return $formattedResults;
62 10
        });
63
64 10
        $this->handleResetFlag($orderedResults);
65
        
66 10
        $this->info("\n" . 'Migrating images.');
67
        
68 10
        $bar = $this->output->createProgressBar(count($results));
69 10
        foreach ($orderedResults->toArray() as $result) {
70
71 10
            if (!$persistedModel = $result['model']) {
72 1
                continue;
73
            }
74
75 10
            foreach ($result['images'] as $line) {
76 10
                $bar->advance();
77
                
78 10
                if(!$this->option('dry')){
79
                    try {
80 9
                        $asset = AssetUploader::uploadFromUrl(public_path($line));
81 1
                    } catch (UnreachableUrl $ex) {
82
                        // increment the amount of unreachable files counter
83 1
                        $unreachable++;
84
                        
85 1
                        continue;
86
                    }
87
                    
88 9
                    $asset->attachToModel($persistedModel);
89
                    
90 9
                    if ($this->argument('ordercolumn')) {
91 1
                        $asset->setOrder($result['order']);
92
                    }
93
                    
94 9
                    if ($this->option('force')) {
95 1
                        unlink(public_path($line));
96
                    }
97
                }
98
                
99
                // increment the amount of files migrated counter
100 10
                $files++;
101
            }
102
        }
103
       
104 10
        $bar->finish();
105
106 10
        $this->info('Migrating done.');
107 10
        $this->info('Migrated '. $files . ' files.');
108 10
        $this->info('Couldn\'t reach '. $unreachable . ' files.');
109 10
    }
110
111 10
    private function getResultsFromDatabase()
112
    {
113 10
        if ($this->ordercolumn) {
114 1
            $results = DB::table($this->table)->select($this->urlcolumn, $this->idcolumn, $this->ordercolumn)->get();
115
        } else {
116 9
            $results = DB::table($this->table)->select($this->urlcolumn, $this->idcolumn)->orderBy($this->idcolumn)->get();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
117
        }
118
119 10
        return $results;
120
    }
121
122 10
    private function setArguments()
123
    {
124 10
        $this->table       = $this->argument('table');
125 10
        $this->urlcolumn   = $this->argument('urlcolumn');
126 10
        $this->linkedmodel = $this->argument('linkedmodel');
127 10
        $this->idcolumn    = $this->argument('idcolumn');
128 10
        $this->ordercolumn = $this->argument('ordercolumn');
129 10
    }
130
131 10
    private function handleResetFlag($orderedResults)
132
    {
133 10
        if ($this->option('reset') && !$this->option('dry')) {
134 1
            $this->info('Resetting the assets on the models');
135 1
            $resetbar = $this->output->createProgressBar(count($orderedResults));
136
            
137
            $orderedResults->each(function ($entry, $key) use ($resetbar) {
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

137
            $orderedResults->each(function ($entry, /** @scrutinizer ignore-unused */ $key) use ($resetbar) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
138 1
                optional($entry['model'])->deleteAllAssets();
139 1
                $resetbar->advance();
140 1
            });
141
            
142 1
            $resetbar->finish();
143
        }
144 10
    }
145
}
146