Passed
Pull Request — master (#26)
by Philippe
08:53 queued 03:20
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 Symfony\Component\Console\Helper\Table;
8
use Thinktomorrow\AssetLibrary\Models\AssetUploader;
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 {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...
19
20
    /**
21
     * The console command description.
22
     *
23
     * @var string
24
     */
25
    protected $description = 'Import images from imageurl on a model to assets managed by assetlibrary.';
26
27
    private $table;
28
    private $urlcolumn;
29
    private $linkedmodel;
30
    private $idcolumn;
31
    private $ordercolumn;
32
33
    /**
34
     * Execute the console command.
35
     *
36
     * @return mixed
37
     */
38 10
    public function handle()
39
    {
40 10
        \ini_set('memory_limit', '256M');
41
42 10
        $unreachable    = 0;
43 10
        $files          = 0;
44
45 10
        $this->setArguments();
46
47 10
        $results = $this->getResultsFromDatabase();
48
49
        $orderedResults = $results->map(function ($result) {
50 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...
51 10
            $formattedResults['model']    = $this->linkedmodel::find($result->{$this->idcolumn});
52
53 10
            if ($this->ordercolumn) {
54 1
                $formattedResults['order'] = $result->{$this->ordercolumn};
55
            }
56
57 10
            return $formattedResults;
58 10
        });
59
60 10
        $this->handleResetFlag($orderedResults);
61
62 10
        $this->info("\n".'Migrating images.');
63
64 10
        $bar = $this->output->createProgressBar(count($results));
65 10
        foreach ($orderedResults->toArray() as $result) {
66 10
            if (! $persistedModel = $result['model']) {
67 1
                continue;
68
            }
69
70 10
            foreach ($result['images'] as $line) {
71 10
                $bar->advance();
72
73 10
                if (! $this->option('dry')) {
74
                    try {
75 9
                        $asset = AssetUploader::uploadFromUrl(public_path($line));
76 1
                    } catch (UnreachableUrl $ex) {
77
                        // increment the amount of unreachable files counter
78 1
                        $unreachable++;
79
80 1
                        continue;
81
                    }
82
83 9
                    $asset->attachToModel($persistedModel);
84
85 9
                    if ($this->argument('ordercolumn')) {
86 1
                        $asset->setOrder($result['order']);
87
                    }
88
89 9
                    if ($this->option('force')) {
90 1
                        unlink(public_path($line));
91
                    }
92
                }
93
94
                // increment the amount of files migrated counter
95 10
                $files++;
96
            }
97
        }
98
99 10
        $bar->finish();
100
101 10
        $this->info('Migrating done.');
102 10
        $this->info('Migrated '.$files.' files.');
103 10
        $this->info('Couldn\'t reach '.$unreachable.' files.');
104 10
    }
105
106 10
    private function getResultsFromDatabase()
107
    {
108 10
        if ($this->ordercolumn) {
109 1
            $results = DB::table($this->table)->select($this->urlcolumn, $this->idcolumn, $this->ordercolumn)->get();
110
        } else {
111 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...
112
        }
113
114 10
        return $results;
115
    }
116
117 10
    private function setArguments()
118
    {
119 10
        $this->table       = $this->argument('table');
120 10
        $this->urlcolumn   = $this->argument('urlcolumn');
121 10
        $this->linkedmodel = $this->argument('linkedmodel');
122 10
        $this->idcolumn    = $this->argument('idcolumn');
123 10
        $this->ordercolumn = $this->argument('ordercolumn');
124 10
    }
125
126 10
    private function handleResetFlag($orderedResults)
127
    {
128 10
        if ($this->option('reset') && ! $this->option('dry')) {
129 1
            $this->info('Resetting the assets on the models');
130 1
            $resetbar = $this->output->createProgressBar(count($orderedResults));
131
132
            $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

132
            $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...
133 1
                optional($entry['model'])->deleteAllAssets();
134 1
                $resetbar->advance();
135 1
            });
136
137 1
            $resetbar->finish();
138
        }
139 10
    }
140
}
141