Test Failed
Pull Request — master (#308)
by
unknown
07:33
created

WebTestCase::getCallingClass()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 2
cts 2
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 4
nop 0
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\Driver\PDOSqlite\Driver as SqliteDriver;
37
use Doctrine\DBAL\Platforms\MySqlPlatform;
38
use Doctrine\ORM\EntityManager;
39
use Doctrine\ORM\Tools\SchemaTool;
40
use Nelmio\Alice\Fixtures;
41
use Liip\FunctionalTestBundle\Utils\HttpAssertions;
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 $excludedDoctrineTables = array();
69
70
    /**
71
     * @var array
72
     */
73
    private static $cachedMetadatas = array();
74
75
    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...
76
    {
77
        $dir = isset($_SERVER['KERNEL_DIR']) ? $_SERVER['KERNEL_DIR'] : static::getPhpUnitXmlDir();
78
79
        list($appname) = explode('\\', get_called_class());
80
81
        $class = $appname.'Kernel';
82
        $file = $dir.'/'.strtolower($appname).'/'.$class.'.php';
83
        if (!file_exists($file)) {
84
            return parent::getKernelClass();
85
        }
86
        require_once $file;
87
88
        return $class;
89
    }
90
91
    /**
92
     * Creates a mock object of a service identified by its id.
93
     *
94
     * @param string $id
95
     *
96
     * @return \PHPUnit_Framework_MockObject_MockBuilder
97
     */
98
    protected function getServiceMockBuilder($id)
99
    {
100
        $service = $this->getContainer()->get($id);
101
        $class = get_class($service);
102
103
        return $this->getMockBuilder($class)->disableOriginalConstructor();
104
    }
105
106
    /**
107
     * Builds up the environment to run the given command.
108
     *
109
     * @param string $name
110
     * @param array  $params
111
     * @param bool   $reuseKernel
112
     *
113
     * @return string
114
     */
115 12
    protected function runCommand($name, array $params = array(), $reuseKernel = false)
116
    {
117 12
        array_unshift($params, $name);
118
119 12
        if (!$reuseKernel) {
120 12
            if (null !== static::$kernel) {
121 9
                static::$kernel->shutdown();
122 9
            }
123
124 12
            $kernel = static::$kernel = $this->createKernel(array('environment' => $this->environment));
125 12
            $kernel->boot();
126 12
        } else {
127 2
            $kernel = $this->getContainer()->get('kernel');
128
        }
129
130 12
        $application = new Application($kernel);
131 12
        $application->setAutoExit(false);
132
133
        // @codeCoverageIgnoreStart
134
        if ('203' === substr(Kernel::VERSION_ID, 0, 3)) {
135
            $params = $this->configureVerbosityForSymfony203($params);
136
        }
137
        // @codeCoverageIgnoreEnd
138
139 12
        $input = new ArrayInput($params);
140 12
        $input->setInteractive(false);
141
142 12
        $fp = fopen('php://temp/maxmemory:'.$this->maxMemory, 'r+');
143 12
        $output = new StreamOutput($fp, $this->getVerbosityLevel(), $this->getDecorated());
144
145 11
        $application->run($input, $output);
146
147 11
        rewind($fp);
148
149 11
        return stream_get_contents($fp);
150
    }
151
152
    /**
153
     * Retrieves the output verbosity level.
154
     *
155
     * @see Symfony\Component\Console\Output\OutputInterface for available levels
156
     *
157
     * @return int
158
     *
159
     * @throws \OutOfBoundsException If the set value isn't accepted
160
     */
161 12
    protected function getVerbosityLevel()
162
    {
163
        // If `null`, is not yet set
164 12
        if (null === $this->verbosityLevel) {
165
            // Set the global verbosity level that is set as NORMAL by the TreeBuilder in Configuration
166 6
            $level = strtoupper($this->getContainer()->getParameter('liip_functional_test.command_verbosity'));
167 6
            $verbosity = '\Symfony\Component\Console\Output\StreamOutput::VERBOSITY_'.$level;
168
169 6
            $this->verbosityLevel = constant($verbosity);
170 6
        }
171
172
        // If string, it is set by the developer, so check that the value is an accepted one
173 12
        if (is_string($this->verbosityLevel)) {
174 6
            $level = strtoupper($this->verbosityLevel);
175 6
            $verbosity = '\Symfony\Component\Console\Output\StreamOutput::VERBOSITY_'.$level;
176
177 6
            if (!defined($verbosity)) {
178 1
                throw new \OutOfBoundsException(
179 1
                    sprintf('The set value "%s" for verbosityLevel is not valid. Accepted are: "quiet", "normal", "verbose", "very_verbose" and "debug".', $level)
180 1
                );
181
            }
182
183 5
            $this->verbosityLevel = constant($verbosity);
184 5
        }
185
186 11
        return $this->verbosityLevel;
187
    }
188
189
    /**
190
     * In Symfony 2.3.* the verbosity level has to be set through {Symfony\Component\Console\Input\ArrayInput} and not
191
     * in {Symfony\Component\Console\Output\OutputInterface}.
192
     *
193
     * This method builds $params to be passed to {Symfony\Component\Console\Input\ArrayInput}.
194
     *
195
     * @codeCoverageIgnore
196
     *
197
     * @param array $params
198
     *
199
     * @return array
200
     */
201
    private function configureVerbosityForSymfony203(array $params)
202
    {
203
        switch ($this->getVerbosityLevel()) {
204
            case OutputInterface::VERBOSITY_QUIET:
205
                $params['-q'] = '-q';
206
                break;
207
208
            case OutputInterface::VERBOSITY_VERBOSE:
209
                $params['-v'] = '';
210
                break;
211
212
            case OutputInterface::VERBOSITY_VERY_VERBOSE:
213
                $params['-vv'] = '';
214
                break;
215
216
            case OutputInterface::VERBOSITY_DEBUG:
217
                $params['-vvv'] = '';
218
                break;
219
        }
220
221
        return $params;
222
    }
223
224 6
    public function setVerbosityLevel($level)
225
    {
226 6
        $this->verbosityLevel = $level;
227 6
    }
228
229
    /**
230
     * Retrieves the flag indicating if the output should be decorated or not.
231
     *
232
     * @return bool
233
     */
234 11
    protected function getDecorated()
235
    {
236 11
        if (null === $this->decorated) {
237
            // Set the global decoration flag that is set to `true` by the TreeBuilder in Configuration
238 5
            $this->decorated = $this->getContainer()->getParameter('liip_functional_test.command_decoration');
239 5
        }
240
241
        // Check the local decorated flag
242 11
        if (false === is_bool($this->decorated)) {
243
            throw new \OutOfBoundsException(
244
                sprintf('`WebTestCase::decorated` has to be `bool`. "%s" given.', gettype($this->decorated))
245
            );
246
        }
247
248 11
        return $this->decorated;
249
    }
250
251 6
    public function isDecorated($decorated)
252
    {
253 6
        $this->decorated = $decorated;
254 6
    }
255
256
    /**
257
     * Get an instance of the dependency injection container.
258
     * (this creates a kernel *without* parameters).
259
     *
260
     * @return ContainerInterface
261
     */
262 49
    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...
263
    {
264 49
        if (!empty($this->kernelDir)) {
265
            $tmpKernelDir = isset($_SERVER['KERNEL_DIR']) ? $_SERVER['KERNEL_DIR'] : null;
266
            $_SERVER['KERNEL_DIR'] = getcwd().$this->kernelDir;
267
        }
268
269 49
        $cacheKey = $this->kernelDir.'|'.$this->environment;
270 49
        if (empty($this->containers[$cacheKey])) {
271
            $options = array(
272 48
                'environment' => $this->environment,
273 48
            );
274 48
            $kernel = $this->createKernel($options);
275 48
            $kernel->boot();
276
277 48
            $this->containers[$cacheKey] = $kernel->getContainer();
278 48
        }
279
280 49
        if (isset($tmpKernelDir)) {
281
            $_SERVER['KERNEL_DIR'] = $tmpKernelDir;
282
        }
283
284 49
        return $this->containers[$cacheKey];
285
    }
286
287
    /**
288
     * This function finds the time when the data blocks of a class definition
289
     * file were being written to, that is, the time when the content of the
290
     * file was changed.
291
     *
292
     * @param string $class The fully qualified class name of the fixture class to
293
     *                      check modification date on
294
     *
295
     * @return \DateTime|null
296
     */
297 3
    protected function getFixtureLastModified($class)
298
    {
299 3
        $lastModifiedDateTime = null;
300
301 3
        $reflClass = new \ReflectionClass($class);
302 3
        $classFileName = $reflClass->getFileName();
303
304 3
        if (file_exists($classFileName)) {
305 3
            $lastModifiedDateTime = new \DateTime();
306 3
            $lastModifiedDateTime->setTimestamp(filemtime($classFileName));
307 3
        }
308
309 3
        return $lastModifiedDateTime;
310
    }
311
312
    /**
313
     * Determine if the Fixtures that define a database backup have been
314
     * modified since the backup was made.
315
     *
316
     * @param array  $classNames The fixture classnames to check
317
     * @param string $backup     The fixture backup SQLite database file path
318
     *
319
     * @return bool TRUE if the backup was made since the modifications to the
320
     *              fixtures; FALSE otherwise
321
     */
322 7
    protected function isBackupUpToDate(array $classNames, $backup)
323
    {
324 7
        $backupLastModifiedDateTime = new \DateTime();
325 7
        $backupLastModifiedDateTime->setTimestamp(filemtime($backup));
326
327
        /** @var \Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader $loader */
328 7
        $loader = $this->getFixtureLoader($this->getContainer(), $classNames);
329
330
        // Use loader in order to fetch all the dependencies fixtures.
331 7
        foreach ($loader->getFixtures() as $className) {
332 3
            $fixtureLastModifiedDateTime = $this->getFixtureLastModified($className);
333 3
            if ($backupLastModifiedDateTime < $fixtureLastModifiedDateTime) {
334 1
                return false;
335
            }
336 7
        }
337
338 7
        return true;
339
    }
340
341
    /**
342
     * Set the database to the provided fixtures.
343
     *
344
     * Drops the current database and then loads fixtures using the specified
345
     * classes. The parameter is a list of fully qualified class names of
346
     * classes that implement Doctrine\Common\DataFixtures\FixtureInterface
347
     * so that they can be loaded by the DataFixtures Loader::addFixture
348
     *
349
     * When using SQLite this method will automatically make a copy of the
350
     * loaded schema and fixtures which will be restored automatically in
351
     * case the same fixture classes are to be loaded again. Caveat: changes
352
     * to references and/or identities may go undetected.
353
     *
354
     * Depends on the doctrine data-fixtures library being available in the
355
     * class path.
356
     *
357
     * @param array  $classNames   List of fully qualified class names of fixtures to load
358
     * @param string $omName       The name of object manager to use
359
     * @param string $registryName The service id of manager registry to use
360
     * @param int    $purgeMode    Sets the ORM purge mode
361
     *
362
     * @return null|AbstractExecutor
363
     */
364 36
    protected function loadFixtures(array $classNames, $omName = null, $registryName = 'doctrine', $purgeMode = null)
365
    {
366 36
        $container = $this->getContainer();
367
        /** @var ManagerRegistry $registry */
368 36
        $registry = $container->get($registryName);
369
        /** @var ObjectManager $om */
370 36
        $om = $registry->getManager($omName);
371 36
        $type = $registry->getName();
372
373 36
        $executorClass = 'PHPCR' === $type && class_exists('Doctrine\Bundle\PHPCRBundle\DataFixtures\PHPCRExecutor')
374 36
            ? 'Doctrine\Bundle\PHPCRBundle\DataFixtures\PHPCRExecutor'
375 36
            : 'Doctrine\\Common\\DataFixtures\\Executor\\'.$type.'Executor';
376 36
        $referenceRepository = new ProxyReferenceRepository($om);
377 36
        $cacheDriver = $om->getMetadataFactory()->getCacheDriver();
378
379 36
        if ($cacheDriver) {
380 36
            $cacheDriver->deleteAll();
381 36
        }
382
383 36
        if ('ORM' === $type) {
384 35
            $connection = $om->getConnection();
385 35
            if ($connection->getDriver() instanceof SqliteDriver) {
386 30
                $params = $connection->getParams();
387 30
                if (isset($params['master'])) {
388
                    $params = $params['master'];
389
                }
390
391 30
                $name = isset($params['path']) ? $params['path'] : (isset($params['dbname']) ? $params['dbname'] : false);
392 30
                if (!$name) {
393
                    throw new \InvalidArgumentException("Connection does not contain a 'path' or 'dbname' parameter and cannot be dropped.");
394
                }
395
396 30
                if (!isset(self::$cachedMetadatas[$omName])) {
397 10
                    self::$cachedMetadatas[$omName] = $om->getMetadataFactory()->getAllMetadata();
398 10
                    usort(self::$cachedMetadatas[$omName], function ($a, $b) {
399
                        return strcmp($a->name, $b->name);
400 10
                    });
401 10
                }
402 30
                $metadatas = self::$cachedMetadatas[$omName];
403
404 30
                if ($container->getParameter('liip_functional_test.cache_sqlite_db')) {
405 9
                    $backup = $container->getParameter('kernel.cache_dir').'/test_'.md5(serialize($metadatas).serialize($classNames)).'.db';
406 9
                    if (file_exists($backup) && file_exists($backup.'.ser') && $this->isBackupUpToDate($classNames, $backup)) {
407 7
                        $om->flush();
408 7
                        $om->clear();
409
410 7
                        $this->preFixtureRestore($om, $referenceRepository);
411
412 7
                        copy($backup, $name);
413
414 7
                        $executor = new $executorClass($om);
415 7
                        $executor->setReferenceRepository($referenceRepository);
416 7
                        $executor->getReferenceRepository()->load($backup);
417
418 7
                        $this->postFixtureRestore();
419
420 7
                        return $executor;
421
                    }
422 3
                }
423
424
                // TODO: handle case when using persistent connections. Fail loudly?
425 24
                $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...
426 24
                $schemaTool->dropDatabase();
427 24
                if (!empty($metadatas)) {
428 24
                    $schemaTool->createSchema($metadatas);
429 24
                }
430 24
                $this->postFixtureSetup();
431
432 24
                $executor = new $executorClass($om);
433 24
                $executor->setReferenceRepository($referenceRepository);
434 24
            }
435 29
        }
436
437 30
        if (empty($executor)) {
438 6
            $purgerClass = 'Doctrine\\Common\\DataFixtures\\Purger\\'.$type.'Purger';
439 6
            if ('PHPCR' === $type) {
440 1
                $purger = new $purgerClass($om);
441 1
                $initManager = $container->has('doctrine_phpcr.initializer_manager')
442 1
                    ? $container->get('doctrine_phpcr.initializer_manager')
443 1
                    : null;
444
445 1
                $executor = new $executorClass($om, $purger, $initManager);
446 1
            } else {
447 5
                if ('ORM' === $type) {
448 5
                    $purger = new $purgerClass(null, $this->excludedDoctrineTables);
449 5
                } else {
450
                    $purger = new $purgerClass();
451
                }
452
453 5
                if (null !== $purgeMode) {
454 2
                    $purger->setPurgeMode($purgeMode);
455 2
                }
456
457 5
                $executor = new $executorClass($om, $purger);
458
            }
459
460 6
            $executor->setReferenceRepository($referenceRepository);
461 6
            $executor->purge();
462 6
        }
463
464 30
        $loader = $this->getFixtureLoader($container, $classNames);
465
466 30
        $executor->execute($loader->getFixtures(), true);
467
468 30
        if (isset($name) && isset($backup)) {
469 3
            $this->preReferenceSave($om, $executor, $backup);
470
471 3
            $executor->getReferenceRepository()->save($backup);
472 3
            copy($name, $backup);
473
474 3
            $this->postReferenceSave($om, $executor, $backup);
475 3
        }
476
477 30
        return $executor;
478
    }
479
480
    /**
481
     * Clean database.
482
     *
483
     * @param ManagerRegistry $registry
484
     * @param EntityManager   $om
485
     * @param null            $omName
486
     */
487 9
    private function cleanDatabase(ManagerRegistry $registry, EntityManager $om, $omName = null)
488
    {
489 9
        $connection = $om->getConnection();
490
491 9
        $mysql = ($registry->getName() === 'ORM'
492 9
            && $connection->getDatabasePlatform() instanceof MySqlPlatform);
493
494 9
        if ($mysql) {
495 1
            $connection->query('SET FOREIGN_KEY_CHECKS=0');
496 1
        }
497
498 9
        $this->loadFixtures(array(), $omName);
499
500 9
        if ($mysql) {
501 1
            $connection->query('SET FOREIGN_KEY_CHECKS=1');
502 1
        }
503 9
    }
504
505
    /**
506
     * Locate fixture files.
507
     *
508
     * @param array $paths
509
     *
510
     * @return array $files
511
     *
512
     * @throws \InvalidArgumentException if a wrong path is given outside a bundle
513
     */
514 9
    private function locateResources($paths)
515
    {
516 9
        $files = array();
517
        $kernel = $this->getContainer()->get('kernel');
518 9
        foreach ($paths as $path) {
519
            $path = $this->getCallingClassPath().'/'.$path;
520 9
            if ($path[0] !== '@') {
521 9
                if (!file_exists($path)) {
522 3
                    throw new \InvalidArgumentException(sprintf('Unable to find file "%s".', $path));
523 1
                }
524
                $files[] = $path;
525 2
                continue;
526 2
            }
527
            $files[] = $kernel->locateResource($path);
528
        }
529 6
        return $files;
530 7
    }
531
532 7
    private function getCallingClassPath()
533
    {
534
        $reflector = new \ReflectionClass($this->getCallingClass());
535
        $callingClassFilename = $reflector->getFileName();
536
537
        return dirname($callingClassFilename);
538
    }
539
540
    private function getCallingClass()
541
    {
542
        $trace = debug_backtrace();
543
        $class = $trace[1]['class'];
544
        for ($i = 1; $i < count($trace); ++$i) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
545 9
            if (isset($trace[$i])) {
546
                if ($class != $trace[$i]['class']) {
547 9
                    return $trace[$i]['class'];
548
                }
549
            }
550
        }
551
    }
