-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatabaseManager.php
52 lines (42 loc) · 1.6 KB
/
DatabaseManager.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
namespace App\Services\DatabaseManager;
use App\Services\DatabaseManager\Exceptions\DatabaseManagerException;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Process\Exceptions\ProcessFailedException;
use Illuminate\Process\PendingProcess;
use Symfony\Component\Console\Output\NullOutput;
final readonly class DatabaseManager implements DatabaseManagerContract
{
public function __construct(
private Repository $config,
private PendingProcess $process,
private Kernel $artisan,
) {
}
/**
* Prepare the database for transaction processing.
*
* @throws DatabaseManagerException
*/
public function prepare(): void
{
$entry = sprintf('database.connections.%s.database', $this->config->get('app.env')); // @phpstan-ignore-line
is_string($file = $this->config->get($entry)) || throw DatabaseManagerException::invalidDatabaseLocation($entry);
try {
is_file($file) || $this->initialise($file);
} catch (ProcessFailedException $exception) {
throw DatabaseManagerException::processError($exception);
}
$this->artisan->call('migrate:fresh', ['--force' => true], new NullOutput());
}
/** @throws ProcessFailedException */
private function initialise(string $file): void
{
if ($file === ':memory:') {
return;
}
is_dir($directory = dirname($file)) || $this->process->run(sprintf('mkdir -m755 %s', $directory))->throw();
$this->process->run(sprintf('touch %s', $file))->throw();
}
}