Passed
Pull Request — 1.x (#23)
by Wouter
02:16
created

HasBrowser::browser()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 31
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 16
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 31
rs 9.4222
1
<?php
2
3
namespace Zenstruck\Browser\Test;
4
5
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
6
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
7
use Zenstruck\Browser\KernelBrowser;
8
9
/**
10
 * @author Kevin Bond <[email protected]>
11
 */
12
trait HasBrowser
13
{
14
    public function browser(array $options = []): KernelBrowser
15
    {
16
        if (!$this instanceof KernelTestCase) {
17
            throw new \RuntimeException(\sprintf('The "%s" method can only be used on TestCases that extend "%s".', __METHOD__, KernelTestCase::class));
18
        }
19
20
        $class = $_SERVER['KERNEL_BROWSER_CLASS'] ?? KernelBrowser::class;
21
22
        if (!\is_a($class, KernelBrowser::class, true)) {
23
            throw new \RuntimeException(\sprintf('"KERNEL_BROWSER_CLASS" env variable must reference a class that extends %s.', KernelBrowser::class));
24
        }
25
26
        if ($this instanceof WebTestCase) {
27
            static::ensureKernelShutdown();
28
29
            $browser = new $class(static::createClient($options));
30
        } else {
31
            // reboot kernel before starting browser
32
            static::bootKernel($options);
33
34
            if (!static::$container->has('test.client')) {
0 ignored issues
show
Bug introduced by
The property container is declared protected in Symfony\Bundle\FrameworkBundle\Test\KernelTestCase and cannot be accessed from this context.
Loading history...
35
                throw new \RuntimeException('The Symfony test client is not enabled.');
36
            }
37
38
            $browser = new $class(static::$container->get('test.client'));
39
        }
40
41
        BrowserExtension::registerBrowser($browser);
42
43
        return $browser
44
            ->setSourceDir($_SERVER['BROWSER_SOURCE_DIR'] ?? './var/browser/source')
45
        ;
46
    }
47
}
48