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

HasBrowser   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
eloc 17
c 5
b 0
f 0
dl 0
loc 33
rs 10
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A browser() 0 31 5
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