552
553
    /**
554
     * @param array  $paths        Either symfony resource locators (@ BundleName/etc) or actual file paths
555 9
     * @param bool   $append
556
     * @param null   $omName
557
     * @param string $registryName
558 9
     *
559
     * @return array
560
     *
561 9
     * @throws \BadMethodCallException
562
     */
563 9
    public function loadFixtureFiles(array $paths = array(), $append = false, $omName = null, $registryName = 'doctrine')
564 9
    {
565 9
        if (!class_exists('Nelmio\Alice\Fixtures')) {
566
            // This class is available during tests, no exception will be thrown.
567 9
            // @codeCoverageIgnoreStart
568
            throw new \BadMethodCallException('nelmio/alice should be installed to use this method.');
569
            // @codeCoverageIgnoreEnd
570 7
        }
571 7
572 3
        /** @var ContainerInterface $container */
573 3
        $container = $this->getContainer();
574 3
575 3
        /** @var ManagerRegistry $registry */
576
        $registry = $container->get($registryName);
577 3
578
        /** @var EntityManager $om */
579
        $om = $registry->getManager($omName);
580 4
581
        if ($append === false) {
582
            $this->cleanDatabase($registry, $om, $omName);
583
        }
584
585
        $files = $this->locateResources($paths);
586
587 24
        // Check if the Hautelook AliceBundle is registered and if yes, use it instead of Nelmio Alice
588
        $hautelookLoaderServiceName = 'hautelook_alice.fixtures.loader';
589 24
        if ($container->has($hautelookLoaderServiceName)) {
590
            $loaderService = $container->get($hautelookLoaderServiceName);
591
            $persisterClass = class_exists('Nelmio\Alice\ORM\Doctrine') ?
592
                'Nelmio\Alice\ORM\Doctrine' :
593
                'Nelmio\Alice\Persister\Doctrine';
594
595
            return $loaderService->load(new $persisterClass($om), $files);
596 7
        }
597
598 7
        return Fixtures::load($files, $om);
599
    }
