LaravelRunner::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace MuhmdRaouf\LaravelParatest\Testing\Paratest;
4
5
use Illuminate\Foundation\Application;
6
use Illuminate\Support\Facades\Artisan;
7
use Illuminate\Contracts\Console\Kernel;
8
9
use ParaTest\Runners\PHPUnit\Options;
10
use ParaTest\Runners\PHPUnit\WrapperRunner;
11
use ParaTest\Runners\PHPUnit\RunnerInterface;
12
13
use Symfony\Component\Console\Output\OutputInterface;
14
15
class LaravelRunner implements RunnerInterface
16
{
17
    /**
18
     * @var WrapperRunner
19
     */
20
    private $innerRunner;
21
    /**
22
     * @var Options
23
     */
24
    private $options;
25
26
    public function __construct(Options $options, OutputInterface $output)
27
    {
28
        $this->options = $options;
29
        $this->innerRunner = new WrapperRunner($options, $output);
30
    }
31
32
    public function run(): void
33
    {
34
        $this->innerRunner->run();
35
        $this->tearDownTestDatabases();
36
    }
37
38
    public function getExitCode(): int
39
    {
40
        return $this->innerRunner->getExitCode();
41
    }
42
43
    private function tearDownTestDatabases()
44
    {
45
        $app = $this->createApp();
46
47
        $driver = $app['config']->get('database.default');
48
        $dbName = $app['config']->get("database.connections.{$driver}.database");
49
50
        for ($i = 1; $i <= $this->options->processes(); ++$i) {
51
            $this->swapTestingDatabase($app, $driver, "$dbName-$i");
52
            Artisan::call('db:drop');
53
        }
54
    }
55
56
    private function swapTestingDatabase($app, $driver, $dbName): void
57
    {
58
        // Paratest gives each process a unique TEST_TOKEN env variable.
59
        // When that's not set, we can default to 1 because it's
60
        // probably running on PHPUnit instead.
61
        $app['config']->set("database.connections.$driver.database", $dbName);
62
    }
63
64
    private function createApp(): Application
65
    {
66
        $currentProjectDirectory = getcwd();
67
68
        $app = require "$currentProjectDirectory/bootstrap/app.php";
69
70
        $app->make(Kernel::class)->bootstrap();
71
72
        return $app;
73
    }
74
}
75