Completed
Push — refactor-loadFixtures ( 5772b7...085b46 )
by Alexis
13:50 queued 05:12
created

WebTestCase::cleanDatabase()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
ccs 12
cts 12
cp 1
rs 9.2
cc 4
eloc 9
nc 8
nop 2
crap 4
1
<?php
2
3
/*
4
 * This file is part of the Liip/FunctionalTestBundle
5
 *
6
 * (c) Lukas Kahwe Smith <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Liip\FunctionalTestBundle\Test;
13
14
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
15
use Symfony\Bundle\FrameworkBundle\Console\Application;
16
use Symfony\Bundle\FrameworkBundle\Client;
17
use Symfony\Component\Console\Input\ArrayInput;
18
use Symfony\Component\Console\Output\OutputInterface;
19
use Symfony\Component\Console\Output\StreamOutput;
20
use Symfony\Component\DomCrawler\Crawler;
21
use Symfony\Component\BrowserKit\Cookie;
22
use Symfony\Component\HttpKernel\Kernel;
23
use Symfony\Component\HttpFoundation\Response;
24
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
25
use Symfony\Component\Security\Core\User\UserInterface;
26
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
27
use Symfony\Component\DependencyInjection\ContainerInterface;
28
use Symfony\Component\HttpFoundation\Session\Session;
29
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
30
use Symfony\Bridge\Doctrine\ManagerRegistry;
31
use Symfony\Bundle\DoctrineFixturesBundle\Common\DataFixtures\Loader;
32
use Doctrine\Common\Persistence\ObjectManager;
33
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
34
use Doctrine\Common\DataFixtures\Executor\AbstractExecutor;
35
use Doctrine\Common\DataFixtures\ProxyReferenceRepository;
36
use Doctrine\DBAL\Connection;
37
use Doctrine\DBAL\Driver\PDOSqlite\Driver as SqliteDriver;
38
use Doctrine\DBAL\Platforms\MySqlPlatform;
39
use Doctrine\ORM\EntityManager;
40
use Doctrine\ORM\Tools\SchemaTool;
41
use Nelmio\Alice\Fixtures;
42
43
/**
44
 * @author Lea Haensenberger
45
 * @author Lukas Kahwe Smith <[email protected]>
46
 * @author Benjamin Eberlei <[email protected]>
47
 */