600
601
    /**
602
     * Callback function to be executed after Schema creation.
603
     * Use this to execute acl:init or other things necessary.
604
     */
605
    protected function postFixtureSetup()
606
    {
607
    }
608 7
609
    /**
610 7
     * Callback function to be executed after Schema restore.
611
     *
612
     * @return WebTestCase
613
     */
614
    protected function postFixtureRestore()
615
    {
616
    }
617
618
    /**
619
     * Callback function to be executed before Schema restore.
620
     *
621 3
     * @param ObjectManager            $manager             The object manager
622
     * @param ProxyReferenceRepository $referenceRepository The reference repository
623 3
     *
624
     * @return WebTestCase
625
     */
626
    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...
627
    {
628
    }
629
630
    /**
631
     * Callback function to be executed after save of references.
632
     *
633
     * @param ObjectManager    $manager        The object manager
634 3
     * @param AbstractExecutor $executor       Executor of the data fixtures
635
     * @param string           $backupFilePath Path of file used to backup the references of the data fixtures
636 3
     *
637
     * @return WebTestCase
638
     */
639
    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...
640
    {
641
    }
642
643
    /**
644
     * Callback function to be executed before save of references.
645
     *
646 36
     * @param ObjectManager    $manager        The object manager
647
     * @param AbstractExecutor $executor       Executor of the data fixtures
648 36
     * @param string           $backupFilePath Path of file used to backup the references of the data fixtures
649 36
     *
650 36
     * @return WebTestCase
651
     */
