Completed
Pull Request — dev (#27)
by
unknown
14:14
created

AbstractController::getClient()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
1
<?php
2
3
namespace Tests\AppBundle\Controller;
4
5
use Doctrine\ORM\EntityManager;
6
use Symfony\Bundle\FrameworkBundle\Client;
7
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
8
use Symfony\Component\DependencyInjection\ContainerInterface;
9
10
abstract class AbstractController extends WebTestCase
11
{
12
    protected static $options = [
13
        'environment' => 'test',
14
        'debug' => true,
15
    ];
16
    /**
17
     * @var ContainerInterface
18
     */
19
    protected $container;
20
    /**
21
     * @var EntityManager
22
     */
23
    protected $em;
24
    /**
25
     * @var Client
26
     */
27
    protected $client;
28
    /**
29
     * {@inheritDoc}
30
     */
31
    public function __construct($name = null, array $data = [], $dataName = '')
32
    {
33
        self::bootKernel(self::$options);
34
35
        $this->container = static::$kernel->getContainer();
36
37
        $this->em = static::$kernel->getContainer()->get('doctrine')->getManager();
38
        parent::__construct($name, $data, $dataName);
39
    }
40
41
42
    /**
43
     * @param string $path
44
     * @param string $method
45
     * @param int $expectedStatusCode
46
     *
47
     * @return \Symfony\Component\DomCrawler\Crawler
48
     */
49
    protected function request($path, $method = 'GET', $expectedStatusCode = 200)
50
    {
51
        $client = $this->getClient();
52
        $crawler = $client->request($method, $path);
53
        self::assertEquals(
54
            $expectedStatusCode,
55
            $client->getResponse()->getStatusCode(),
56
            sprintf(
57
                'We expected that uri "%s" will return %s status code, but had received %d',
58
                $path,
59
                $expectedStatusCode,
60
                $client->getResponse()->getStatusCode()
61
            )
62
        );
63
        return $crawler;
64
    }
65
66
    /**
67
     * @param array $options
68
     * @param array $server
69
     * @return Client
70
     */
71
    protected function getClient(array $options = array(), array $server = array())
72
    {
73
        if (!$this->client) {
74
            $this->client = static::createClient($options, $server);
75
        }
76
        return $this->client;
77
    }
78
79
    protected function logIn($username = '[email protected]', $password = 'admin')
80
    {
81
        $client = $this->getClient();
82
        $crawler = $client->request('GET', '/login');
83
        $form = $crawler->selectButton('Login')->form();
84
        $client->submit($form, ['_username' => $username, '_password' => $password]);
85
        return $client;
86
    }
87
}
88