48
abstract class WebTestCase extends BaseWebTestCase
49
{
50
    protected $environment = 'test';
51
    protected $containers;
52
    protected $kernelDir;
53
    // 5 * 1024 * 1024 KB
54
    protected $maxMemory = 5242880;
55
56
    // RUN COMMAND
57
    protected $verbosityLevel;
58
    protected $decorated;
59
60
    /**
61
     * @var array
62
     */
63
    private $firewallLogins = array();
64
65
    /**
66
     * @var array
67
     */
68
    private static $cachedMetadatas = array();
69
70 1
    protected static function getKernelClass()
0 ignored issues
show
Coding Style introduced by
getKernelClass uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
71
    {
72 1
        $dir = isset($_SERVER['KERNEL_DIR']) ? $_SERVER['KERNEL_DIR'] : self::getPhpUnitXmlDir();
73
74 1
        list($appname) = explode('\\', get_called_class());
75
76 1
        $class = $appname.'Kernel';
77 1
        $file = $dir.'/'.strtolower($appname).'/'.$class.'.php';
78 1
        if (!file_exists($file)) {
79 1
            return parent::getKernelClass();
80
        }
81
        require_once $file;
82
83
        return $class;
84
    }
85
86
    /**
87
     * Creates a mock object of a service identified by its id.
88
     *
89
     * @param string $id
90
     *
91
     * @return \PHPUnit_Framework_MockObject_MockBuilder
92
     */
93 2
    protected function getServiceMockBuilder($id)
94
    {
95 2
        $service = $this->getContainer()->get($id);
96
        $class = get_class($service);
97
98
        return $this->getMockBuilder($class)->disableOriginalConstructor();
99
    }
100
101
    /**
102
     * Builds up the environment to run the given command.
103
     *
104
     * @param string $name
105
     * @param array  $params
106
     * @param bool   $reuseKernel
107
     *
108
     * @return string
109
     */
110 12
    protected function runCommand($name, array $params = array(), $reuseKernel = false)
111
    {
112 12
        array_unshift($params, $name);
113
114 12
        if (!$reuseKernel) {
115 12
            if (null !== static::$kernel) {
116 9
                static::$kernel->shutdown();
117 9
            }
118
119 12
            $kernel = static::$kernel = $this->createKernel(array('environment' => $this->environment));
120 12
            $kernel->boot();
121 12
        } else {
122 2
            $kernel = $this->getContainer()->get('kernel');
123
        }
124
125 12
        $application = new Application($kernel);
126 12
        $application->setAutoExit(false);
127
128
        // @codeCoverageIgnoreStart
129
        if ('20301' === Kernel::VERSION_ID) {
130
            $params = $this->configureVerbosityForSymfony20301($params);
131
        }
132
        // @codeCoverageIgnoreEnd
133
134 12
        $input = new ArrayInput($params);
135 12
        $input->setInteractive(false);
136
137 12
        $fp = fopen('php://temp/maxmemory:'.$this->maxMemory, 'r+');
138 12
        $output = new StreamOutput($fp, $this->getVerbosityLevel(), $this->getDecorated());
139
140 11
        $application->run($input, $output);
141
142 11
        rewind($fp);
143
144 11
        return stream_get_contents($fp);
145
    }
146
147
    /**
148
     * Retrieves the output verbosity level.
149
     *
150
     * @see Symfony\Component\Console\Output\OutputInterface for available levels
151
     *
152
     * @return int
153
     *
154
     * @throws \OutOfBoundsException If the set value isn't accepted
155
     */
156 12
    protected function getVerbosityLevel()
157
    {
158
        // If `null`, is not yet set
159 12
        if (null === $this->verbosityLevel) {
160
            // Set the global verbosity level that is set as NORMAL by the TreeBuilder in Configuration
161 6
            $level = strtoupper($this->getContainer()->getParameter('liip_functional_test.command_verbosity'));
162 6
            $verbosity = '\Symfony\Component\Console\Output\StreamOutput::VERBOSITY_'.$level;
163
164 6
            $this->verbosityLevel = constant($verbosity);
165 6
        }
166
167
        // If string, it is set by the developer, so check that the value is an accepted one
168 12
        if (is_string($this->verbosityLevel)) {
169 6
            $level = strtoupper($this->verbosityLevel);
170 6
            $verbosity = '\Symfony\Component\Console\Output\StreamOutput::VERBOSITY_'.$level;
171
172 6
            if (!defined($verbosity)) {
173 1
                throw new \OutOfBoundsException(
174 1
                    sprintf('The set value "%s" for verbosityLevel is not valid. Accepted are: "quiet", "normal", "verbose", "very_verbose" and "debug".', $level)
175 1
                    );
176
            }
177
178 5
            $this->verbosityLevel = constant($verbosity);
179 5
        }
180
181 11
        return $this->verbosityLevel;
182
    }
183
184
    /**
185
     * In Symfony 2.3.1 the verbosity level has to be set through {Symfony\Component\Console\Input\ArrayInput} and not
186
     * in {Symfony\Component\Console\Output\OutputInterface}.
187
     *
188
     * This method builds $params to be passed to {Symfony\Component\Console\Input\ArrayInput}.
189
     *
190
     * @codeCoverageIgnore
191
     *
192
     * @param array $params
193
     *
194
     * @return array
195
     */
196
    private function configureVerbosityForSymfony20301(array $params)
197
    {
198
        switch ($this->getVerbosityLevel()) {
199
            case OutputInterface::VERBOSITY_QUIET:
200
                $params['-q'] = '-q';
201
                break;
202
203
            case OutputInterface::VERBOSITY_VERBOSE:
204
                $params['-v'] = '';
205
                break;
206
207
            case OutputInterface::VERBOSITY_VERY_VERBOSE:
208
                $params['-vv'] = '';
209
                break;
210
211
            case OutputInterface::VERBOSITY_DEBUG:
212
                $params['-vvv'] = '';
213
                break;
214
        }
215
216
        return $params;
217
    }
218
219 6
    public function setVerbosityLevel($level)
220
    {
221 6
        $this->verbosityLevel = $level;
222 6
    }
223
224
    /**
225
     * Retrieves the flag indicating if the output should be decorated or not.
226
     *
227
     * @return bool
228
     */
229 11
    protected function getDecorated()
230
    {
231 11
        if (null === $this->decorated) {
232
            // Set the global decoration flag that is set to `true` by the TreeBuilder in Configuration
233 5
            $this->decorated = $this->getContainer()->getParameter('liip_functional_test.command_decoration');
234 5
        }
235
236
        // Check the local decorated flag
237 11
        if (false === is_bool($this->decorated)) {
238
            throw new \OutOfBoundsException(
239
                sprintf('`WebTestCase::decorated` has to be `bool`. "%s" given.', gettype($this->decorated))
240
            );
241
        }
242
243 11
        return $this->decorated;
244
    }
245
246 6
    public function isDecorated($decorated)
247
    {
248 6
        $this->decorated = $decorated;
249 6
    }
250
251
    /**
252
     * Get an instance of the dependency injection container.
253
     * (this creates a kernel *without* parameters).
254
     *
255
     * @return ContainerInterface
256
     */
257 34
    protected function getContainer()
0 ignored issues
show
Coding Style introduced by
getContainer uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
258
    {
259 34
        if (!empty($this->kernelDir)) {
260
            $tmpKernelDir = isset($_SERVER['KERNEL_DIR']) ? $_SERVER['KERNEL_DIR'] : null;
261
            $_SERVER['KERNEL_DIR'] = getcwd().$this->kernelDir;
262
        }
263
264 34
        $cacheKey = $this->kernelDir.'|'.$this->environment;
265 34
        if (empty($this->containers[$cacheKey])) {
266
            $options = array(
267 34
                'environment' => $this->environment,
268 34
            );
269 34
            $kernel = $this->createKernel($options);
270 34
            $kernel->boot();
271
272 34
            $this->containers[$cacheKey] = $kernel->getContainer();
273 34
        }
274
275 34
        if (isset($tmpKernelDir)) {
276
            $_SERVER['KERNEL_DIR'] = $tmpKernelDir;
277
        }
278
279 34
        return $this->containers[$cacheKey];
280
    }
281
282
    /**
283
     * @param string $type
284
     *
285
     * @return string
286
     */
287 26
    private function getExecutorClass($type)
288
    {
289 26
        return 'PHPCR' === $type && class_exists('Doctrine\Bundle\PHPCRBundle\DataFixtures\PHPCRExecutor')
290 26
            ? 'Doctrine\Bundle\PHPCRBundle\DataFixtures\PHPCRExecutor'
291 26
            : 'Doctrine\\Common\\DataFixtures\\Executor\\'.$type.'Executor';
292
    }
293
294
    /**
295
     * Get file path of the SQLite database.
296
     *
297
     * @param Connection $connection
298
     *
299
     * @return string $name
300
     */
301 21
    private function getNameParameter(Connection $connection)
302
    {
303 21
        $params = $connection->getParams();
304
305 21
        if (isset($params['master'])) {
306
            $params = $params['master'];
307
        }
308
309 21
        $name = isset($params['path']) ? $params['path'] : (isset($params['dbname']) ? $params['dbname'] : false);
310
311 21
        if (!$name) {
312
            throw new \InvalidArgumentException("Connection does not contain a 'path' or 'dbname' parameter and cannot be dropped.");
313
        }
314
315 21
        return $name;
316
    }
317
318
    /**
319
     * Purge SQLite database.
320
     *
321
     * @param ObjectManager $om
322
     * @param string        $omName The name of object manager to use
323
     */
324 21
    private function getCachedMetadatas(ObjectManager $om, $omName)
325
    {
326 21
        if (!isset(self::$cachedMetadatas[$omName])) {
327 6
            self::$cachedMetadatas[$omName] = $om->getMetadataFactory()->getAllMetadata();
328
            usort(self::$cachedMetadatas[$omName], function ($a, $b) { return strcmp($a->name, $b->name); });
329 6
        }
330
331 21
        return self::$cachedMetadatas[$omName];
332
    }
333
334
    /**
335
     * This function finds the time when the data blocks of a class definition
336
     * file were being written to, that is, the time when the content of the
337
     * file was changed.
338
     *
339
     * @param string $class The fully qualified class name of the fixture class to
340
     *                      check modification date on.
341
     *
342
     * @return \DateTime|null
343
     */
344 2
    protected function getFixtureLastModified($class)
345
    {
346 2
        $lastModifiedDateTime = null;
347
348 2
        $reflClass = new \ReflectionClass($class);
349 2
        $classFileName = $reflClass->getFileName();
350
351 2
        if (file_exists($classFileName)) {
352 2
            $lastModifiedDateTime = new \DateTime();
353 2
            $lastModifiedDateTime->setTimestamp(filemtime($classFileName));
354 2
        }
355
356 2
        return $lastModifiedDateTime;
357
    }
358
359
    /**
360
     * Determine if the Fixtures that define a database backup have been
361
     * modified since the backup was made.
362
     *
363
     * @param array  $classNames The fixture classnames to check
364
     * @param string $backup     The fixture backup SQLite database file path
365
     *
366
     * @return bool TRUE if the backup was made since the modifications to the
367
     *              fixtures; FALSE otherwise
368
     */
369 3
    protected function isBackupUpToDate(array $classNames, $backup)
370
    {
371 3
        $backupLastModifiedDateTime = new \DateTime();
372 3
        $backupLastModifiedDateTime->setTimestamp(filemtime($backup));
373
374 3
        foreach ($classNames as &$className) {
375 2
            $fixtureLastModifiedDateTime = $this->getFixtureLastModified($className);
376 2
            if ($backupLastModifiedDateTime < $fixtureLastModifiedDateTime) {
377
                return false;
378
            }
379 3
        }
380
381 3
        return true;
382
    }
383
384
    /**
385
     * Copy SQLite backup file.
386
     *
387
     * @param ObjectManager            $om
388
     * @param string                   $executorClass
389
     * @param ProxyReferenceRepository $referenceRepository
390
     * @param string                   $backup              Path of the source file.
391
     * @param string                   $name                Path of the destination file.
392
     */
393 3
    private function copySqliteBackup($om, $executorClass,
394
        $referenceRepository, $backup, $name)
395
    {
396 3
        $om->flush();
397 3
        $om->clear();
398
399 3
        $this->preFixtureRestore($om, $referenceRepository);
400
401 3
        copy($backup, $name);
402
403 3
        $executor = new $executorClass($om);
404 3
        $executor->setReferenceRepository($referenceRepository);
405 3
        $executor->getReferenceRepository()->load($backup);
406
407 3
        $this->postFixtureRestore();
408
409 3
        return $executor;
410
    }
411
412
    /**
413
     * Purge database.
414
     *
415
     * @param ObjectManager            $om
416
     * @param string                   $type
417
     * @param int                      $purgeMode
418
     * @param string                   $executorClass
419
     * @param ProxyReferenceRepository $referenceRepository
420
     */
421 23
    private function purgeDatabase(ObjectManager $om, $type, $purgeMode,
422
        $executorClass,
423
        ProxyReferenceRepository $referenceRepository)
424
    {
425 23
        $container = $this->getContainer();
426
427 23
        $purgerClass = 'Doctrine\\Common\\DataFixtures\\Purger\\'.$type.'Purger';
428 23
        if ('PHPCR' === $type) {
429 1
            $purger = new $purgerClass($om);
430 1
            $initManager = $container->has('doctrine_phpcr.initializer_manager')
431 1
                ? $container->get('doctrine_phpcr.initializer_manager')
432 1
                : null;
433
434 1
            $executor = new $executorClass($om, $purger, $initManager);
435 1
        } else {
436 22
            $purger = new $purgerClass();
437 22
            if (null !== $purgeMode) {
438 1
                $purger->setPurgeMode($purgeMode);
439 1
            }
440
441 22
            $executor = new $executorClass($om, $purger);
442
        }
443
444 23
        $executor->setReferenceRepository($referenceRepository);
445 23
        $executor->purge();
446
447 23
        return $executor;
448
    }
449
450
    /**
451
     * Purge database.
452
     *
453
     * @param ObjectManager            $om
454
     * @param string                   $name
455
     * @param array                    $metadatas
456
     * @param string                   $executorClass
457
     * @param ProxyReferenceRepository $referenceRepository
458
     */
459 18
    private function createSqliteSchema(ObjectManager $om, $name,
460
        $metadatas, $executorClass,
461
        ProxyReferenceRepository $referenceRepository)
462
    {
463
        // TODO: handle case when using persistent connections. Fail loudly?
464 18
        $schemaTool = new SchemaTool($om);
0 ignored issues
show
Compatibility introduced by
$om of type object<Doctrine\Common\Persistence\ObjectManager> is not a sub-type of object<Doctrine\ORM\EntityManagerInterface>. It seems like you assume a child interface of the interface Doctrine\Common\Persistence\ObjectManager to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
465 18
        $schemaTool->dropDatabase($name);
0 ignored issues
show
Unused Code introduced by
The call to SchemaTool::dropDatabase() has too many arguments starting with $name.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
466 18
        if (!empty($metadatas)) {
467 18
            $schemaTool->createSchema($metadatas);
468 18
        }
469 18
        $this->postFixtureSetup();
470
471 18
        $executor = new $executorClass($om);
472 18
        $executor->setReferenceRepository($referenceRepository);
473 18
    }
474
475
    /**
476
     * Set the database to the provided fixtures.
477
     *
478
     * Drops the current database and then loads fixtures using the specified
479
     * classes. The parameter is a list of fully qualified class names of
480
     * classes that implement Doctrine\Common\DataFixtures\FixtureInterface
481
     * so that they can be loaded by the DataFixtures Loader::addFixture
482
     *
483
     * When using SQLite this method will automatically make a copy of the
484
     * loaded schema and fixtures which will be restored automatically in
485
     * case the same fixture classes are to be loaded again. Caveat: changes
486
     * to references and/or identities may go undetected.
487
     *
488
     * Depends on the doctrine data-fixtures library being available in the
489
     * class path.
490
     *
491
     * @param array  $classNames   List of fully qualified class names of fixtures to load
492
     * @param string $omName       The name of object manager to use
493
     * @param string $registryName The service id of manager registry to use
494
     * @param int    $purgeMode    Sets the ORM purge mode
495
     *
496
     * @return null|AbstractExecutor
497
     */
498 26
    protected function loadFixtures(array $classNames, $omName = null, $registryName = 'doctrine', $purgeMode = null)
499
    {
500 26
        $container = $this->getContainer();
501
        /** @var ManagerRegistry $registry */
502 26
        $registry = $container->get($registryName);
503 26
        $om = $registry->getManager($omName);
504 26
        $type = $registry->getName();
505
506 26
        $executorClass = $this->getExecutorClass($type);
507 26
        $referenceRepository = new ProxyReferenceRepository($om);
508
509 26
        $cacheDriver = $om->getMetadataFactory()->getCacheDriver();
510
511 26
        if ($cacheDriver) {
512 26
            $cacheDriver->deleteAll();
513 26
        }
514
515 26
        if ('ORM' === $type) {
516 25
            $connection = $om->getConnection();
517 25
            if ($connection->getDriver() instanceof SqliteDriver) {
518 21
                $name = $this->getNameParameter($connection);
519 21
                $metadatas = $this->getCachedMetadatas($om, $omName);
520
521 21
                if ($container->getParameter('liip_functional_test.cache_sqlite_db')) {
522 5
                    $backup = $container->getParameter('kernel.cache_dir').'/test_'.md5(serialize($metadatas).serialize($classNames)).'.db';
523 5
                    if (file_exists($backup) && file_exists($backup.'.ser') && $this->isBackupUpToDate($classNames, $backup)) {
524 3
                        $executor = $this->copySqliteBackup($om,
525 3
                            $executorClass, $referenceRepository,
526 3
                            $backup, $name);
527
528 3
                        return $executor;
529
                    }
530 2
                }
531
532 18
                $this->createSqliteSchema($om, $name, $metadatas,
533 18
                    $executorClass, $referenceRepository);
534 18
            }
535 22
        }
536
537 23
        if (empty($executor)) {
0 ignored issues
show
Bug introduced by
The variable $executor seems only to be defined at a later point. As such the call to empty() seems to always evaluate to true.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
538 23
            $executor = $this->purgeDatabase($om, $type, $purgeMode,
539 23
                $executorClass, $referenceRepository);
540 23
        }
541
542 23
        $loader = $this->getFixtureLoader($container, $classNames);
543
544 23
        $executor->execute($loader->getFixtures(), true);
545
546 23
        if (isset($name) && isset($backup)) {
547 2
            $this->preReferenceSave($om, $executor, $backup);
548
549 2
            $executor->getReferenceRepository()->save($backup);
550 2
            copy($name, $backup);
551
552 2
            $this->postReferenceSave($om, $executor, $backup);
553 2
        }
554
555 23
        return $executor;
556
    }
557
558
    /**
559
     * Clean database.
560
     *
561
     * @param ManagerRegistry $registry
562
     * @param EntityManager   $om
563
     */
564 3
    private function cleanDatabase(ManagerRegistry $registry, EntityManager $om)
565
    {
566 3
        $connection = $om->getConnection();
567
568 3
        $mysql = ($registry->getName() === 'ORM'
569 3
            && $connection->getDatabasePlatform() instanceof MySqlPlatform);
570
571 3
        if ($mysql) {
572 1
            $connection->query('SET FOREIGN_KEY_CHECKS=0');
573 1
        }
574
575 3
        $this->loadFixtures(array());
576
577 3
        if ($mysql) {
578 1
            $connection->query('SET FOREIGN_KEY_CHECKS=1');
579 1
        }
580 3
    }
581
582
    /**
583
     * Locate fixture files.
584
     *
585
     * @param array $paths
586
     *
587
     * @return array $files
588
     */
589 3
    private function locateResources($paths)
590
    {
591 3
        $files = array();
592
593 3
        $kernel = $this->getContainer()->get('kernel');
594
595 3
        foreach ($paths as $path) {
596 3
            if ($path[0] !== '@' && file_exists($path) === true) {
597 1
                $files[] = $path;
598 1
                continue;
599
            }
600
601 2
            $files[] = $kernel->locateResource($path);
602 3
        }
603
604 3
        return $files;
605
    }
606
607
    /**
608
     * @param array  $paths        Either symfony resource locators (@ BundleName/etc) or actual file paths
609
     * @param bool   $append
610
     * @param null   $omName
611
     * @param string $registryName
612
     *
613
     * @return array
614
     *
615
     * @throws \BadMethodCallException
616
     */
617 3
    public function loadFixtureFiles(array $paths = array(), $append = false, $omName = null, $registryName = 'doctrine')
618
    {
619 3
        if (!class_exists('Nelmio\Alice\Fixtures')) {
620
            throw new \BadMethodCallException('nelmio/alice should be installed to use this method.');
621
        }
622
623
        /** @var ManagerRegistry $registry */
624 3
        $registry = $this->getContainer()->get($registryName);
625
        /** @var EntityManager $om */
626 3
        $om = $registry->getManager($omName);
627
628 3
        if ($append === false) {
629 3
            $this->cleanDatabase($registry, $om);
630 3
        }
631
632 3
        $files = $this->locateResources($paths);
633
634 3
        return Fixtures::load($files, $om);
635
    }
636
637
    /**
638
     * Callback function to be executed after Schema creation.
639
     * Use this to execute acl:init or other things necessary.
640
     */
641 18
    protected function postFixtureSetup()
642
    {
643 18
    }
644
645
    /**
646
     * Callback function to be executed after Schema restore.
647
     *
648
     * @return WebTestCase
649
     */
650 3
    protected function postFixtureRestore()
651
    {
652 3
    }
653
654
    /**
655
     * Callback function to be executed before Schema restore.
656
     *
657
     * @param ObjectManager            $manager             The object manager
658
     * @param ProxyReferenceRepository $referenceRepository The reference repository
659
     *
660
     * @return WebTestCase
661
     */
662 3
    protected function preFixtureRestore(ObjectManager $manager, ProxyReferenceRepository $referenceRepository)
0 ignored issues
show
Unused Code introduced by
The parameter $manager is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $referenceRepository is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
663
    {
664 3
    }
665
666
    /**
667
     * Callback function to be executed after save of references.
668
     *
669
     * @param ObjectManager    $manager        The object manager
670
     * @param AbstractExecutor $executor       Executor of the data fixtures
671
     * @param string           $backupFilePath Path of file used to backup the references of the data fixtures
672
     *
673
     * @return WebTestCase
674
     */
675 2
    protected function postReferenceSave(ObjectManager $manager, AbstractExecutor $executor, $backupFilePath)
0 ignored issues
show
Unused Code introduced by
The parameter $manager is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $executor is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $backupFilePath is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
676
    {
677 2
    }
678
679
    /**
680
     * Callback function to be executed before save of references.
681
     *
682
     * @param ObjectManager    $manager        The object manager
683
     * @param AbstractExecutor $executor       Executor of the data fixtures
684
     * @param string           $backupFilePath Path of file used to backup the references of the data fixtures
685
     *
686
     * @return WebTestCase
687
     */
688 2
    protected function preReferenceSave(ObjectManager $manager, AbstractExecutor $executor, $backupFilePath)
0 ignored issues
show
Unused Code introduced by
The parameter $manager is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $executor is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $backupFilePath is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
689
    {
690 2
    }
691
692
    /**
693
     * Retrieve Doctrine DataFixtures loader.
694
     *
695
     * @param ContainerInterface $container
696
     * @param array              $classNames
697
     *
698
     * @return Loader
699
     */
700 23
    protected function getFixtureLoader(ContainerInterface $container, array $classNames)
701
    {
702 23
        $loaderClass = class_exists('Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader')
703 23
            ? 'Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader'
704 23
            : (class_exists('Doctrine\Bundle\FixturesBundle\Common\DataFixtures\Loader')
705
                ? 'Doctrine\Bundle\FixturesBundle\Common\DataFixtures\Loader'
706 23
                : 'Symfony\Bundle\DoctrineFixturesBundle\Common\DataFixtures\Loader');
707
708 23
        $loader = new $loaderClass($container);
709
710 23
        foreach ($classNames as $className) {
711 6
            $this->loadFixtureClass($loader, $className);
712 23
        }
713
714 23
        return $loader;
715
    }
716
717
    /**
718
     * Load a data fixture class.
719
     *
720
     * @param Loader $loader
721
     * @param string $className
722
     */
723 6
    protected function loadFixtureClass($loader, $className)
724
    {
725 6
        $fixture = new $className();
726
727 6
        if ($loader->hasFixture($fixture)) {
728
            unset($fixture);
729
730
            return;
731
        }
732
733 6
        $loader->addFixture($fixture);
734
735 6
        if ($fixture instanceof DependentFixtureInterface) {
736
            foreach ($fixture->getDependencies() as $dependency) {
737
                $this->loadFixtureClass($loader, $dependency);
738
            }
739
        }
740 6
    }
741
742
    /**
743
     * Creates an instance of a lightweight Http client.
744
     *
745
     * If $authentication is set to 'true' it will use the content of
746
     * 'liip_functional_test.authentication' to log in.
747
     *
748
     * $params can be used to pass headers to the client, note that they have
749
     * to follow the naming format used in $_SERVER.
750
     * Example: 'HTTP_X_REQUESTED_WITH' instead of 'X-Requested-With'
751
     *
752
     * @param bool|array $authentication
753
     * @param array      $params
754
     *
755
     * @return Client
756
     */
757 46
    protected function makeClient($authentication = false, array $params = array())
758
    {
759 46
        if ($authentication) {
760 2
            if ($authentication === true) {
761
                $authentication = array(
762 1
                    'username' => $this->getContainer()
763 1
                        ->getParameter('liip_functional_test.authentication.username'),
764 1
                    'password' => $this->getContainer()
765 1
                        ->getParameter('liip_functional_test.authentication.password'),
766 1
                );
767 1
            }
768
769 2
            $params = array_merge($params, array(
770 2
                'PHP_AUTH_USER' => $authentication['username'],
771 2
                'PHP_AUTH_PW' => $authentication['password'],
772 2
            ));
773 2
        }
774
775 46
        $client = static::createClient(array('environment' => $this->environment), $params);
776
777 46
        if ($this->firewallLogins) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->firewallLogins of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
778
            // has to be set otherwise "hasPreviousSession" in Request returns false.
779 2
            $options = $client->getContainer()->getParameter('session.storage.options');
780
781 2
            if (!$options || !isset($options['name'])) {
782
                throw new \InvalidArgumentException('Missing session.storage.options#name');
783
            }
784
785 2
            $session = $client->getContainer()->get('session');
786
            // Since the namespace of the session changed in symfony 2.1, instanceof can be used to check the version.
787 2
            if ($session instanceof Session) {
788 2
                $session->setId(uniqid());
789 2
            }
790
791 2
            $client->getCookieJar()->set(new Cookie($options['name'], $session->getId()));
792
793
            /** @var $user UserInterface */
794 2
            foreach ($this->firewallLogins as $firewallName => $user) {
795 2
                $token = $this->createUserToken($user, $firewallName);
796
797
                // BC: security.token_storage is available on Symfony 2.6+
798
                // see http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
799 2
                if ($client->getContainer()->has('security.token_storage')) {
800 2
                    $tokenStorage = $client->getContainer()->get('security.token_storage');
801 2
                } else {
802
                    // This block will never be reached with Symfony 2.6+
803
                    // @codeCoverageIgnoreStart
804
                    $tokenStorage = $client->getContainer()->get('security.context');
805
                    // @codeCoverageIgnoreEnd
806
                }
807
808 2
                $tokenStorage->setToken($token);
809 2
                $session->set('_security_'.$firewallName, serialize($token));
810 2
            }
811
812 2
            $session->save();
813 2
        }
814
815 46
        return $client;
816
    }