652
    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...
653
    {
654
    }
655 36
656
    /**
657 36
     * Retrieve Doctrine DataFixtures loader.
658
     *
659 36
     * @param ContainerInterface $container
660 11
     * @param array              $classNames
661 36
     *
662
     * @return Loader
663 36
     */
664
    protected function getFixtureLoader(ContainerInterface $container, array $classNames)
665
    {
666
        $loaderClass = class_exists('Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader')
667
            ? 'Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader'
668
            : (class_exists('Doctrine\Bundle\FixturesBundle\Common\DataFixtures\Loader')
669
                // This class is not available during tests.
670
                // @codeCoverageIgnoreStart
671
                ? 'Doctrine\Bundle\FixturesBundle\Common\DataFixtures\Loader'
672 11
                // @codeCoverageIgnoreEnd
673
                : 'Symfony\Bundle\DoctrineFixturesBundle\Common\DataFixtures\Loader');
674 11
675
        $loader = new $loaderClass($container);
676 11
677 2
        foreach ($classNames as $className) {
678
            $this->loadFixtureClass($loader, $className);
679 2
        }
680
681
        return $loader;
682 11
    }
683
684 11
    /**
685 2
     * Load a data fixture class.
686 2
     *
687 2
     * @param Loader $loader
688 2
     * @param string $className
689 11
     */
