Passed
Branch master (8cb5b2)
by Christopher
04:37
created

Rollback::deleteLogsBySteps()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 4
nop 1
dl 0
loc 16
ccs 10
cts 10
cp 1
crap 3
rs 10
c 0
b 0
f 0
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 132
    public function __construct(MappingLogRepositoryContract $mappingLogRepository)
33
    {
34 132
        parent::__construct();
35
        
36 132
        $this->mappingLogRepository = $mappingLogRepository;
37 132
    }
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