817
818
    /**
819
     * Create User Token.
820
     *
821
     * Factory method for creating a User Token object for the firewall based on
822
     * the user object provided. By default it will be a Username/Password
823
     * Token based on the user's credentials, but may be overridden for custom
824
     * tokens in your applications.
825
     *
826
     * @param UserInterface $user         The user object to base the token off of
827
     * @param string        $firewallName name of the firewall provider to use
828
     *
829
     * @return TokenInterface The token to be used in the security context
830
     */
831 2
    protected function createUserToken(UserInterface $user, $firewallName)
832
    {
833 2
        return new UsernamePasswordToken(
834 2
            $user,
835 2
            null,
836 2
            $firewallName,
837 2
            $user->getRoles()
838 2
        );
839
    }
840
841
    /**
842
     * Extracts the location from the given route.
843
     *
844
     * @param string $route    The name of the route
845
     * @param array  $params   Set of parameters
846
     * @param bool   $absolute
847
     *
848
     * @return string
849
     */
850 1
    protected function getUrl($route, $params = array(), $absolute = UrlGeneratorInterface::ABSOLUTE_PATH)
851
    {
852 1
        return $this->getContainer()->get('router')->generate($route, $params, $absolute);
853
    }
854
855
    /**
856
     * Checks the success state of a response.
857
     *
858
     * @param Response $response Response object
859
     * @param bool     $success  to define whether the response is expected to be successful
860
     * @param string   $type
861
     */