690
    protected function loadFixtureClass($loader, $className)
691
    {
692
        $fixture = new $className();
693
694
        if ($loader->hasFixture($fixture)) {
695
            unset($fixture);
696
697
            return;
698
        }
699
700
        $loader->addFixture($fixture);
701
702
        if ($fixture instanceof DependentFixtureInterface) {
703
            foreach ($fixture->getDependencies() as $dependency) {
704
                $this->loadFixtureClass($loader, $dependency);
705
            }
706 54
        }
707
    }
708 54
709 2
    /**
710
     * Creates an instance of a lightweight Http client.
711 1
     *
712 1
     * If $authentication is set to 'true' it will use the content of
713 1
     * 'liip_functional_test.authentication' to log in.
714 1
     *
715 1
     * $params can be used to pass headers to the client, note that they have
716 1
     * to follow the naming format used in $_SERVER.
717
     * Example: 'HTTP_X_REQUESTED_WITH' instead of 'X-Requested-With'
718 2
     *
719 2
     * @param bool|array $authentication
720 2
     * @param array      $params
721 2
     *
722 2
     * @return Client
723
     */
724 54
    protected function makeClient($authentication = false, array $params = array())
725
    {
726 54
        if ($authentication) {
727
            if ($authentication === true) {
728 2
                $authentication = array(
729
                    'username' => $this->getContainer()
730 2
                        ->getParameter('liip_functional_test.authentication.username'),
731
                    'password' => $this->getContainer()
732
                        ->getParameter('liip_functional_test.authentication.password'),
733
                );
734 2
            }
735
736 2
            $params = array_merge($params, array(
737 2
                'PHP_AUTH_USER' => $authentication['username'],
738 2
                'PHP_AUTH_PW' => $authentication['password'],
739
            ));
740 2
        }
741
742
        $client = static::createClient(array('environment' => $this->environment), $params);
743 2
744 2
        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...
745
            // has to be set otherwise "hasPreviousSession" in Request returns false.
746
            $options = $client->getContainer()->getParameter('session.storage.options');
747
748 2
            if (!$options || !isset($options['name'])) {
749 2
                throw new \InvalidArgumentException('Missing session.storage.options#name');
750 2
            }
751
752
            $session = $client->getContainer()->get('session');
753
            // Since the namespace of the session changed in symfony 2.1, instanceof can be used to check the version.
754
            if ($session instanceof Session) {
755
                $session->setId(uniqid());
756
            }
757 2
758 2
            $client->getCookieJar()->set(new Cookie($options['name'], $session->getId()));
759 2
760
            /** @var $user UserInterface */
761 2
            foreach ($this->firewallLogins as $firewallName => $user) {
762 2
                $token = $this->createUserToken($user, $firewallName);
763
764 54
                // BC: security.token_storage is available on Symfony 2.6+
765
                // see http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
766
                if ($client->getContainer()->has('security.token_storage')) {
767
                    $tokenStorage = $client->getContainer()->get('security.token_storage');
768
                } else {
769
                    // This block will never be reached with Symfony 2.6+
770
                    // @codeCoverageIgnoreStart
771
                    $tokenStorage = $client->getContainer()->get('security.context');
772
                    // @codeCoverageIgnoreEnd
773
                }
774
775
                $tokenStorage->setToken($token);
776
                $session->set('_security_'.$firewallName, serialize($token));
777
            }
778
779
            $session->save();
780 2
        }
