Passed
Pull Request — master (#9)
by
unknown
10:07
created

MigrationEndedEventListener::handle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 29
rs 9.7666
cc 3
nc 3
nop 1
1
<?php
2
3
namespace LaravelSynchronize\Listeners;
4
5
use Illuminate\Database\Events\MigrationEnded;
6
use LaravelSynchronize\Console\Synchronizer\Synchronizer;
7
use LaravelSynchronize\Console\Synchronizer\SynchronizerRepository;
8
9
class MigrationEndedEventListener
10
{
11
    /**
12
     * The Synchronizer instance.
13
     *
14
     * @var \LaravelSynchronize\Console\Synchronizer\Synchronizer
15
     */
16
    protected $synchronizer;
17
18
    /**
19
     * @var \LaravelSynchronize\Console\Synchronizer\SynchronizerRepository $synchronizerRepository
20
     */
21
    protected $synchronizerRepository;
22
23
    public function __construct(Synchronizer $synchronizer, SynchronizerRepository $synchronizerRepository)
24
    {
25
        $this->synchronizer = $synchronizer;
26
        $this->synchronizerRepository = $synchronizerRepository;
27
    }
28
29
    /**
30
     * Handle the event.
31
     *
32
     * @todo use MigrationsStarted event to collect synchronizations
33
     *
34
     * @param MigrationEnded $migrationEnded
35
     *
36
     * @return void
37
     *
38
     * @author Ramon Bakker <[email protected]>
39
     * @version 1.0.0
40
     */
41
    public function handle(MigrationEnded $migrationEnded)
42
    {
43
        // Synchronizations should execute after going down
44
        if ($migrationEnded->method !== 'down') {
45
            return;
46
        }
47
48
        $class = get_class($migrationEnded->migration) . 'Synchronization';
49
        $files = $this->synchronizer->getSynchronizations();
50
51
        $handledFiles = collect($this->synchronizerRepository->getLast())
52
            ->pluck('synchronization');
53
54
        $filesToHandle = $files->filter(function ($file) use ($handledFiles) {
55
            return $handledFiles->contains($file->getFileName());
56
        });
57
58
        if ($filesToHandle->isEmpty()) {
59
            echo "No synchronization found for {$class}\n";
60
61
            return;
62
        }
63
64
        $filesToHandle->each(function ($file) {
65
            echo 'Rolling back synchronization: ' . $file->getFileName() . "\n";
66
67
            $this->synchronizer->run($file, 'down');
68
69
            echo 'Rolled back synchronization: ' . $file->getFileName() . "\n";
70
        });
71
    }
72
}
73