862 5
    public function isSuccessful(Response $response, $success = true, $type = 'text/html')
863
    {
864
        try {
865 5
            $crawler = new Crawler();
866 5
            $crawler->addContent($response->getContent(), $type);
867 5
            if (!count($crawler->filter('title'))) {
868 1
                $title = '['.$response->getStatusCode().'] - '.$response->getContent();
869 1
            } else {
870 4
                $title = $crawler->filter('title')->text();
871
            }
872 5
        } catch (\Exception $e) {
873
            $title = $e->getMessage();
874
        }
875
876 5
        if ($success) {
877 4
            $this->assertTrue($response->isSuccessful(), 'The Response was not successful: '.$title);
878 4
        } else {
879 1
            $this->assertFalse($response->isSuccessful(), 'The Response was successful: '.$title);
880
        }
881 5
    }
882
883
    /**
884
     * Executes a request on the given url and returns the response contents.
885
     *
886
     * This method also asserts the request was successful.
887
     *
888
     * @param string $path           path of the requested page
889
     * @param string $method         The HTTP method to use, defaults to GET
890
     * @param bool   $authentication Whether to use authentication, defaults to false
891
     * @param bool   $success        to define whether the response is expected to be successful
892
     *
893
     * @return string
894
     */
895 1
    public function fetchContent($path, $method = 'GET', $authentication = false, $success = true)