781
782 2
        return $client;
783 2
    }
784 2
785 2
    /**
786 2
     * Create User Token.
787 2
     *
788
     * Factory method for creating a User Token object for the firewall based on
789
     * the user object provided. By default it will be a Username/Password
790
     * Token based on the user's credentials, but may be overridden for custom
791
     * tokens in your applications.
792
     *
793
     * @param UserInterface $user         The user object to base the token off of
794
     * @param string        $firewallName name of the firewall provider to use
795
     *
796
     * @return TokenInterface The token to be used in the security context
797
     */
798
    protected function createUserToken(UserInterface $user, $firewallName)
799 1
    {
800
        return new UsernamePasswordToken(
801 1
            $user,
802
            null,
803
            $firewallName,
804
            $user->getRoles()
805
        );
806
    }
807
808
    /**
809
     * Extracts the location from the given route.
810
     *
811 6
     * @param string $route    The name of the route
812
     * @param array  $params   Set of parameters
813 6
     * @param int    $absolute
814 5
     *
815
     * @return string
816
     */
817
    protected function getUrl($route, $params = array(), $absolute = UrlGeneratorInterface::ABSOLUTE_PATH)
818
    {
819
        return $this->getContainer()->get('router')->generate($route, $params, $absolute);
820
    }
821
822
    /**
823
     * Checks the success state of a response.
824
     *
825
     * @param Response $response Response object
826
     * @param bool     $success  to define whether the response is expected to be successful
827
     * @param string   $type
828 1
     */
