Passed
Pull Request — master (#24)
by Philippe
03:23
created

ImageToAssetMigrateCommand   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 97
Duplicated Lines 0 %

Test Coverage

Coverage 95.35%

Importance

Changes 0
Metric Value
wmc 8
eloc 47
dl 0
loc 97
ccs 41
cts 43
cp 0.9535
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B handle() 0 76 8
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}';
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 139 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
    /**
32
     * Execute the console command.
33
     *
34
     * @return mixed
35
     */
36 5
    public function handle()
37
    {
38 5
        \ini_set('memory_limit', '256M');
39
        
40 5
        $tableName      = $this->argument('table');
41 5
        $imageUrlColumn = $this->argument('urlcolumn');
42 5
        $modelIdColumn  = $this->argument('idcolumn');
43 5
        $ordercolumn    = $this->argument('ordercolumn');
44 5
        $model          = $this->argument('linkedmodel');
45 5
        $unreachable    = 0;
46 5
        $files          = 0;
47
48 5
        if($ordercolumn){
49
            $results = DB::table($tableName)->select($imageUrlColumn, $modelIdColumn, $ordercolumn)->get();
0 ignored issues
show
Bug introduced by
It seems like $tableName can also be of type array; however, parameter $table of Illuminate\Support\Facades\DB::table() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

49
            $results = DB::table(/** @scrutinizer ignore-type */ $tableName)->select($imageUrlColumn, $modelIdColumn, $ordercolumn)->get();
Loading history...
50
        }else{
51 5
            $results = DB::table($tableName)->select($imageUrlColumn, $modelIdColumn)->orderBy($modelIdColumn)->get();
0 ignored issues
show
Bug introduced by
It seems like $modelIdColumn can also be of type array; however, parameter $column of Illuminate\Database\Query\Builder::orderBy() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

51
            $results = DB::table($tableName)->select($imageUrlColumn, $modelIdColumn)->orderBy(/** @scrutinizer ignore-type */ $modelIdColumn)->get();
Loading history...
52
        }
53
54 5
        $orderedResults = [];
55
        $results->each(function($result) use($modelIdColumn, $results, &$orderedResults, $imageUrlColumn){
0 ignored issues
show
Unused Code introduced by
The import $results is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
56 5
            $orderedResults[$result->$modelIdColumn][] = $result->$imageUrlColumn;
57 5
        });
58
59 5
        $orderedResults = collect($orderedResults);
60
61 5
        if($this->option('reset')){
62 1
            $this->info('Resetting the asserts on the models');
63 1
            $resetbar = $this->output->createProgressBar(count($orderedResults));
64
            
65
            $orderedResults->each(function($entry, $key) use($model, $resetbar){
66 1
                optional($model::find($key))->deleteAllAssets();
67 1
                $resetbar->advance();
68 1
            });
69
            
70 1
            $resetbar->finish();
71
        }
72
        
73
74 5
        $bar = $this->output->createProgressBar(count($results));
75
        
76 5
        $this->info("\n" . 'Migrating images.');
77 5
        foreach($orderedResults as $key => $result)
78
        {
79 5
            $persistedModel = $model::find($key);
80 5
            if(!$persistedModel){
81
                continue;
82
            }
83
84 5
            foreach($result as $line){
85 5
                $bar->advance();
86
                
87
                try{
88 5
                    $asset = AssetUploader::uploadFromUrl(public_path($line));
89 1
                }catch(UnreachableUrl $ex){
90
                    // increment the amount of unreachable files counter
91 1
                    $unreachable++;
92
                    
93 1
                    continue;
94
                }
95
                
96 5
                $asset->attachToModel($persistedModel);
97
                
98 5
                if($this->option('force')){
99 1
                    unlink(public_path($line));
100
                }
101
    
102
                // increment the amount of files migrated counter
103 5
                $files++;
104
            }
105
        }
106
       
107 5
        $bar->finish();
108
109 5
        $this->info('Migrating done.');
110 5
        $this->info('Migrated '. $files . ' files.');
111 5
        $this->info('Couldn\'t reach '. $unreachable . ' files.');
112 5
    }
113
}
114