1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LaravelSynchronize\Listeners; |
4
|
|
|
|
5
|
|
|
use SplFileInfo; |
6
|
|
|
use Illuminate\Support\Facades\DB; |
7
|
|
|
use Illuminate\Support\Facades\Config; |
8
|
|
|
use Illuminate\Database\Events\MigrationStarted; |
9
|
|
|
use LaravelSynchronize\Console\Synchronizer\Synchronizer; |
10
|
|
|
|
11
|
|
|
class MigrationStartedEventListener |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* The Synchronizer instance. |
15
|
|
|
* |
16
|
|
|
* @var \LaravelSynchronize\Console\Synchronizer\Synchronizer |
17
|
|
|
*/ |
18
|
|
|
protected $synchronizer; |
19
|
|
|
|
20
|
|
|
public function __construct(Synchronizer $synchronizer) |
21
|
|
|
{ |
22
|
|
|
$this->synchronizer = $synchronizer; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Handle the event. |
27
|
|
|
* |
28
|
|
|
* @todo use MigrationsStarted event to collect synchronization files |
29
|
|
|
* |
30
|
|
|
* @param MigrationStarted $migrationStarted |
31
|
|
|
* |
32
|
|
|
* @return void |
33
|
|
|
* |
34
|
|
|
* @author Ramon Bakker <[email protected]> |
35
|
|
|
* @version 1.0.0 |
36
|
|
|
*/ |
37
|
|
|
public function handle(MigrationStarted $migrationStarted) |
38
|
|
|
{ |
39
|
|
|
// Synchronizations should execute before going up |
40
|
|
|
if ($migrationStarted->method !== 'up') { |
41
|
|
|
return; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$class = get_class($migrationStarted->migration) . 'Synchronization'; |
45
|
|
|
$files = $this->synchronizer->getSynchronizations(); |
46
|
|
|
|
47
|
|
|
$fileNames = $files->map(function ($file) { |
48
|
|
|
return $file->getFileName(); |
49
|
|
|
}); |
50
|
|
|
|
51
|
|
|
$handledFiles = DB::table(Config::get('synchronizer.table'))->pluck('synchronization'); |
52
|
|
|
$unHandledFiles = $fileNames->diff($handledFiles); |
53
|
|
|
|
54
|
|
|
$filesToHandle = $files->filter(function ($file) use ($unHandledFiles, $class) { |
55
|
|
|
return $unHandledFiles->contains($file->getFileName()) |
56
|
|
|
&& (!$class || ($class === $this->getClassName($file))); |
57
|
|
|
}); |
58
|
|
|
|
59
|
|
|
if ($filesToHandle->isEmpty()) { |
60
|
|
|
echo "No synchronization found for {$class}\n"; |
61
|
|
|
|
62
|
|
|
return; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$filesToHandle->each(function ($file) { |
66
|
|
|
echo 'Synchronizing: ' . $file->getFileName() . "\n"; |
67
|
|
|
|
68
|
|
|
$this->synchronizer->run($file, 'up'); |
69
|
|
|
|
70
|
|
|
echo 'Synchronized: ' . $file->getFileName() . "\n"; |
71
|
|
|
}); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Get class name for file |
76
|
|
|
* |
77
|
|
|
* @param SplFileInfo $file |
78
|
|
|
* |
79
|
|
|
* @return string |
80
|
|
|
*/ |
81
|
|
|
private function getClassName(SplFileInfo $file): string |
82
|
|
|
{ |
83
|
|
|
return $this->synchronizer->getClassName( |
84
|
|
|
$this->synchronizer->getSynchronizationName($file->getFilename()) |
85
|
|
|
); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|