829
    public function isSuccessful(Response $response, $success = true, $type = 'text/html')
830 1
    {
831 1
        HttpAssertions::isSuccessful($response, $success, $type);
832
    }
833 1
834 1
    /**
835 1
     * Executes a request on the given url and returns the response contents.
836 1
     *
837
     * This method also asserts the request was successful.
838 1
     *
839
     * @param string $path           path of the requested page
840
     * @param string $method         The HTTP method to use, defaults to GET
841
     * @param bool   $authentication Whether to use authentication, defaults to false
842
     * @param bool   $success        to define whether the response is expected to be successful
843
     *
844
     * @return string
845
     */
846
    public function fetchContent($path, $method = 'GET', $authentication = false, $success = true)
847
    {
848
        $client = $this->makeClient($authentication);
849
        $client->request($method, $path);
850
851
        $content = $client->getResponse()->getContent();
852
        if (is_bool($success)) {
853 1
            $this->isSuccessful($client->getResponse(), $success);
0 ignored issues
show
Bug introduced by
It seems like $client->getResponse() can be null; however, isSuccessful() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
854
        }
855 1
856 1
        return $content;
857
    }
858 1
859
    /**
860 1
     * Executes a request on the given url and returns a Crawler object.
861
     *
862
     * This method also asserts the request was successful.
863
     *
864
     * @param string $path           path of the requested page
865
     * @param string $method         The HTTP method to use, defaults to GET
866
     * @param bool   $authentication Whether to use authentication, defaults to false
867
     * @param bool   $success        Whether the response is expected to be successful
868
     *
869 2
     * @return Crawler
870
     */