896
    {
897 1
        $client = $this->makeClient($authentication);
898 1
        $client->request($method, $path);
899
900 1
        $content = $client->getResponse()->getContent();
901 1
        if (is_bool($success)) {
902 1
            $this->isSuccessful($client->getResponse(), $success);
903 1
        }
904
905 1
        return $content;
906
    }
907
908
    /**
909
     * Executes a request on the given url and returns a Crawler object.
910
     *
911
     * This method also asserts the request was successful.
912
     *
913
     * @param string $path           path of the requested page
914
     * @param string $method         The HTTP method to use, defaults to GET
915
     * @param bool   $authentication Whether to use authentication, defaults to false
916
     * @param bool   $success        Whether the response is expected to be successful
917
     *
918
     * @return Crawler
919
     */
920 1
    public function fetchCrawler($path, $method = 'GET', $authentication = false, $success = true)
921
    {
922 1
        $client = $this->makeClient($authentication);
923 1
        $crawler = $client->request($method, $path);
924
925 1
        $this->isSuccessful($client->getResponse(), $success);
926
927 1
        return $crawler;
928
    }
929
930
    /**
931
     * @param UserInterface $user
932
     *
933
     * @return WebTestCase
934
     */
935 2
    public function loginAs(UserInterface $user, $firewallName)
