Rollback   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 95.24%

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 69
ccs 20
cts 21
cp 0.9524
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A handle() 0 9 4
A deleteLogsBySteps() 0 16 3
1
<?php
2
namespace Triadev\Leopard\Console\Commands\Mapping;
3
4
use Illuminate\Console\ConfirmableTrait;
5
use Triadev\Leopard\Contract\Repository\MappingLogRepositoryContract;
6
7
class Rollback extends BaseCommand
8
{
9
    use ConfirmableTrait;
10
    
11
    /**
12
     * The console command name.
13
     *
14
     * @var string
15
     */
16
    protected $signature = 'triadev:mapping:rollback {--steps=}';
17
    
18
    /**
19
     * The console command description.
20
     *
21
     * @var string
22
     */
23
    protected $description = 'Rollback the last migration steps.';
24
    
25
    /** @var MappingLogRepositoryContract */
26
    private $mappingLogRepository;
27
    
28
    /**
29
     * Rollback constructor.
30
     * @param MappingLogRepositoryContract $mappingLogRepository
31
     */
32 34
    public function __construct(MappingLogRepositoryContract $mappingLogRepository)
33
    {
34 34
        parent::__construct();
35
        
36 34
        $this->mappingLogRepository = $mappingLogRepository;
37 34
    }
38
    
39
    /**
40
     * Execute the console command.
41
     *
42
     * @throws \Throwable
43
     */
44 4
    public function handle()
45
    {
46 4
        if (!$this->confirmToProceed()) {
47
            return;
48
        }
49
        
50 4
        $steps = $this->option('steps') ?: $this->mappingLogRepository->reset();
51 4
        if (is_int($steps)) {
52 3
            $this->deleteLogsBySteps($steps);
53
        }
54 4
    }
55
    
56
    /**
57
     * @param int $steps
58
     * @throws \Throwable
59
     */
60 3
    private function deleteLogsBySteps(int $steps)
61
    {
62 3
        $logs = $this->mappingLogRepository->all();
63
    
64 3
        if ($steps >= count($logs)) {
65 2
            $this->mappingLogRepository->reset();
66
        }
67
    
68 3
        $logs = array_slice(
69 3
            array_reverse($logs),
70 3
            0,
71 3
            $steps
72
        );
73
    
74 3
        foreach ($logs as $log) {
75 3
            $this->mappingLogRepository->delete($log['id']);
76
        }
77 3
    }
78
}
79