871 2
    public function fetchCrawler($path, $method = 'GET', $authentication = false, $success = true)
872
    {
873 2
        $client = $this->makeClient($authentication);
874
        $crawler = $client->request($method, $path);
875
876
        $this->isSuccessful($client->getResponse(), $success);
0 ignored issues
show
Bug introduced by
It seems like $client->getResponse() can be null; however, isSuccessful() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
877
878
        return $crawler;
879
    }
880
881
    /**
882
     * @param UserInterface $user
883
     * @param string        $firewallName
884 12
     *
885
     * @return WebTestCase
886 12
     */
887 9
    public function loginAs(UserInterface $user, $firewallName)
888
    {
889
        $this->firewallLogins[$firewallName] = $user;
890
891
        return $this;
892
    }
893
894
    /**
895
     * Asserts that the HTTP response code of the last request performed by
896 3
     * $client matches the expected code. If not, raises an error with more
897
     * information.
898 3
     *
899 1
     * @param $expectedStatusCode
900
     * @param Client $client
901
     */
902
    public function assertStatusCode($expectedStatusCode, Client $client)
903
    {
904 1
        HttpAssertions::assertStatusCode($expectedStatusCode, $client);
905
    }
906 1
907 1
    /**
908
     * Assert that the last validation errors within $container match the
909
     * expected keys.
910
     *
911
     * @param array              $expected  A flat array of field names
912
     * @param ContainerInterface $container
913
     */
914
    public function assertValidationErrors(array $expected, ContainerInterface $container)
915
    {
916
        HttpAssertions::assertValidationErrors($expected, $container);
917
    }
918
919
    /**
920
     * @param array $excludedDoctrineTables
921
     */
922
    public function setExcludedDoctrineTables($excludedDoctrineTables)
923
    {
924
        $this->excludedDoctrineTables = $excludedDoctrineTables;
925
    }
926
}
927