936
    {
937 2
        $this->firewallLogins[$firewallName] = $user;
938
939 2
        return $this;
940
    }
941
942
    /**
943
     * Asserts that the HTTP response code of the last request performed by
944
     * $client matches the expected code. If not, raises an error with more
945
     * information.
946
     *
947
     * @param $expectedStatusCode
948
     * @param Client $client
949
     */
950 9
    public function assertStatusCode($expectedStatusCode, Client $client)
951
    {
952 9
        $helpfulErrorMessage = null;
953
954 9
        if ($expectedStatusCode !== $client->getResponse()->getStatusCode()) {
955
            // Get a more useful error message, if available
956
            if ($exception = $client->getContainer()->get('liip_functional_test.exception_listener')->getLastException()) {
957
                $helpfulErrorMessage = $exception->getMessage();
958
            } elseif (count($validationErrors = $client->getContainer()->get('liip_functional_test.validator')->getLastErrors())) {
959
                $helpfulErrorMessage = "Unexpected validation errors:\n";
960
961
                foreach ($validationErrors as $error) {
962
                    $helpfulErrorMessage .= sprintf("+ %s: %s\n", $error->getPropertyPath(), $error->getMessage());
963
                }
964
            } else {
965
                $helpfulErrorMessage = substr($client->getResponse(), 0, 200);
966
            }
967
        }
968
969 9
        self::assertEquals($expectedStatusCode, $client->getResponse()->getStatusCode(), $helpfulErrorMessage);
970 9
    }
971
972
    /**
973
     * Assert that the last validation errors within $container match the
974
     * expected keys.
975
     *
976
     * @param array              $expected  A flat array of field names
977
     * @param ContainerInterface $container
978
     */
979 2
    public function assertValidationErrors(array $expected, ContainerInterface $container)
980
    {
981 2
        self::assertThat(
982 2
            $container->get('liip_functional_test.validator')->getLastErrors(),
983 2
            new ValidationErrorsConstraint($expected),
984
            'Validation errors should match.'
985 2
        );
986 1
    }
987
}
988