Completed
Pull Request — master (#230)
by Adamo
06:37
created

WebTestCase::getVerbosityLevel()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.074

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 27
ccs 10
cts 12
cp 0.8333
rs 8.5806
cc 4
eloc 13
nc 6
nop 0
crap 4.074
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\StreamOutput;
19
use Symfony\Component\DomCrawler\Crawler;
20
use Symfony\Component\BrowserKit\Cookie;
21
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
22
use Symfony\Component\Security\Core\User\UserInterface;
23
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
24
use Symfony\Component\DependencyInjection\ContainerInterface;
25
use Symfony\Component\HttpFoundation\Session\Session;
26
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
27
use Symfony\Bridge\Doctrine\ManagerRegistry;
28
use Symfony\Bundle\DoctrineFixturesBundle\Common\DataFixtures\Loader;
29
use Doctrine\Common\Persistence\ObjectManager;
30
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
31
use Doctrine\Common\DataFixtures\Executor\AbstractExecutor;
32
use Doctrine\Common\DataFixtures\ProxyReferenceRepository;
33
use Doctrine\DBAL\Driver\PDOSqlite\Driver as SqliteDriver;
34
use Doctrine\DBAL\Platforms\MySqlPlatform;
35
use Doctrine\ORM\Tools\SchemaTool;
36
use Nelmio\Alice\Fixtures;
37
38
/**
39
 * @author Lea Haensenberger
40
 * @author Lukas Kahwe Smith <[email protected]>
41
 * @author Benjamin Eberlei <[email protected]>
42
 */
43
abstract class WebTestCase extends BaseWebTestCase
44
{
45
    protected $environment = 'test';
46
    protected $containers;
47
    protected $kernelDir;
48
    // 5 * 1024 * 1024 KB
49
    protected $maxMemory = 5242880;
50
    protected $verbosityLevel;
51
    protected $decorated;
52
53
    /**
54
     * @var array
55
     */
56
    private $firewallLogins = array();
57
58
    /**
59
     * @var array
60
     */
61
    private static $cachedMetadatas = array();
62
63 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...
64
    {
65 1
        $dir = isset($_SERVER['KERNEL_DIR']) ? $_SERVER['KERNEL_DIR'] : self::getPhpUnitXmlDir();
66
67 1
        list($appname) = explode('\\', get_called_class());
68
69 1
        $class = $appname.'Kernel';
70 1
        $file = $dir.'/'.strtolower($appname).'/'.$class.'.php';
71 1
        if (!file_exists($file)) {
72 1
            return parent::getKernelClass();
73
        }
74
        require_once $file;
75
76
        return $class;
77
    }
78
79
    /**
80
     * Creates a mock object of a service identified by its id.
81
     *
82
     * @param string $id
83
     *
84
     * @return PHPUnit_Framework_MockObject_MockBuilder
85
     */
86
    protected function getServiceMockBuilder($id)
87
    {
88
        $service = $this->getContainer()->get($id);
89
        $class = get_class($service);
90
91
        return $this->getMockBuilder($class)->disableOriginalConstructor();
92
    }
93
94
    /**
95
     * Builds up the environment to run the given command.
96
     *
97
     * @param string $name
98
     * @param array  $params
99
     * @param bool   $reuseKernel
100
     *
101
     * @return string
102
     */
103 1
    protected function runCommand($name, array $params = array(), $reuseKernel = false)
104
    {
105 1
        array_unshift($params, $name);
106
107 1
        if (!$reuseKernel) {
108 1
            if (null !== static::$kernel) {
109 1
                static::$kernel->shutdown();
110 1
            }
111
112 1
            $kernel = static::$kernel = $this->createKernel(array('environment' => $this->environment));
113 1
            $kernel->boot();
114 1
        } else {
115 1
            $kernel = $this->getContainer()->get('kernel');
116
        }
117
118 1
        $application = new Application($kernel);
119 1
        $application->setAutoExit(false);
120
121 1
        $input = new ArrayInput($params);
122 1
        $input->setInteractive(false);
123
124 1
        $fp = fopen('php://temp/maxmemory:'.$this->maxMemory, 'r+');
125 1
        $output = new StreamOutput($fp, $this->getVerbosityLevel(), $this->getDecorated());
126
127 1
        $application->run($input, $output);
128
129 1
        rewind($fp);
130
131 1
        return stream_get_contents($fp);
132
    }
133
134
    /**
135
     * Retrieves the output verbosity level.
136
     *
137
     * @see Symfony\Component\Console\Output\OutputInterface for available levels
138
     *
139
     * @return int
140
     * @throws \OutOfBoundsException If the set value isn't accepted
141 1
     */
142
    protected function getVerbosityLevel()
143
    {
144 1
        // If `null`, is not yet set
145 1
        if (null === $this->verbosityLevel) {
146 1
            // Set the global verbosity level that is set as NORMAL by the TreeBuilder in Configuration
147
            $level = strtoupper($this->getContainer()->getParameter('liip_functional_test.command_verbosity'));
148
            $verbosity = '\Symfony\Component\Console\Output\StreamOutput::VERBOSITY_'.$level;
149 1
150
            $this->verbosityLevel = constant($verbosity);
151
        }
152 1
153 1
        // If string, it is set by the developer, so check that the value is an accepted one
154 1
        if (is_string($this->verbosityLevel)) {
155
            $level = strtoupper($this->verbosityLevel);
156
            $verbosity = '\Symfony\Component\Console\Output\StreamOutput::VERBOSITY_'.$level;
157 1
158
            if (null === constant($verbosity)) {
159
                throw new \OutOfBoundsException(
160 1
                    'The set value "%s" for verbosityLevel is not valid. Accepted are: "quiet", "normal", "verbose", "very_verbose" and "debug".
161
                    ');
162
            }
163
164
            $this->verbosityLevel = constant($verbosity);
165
        }
166
167
        return $this->verbosityLevel;
168 1
    }
169
170
    /**
171 1
     * Retrieves the flag indicating if the output should be decorated or not.
172 1
     *
173
     * @return bool
174
     *
175
     * @throws \OutOfBoundsException
176 1
     */
177 1
    protected function getDecorated()
178
    {
179
        if (null === $this->decorated) {
180
            // Set the global decoration flag that is set to `true` by the TreeBuilder in Configuration
181
            $this->decorated = $this->getContainer()->getParameter('liip_functional_test.command_decoration');
182
        }
183
184
        // Check the local decorated flag
185
        if (false === is_bool($this->decorated)) {
186
            throw new \OutOfBoundsException(
187
                sprintf('`WebTestCase::decorated` has to be `bool`. "%s" given.', gettype($this->decorated))
188
            );
189
        }
190 25
191
        return $this->decorated;
192 25
    }
193
194
    /**
195
     * Get an instance of the dependency injection container.
196
     * (this creates a kernel *without* parameters).
197 25
     *
198 25
     * @return ContainerInterface
199
     */
200 25
    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...
201 25
    {
202 25
        if (!empty($this->kernelDir)) {
203 25
            $tmpKernelDir = isset($_SERVER['KERNEL_DIR']) ? $_SERVER['KERNEL_DIR'] : null;
204
            $_SERVER['KERNEL_DIR'] = getcwd().$this->kernelDir;
205 25
        }
206 25
207
        $cacheKey = $this->kernelDir.'|'.$this->environment;
208 25
        if (empty($this->containers[$cacheKey])) {
209
            $options = array(
210
                'environment' => $this->environment,
211
            );
212 25
            $kernel = $this->createKernel($options);
213
            $kernel->boot();
214
215
            $this->containers[$cacheKey] = $kernel->getContainer();
216
        }
217
218
        if (isset($tmpKernelDir)) {
219
            $_SERVER['KERNEL_DIR'] = $tmpKernelDir;
220
        }
221
222
        return $this->containers[$cacheKey];
223
    }
224
225 5
    /**
226
     * This function finds the time when the data blocks of a class definition
227 5
     * file were being written to, that is, the time when the content of the
228
     * file was changed.
229 5
     *
230 5
     * @param string $class The fully qualified class name of the fixture class to
231
     *                      check modification date on.
232 5
     *
233 5
     * @return \DateTime|null
234 5
     */
235 5
    protected function getFixtureLastModified($class)
236
    {
237 5
        $lastModifiedDateTime = null;
238
239
        $reflClass = new \ReflectionClass($class);
240
        $classFileName = $reflClass->getFileName();
241
242
        if (file_exists($classFileName)) {
243
            $lastModifiedDateTime = new \DateTime();
244
            $lastModifiedDateTime->setTimestamp(filemtime($classFileName));
245
        }
246
247
        return $lastModifiedDateTime;
248
    }
249
250 23
    /**
251
     * Determine if the Fixtures that define a database backup have been
252 23
     * modified since the backup was made.
253 23
     *
254
     * @param array  $classNames The fixture classnames to check
255 23
     * @param string $backup     The fixture backup SQLite database file path
256 5
     *
257 5
     * @return bool TRUE if the backup was made since the modifications to the
258
     *              fixtures; FALSE otherwise
259
     */
260 23
    protected function isBackupUpToDate(array $classNames, $backup)
261
    {
262 23
        $backupLastModifiedDateTime = new \DateTime();
263
        $backupLastModifiedDateTime->setTimestamp(filemtime($backup));
264
265
        foreach ($classNames as &$className) {
266
            $fixtureLastModifiedDateTime = $this->getFixtureLastModified($className);
267
            if ($backupLastModifiedDateTime < $fixtureLastModifiedDateTime) {
268
                return false;
269
            }
270
        }
271
272
        return true;
273
    }
274
275
    /**
276
     * Set the database to the provided fixtures.
277
     *
278
     * Drops the current database and then loads fixtures using the specified
279
     * classes. The parameter is a list of fully qualified class names of
280
     * classes that implement Doctrine\Common\DataFixtures\FixtureInterface
281
     * so that they can be loaded by the DataFixtures Loader::addFixture
282
     *
283
     * When using SQLite this method will automatically make a copy of the
284
     * loaded schema and fixtures which will be restored automatically in
285
     * case the same fixture classes are to be loaded again. Caveat: changes
286
     * to references and/or identities may go undetected.
287
     *
288 25
     * Depends on the doctrine data-fixtures library being available in the
289
     * class path.
290 25
     *
291
     * @param array  $classNames   List of fully qualified class names of fixtures to load
292 25
     * @param string $omName       The name of object manager to use
293 25
     * @param string $registryName The service id of manager registry to use
294 25
     * @param int    $purgeMode    Sets the ORM purge mode
295
     *
296 25
     * @return null|AbstractExecutor
297 25
     */
298 25
    protected function loadFixtures(array $classNames, $omName = null, $registryName = 'doctrine', $purgeMode = null)
299 25
    {
300 25
        $container = $this->getContainer();
301
        /** @var ManagerRegistry $registry */
302 25
        $registry = $container->get($registryName);
303 25
        $om = $registry->getManager($omName);
304 25
        $type = $registry->getName();
305
306 25
        $executorClass = 'PHPCR' === $type && class_exists('Doctrine\Bundle\PHPCRBundle\DataFixtures\PHPCRExecutor')
307 25
            ? 'Doctrine\Bundle\PHPCRBundle\DataFixtures\PHPCRExecutor'
308 25
            : 'Doctrine\\Common\\DataFixtures\\Executor\\'.$type.'Executor';
309 25
        $referenceRepository = new ProxyReferenceRepository($om);
310 25
        $cacheDriver = $om->getMetadataFactory()->getCacheDriver();
311
312
        if ($cacheDriver) {
313
            $cacheDriver->deleteAll();
314 25
        }
315 25
316
        if ('ORM' === $type) {
317
            $connection = $om->getConnection();
318
            if ($connection->getDriver() instanceof SqliteDriver) {
319 25
                $params = $connection->getParams();
320 1
                if (isset($params['master'])) {
321
                    $params = $params['master'];
322 1
                }
323 25
324
                $name = isset($params['path']) ? $params['path'] : (isset($params['dbname']) ? $params['dbname'] : false);
325 25
                if (!$name) {
326 25
                    throw new \InvalidArgumentException("Connection does not contain a 'path' or 'dbname' parameter and cannot be dropped.");
327 25
                }
328 23
329 23
                if (!isset(self::$cachedMetadatas[$omName])) {
330
                    self::$cachedMetadatas[$omName] = $om->getMetadataFactory()->getAllMetadata();
331 23
                    usort(self::$cachedMetadatas[$omName], function ($a, $b) { return strcmp($a->name, $b->name); });
332
                }
333 23
                $metadatas = self::$cachedMetadatas[$omName];
334
335 23
                if ($container->getParameter('liip_functional_test.cache_sqlite_db')) {
336 23
                    $backup = $container->getParameter('kernel.cache_dir').'/test_'.md5(serialize($metadatas).serialize($classNames)).'.db';
337 23
                    if (file_exists($backup) && file_exists($backup.'.ser') && $this->isBackupUpToDate($classNames, $backup)) {
338
                        $om->flush();
339 23
                        $om->clear();
340
341 23
                        $this->preFixtureRestore($om, $referenceRepository);
342
343 2
                        copy($backup, $name);
344
345
                        $executor = new $executorClass($om);
346 2
                        $executor->setReferenceRepository($referenceRepository);
347 2
                        $executor->getReferenceRepository()->load($backup);
348 2
349 2
                        $this->postFixtureRestore();
350 2
351 2
                        return $executor;
352
                    }
353 2
                }
354 2
355 2
                // TODO: handle case when using persistent connections. Fail loudly?
356 2
                $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...
357
                $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...
358 2
                if (!empty($metadatas)) {
359
                    $schemaTool->createSchema($metadatas);
360
                }
361
                $this->postFixtureSetup();
362
363
                $executor = new $executorClass($om);
364
                $executor->setReferenceRepository($referenceRepository);
365
            }
366
        }
367
368
        if (empty($executor)) {
369
            $purgerClass = 'Doctrine\\Common\\DataFixtures\\Purger\\'.$type.'Purger';
370
            if ('PHPCR' === $type) {
371
                $purger = new $purgerClass($om);
372
                $initManager = $container->has('doctrine_phpcr.initializer_manager')
373
                    ? $container->get('doctrine_phpcr.initializer_manager')
374
                    : null;
375
376
                $executor = new $executorClass($om, $purger, $initManager);
377
            } else {
378
                $purger = new $purgerClass();
379
                if (null !== $purgeMode) {
380 2
                    $purger->setPurgeMode($purgeMode);
381
                }
382 2
383
                $executor = new $executorClass($om, $purger);
384 2
            }
385 2
386
            $executor->setReferenceRepository($referenceRepository);
387 2
            $executor->purge();
388 2
        }
389
390 2
        $loader = $this->getFixtureLoader($container, $classNames);
391 2
392
        $executor->execute($loader->getFixtures(), true);
393 2
394
        if (isset($name) && isset($backup)) {
395
            $this->preReferenceSave($om, $executor, $backup);
396
397
            $executor->getReferenceRepository()->save($backup);
398
            copy($name, $backup);
399
400
            $this->postReferenceSave($om, $executor, $backup);
401
        }
402
403
        return $executor;
404
    }
405
406 2
    /**
407
     * @param array  $paths        Either symfony resource locators (@ BundleName/etc) or actual file paths
408 2
     * @param bool   $append
409
     * @param null   $omName
410
     * @param string $registryName
411
     *
412
     * @return array
413 2
     *
414 2
     * @throws \BadMethodCallException
415
     */
416 2
    public function loadFixtureFiles(array $paths = array(), $append = false, $omName = null, $registryName = 'doctrine')
417
    {
418 2
        if (!class_exists('Nelmio\Alice\Fixtures')) {
419 2
            throw new \BadMethodCallException('nelmio/alice should be installed to use this method.');
420
        }
421
422
        /** @var ManagerRegistry $registry */
423 2
        $registry = $this->getContainer()->get($registryName);
424
        $om = $registry->getManager($omName);
425 2
426
        if ($append === false) {
427
            //Clean database
428 2
            $connection = $om->getConnection();
429
            if ($registry->getName() === 'ORM' && $connection->getDatabasePlatform() instanceof MySqlPlatform) {
430 2
                $connection->query('SET FOREIGN_KEY_CHECKS=0');
431 2
            }
432 2
433 2
            $this->loadFixtures(array());
434 1
435 1
            if ($registry->getName() === 'ORM' && $connection->getDatabasePlatform() instanceof MySqlPlatform) {
436
                $connection->query('SET FOREIGN_KEY_CHECKS=1');
437
            }
438 1
        }
439 2
440
        $files = array();
441 2
        $kernel = $this->getContainer()->get('kernel');
442
        foreach ($paths as $path) {
443
            if ($path[0] !== '@' && file_exists($path) === true) {
444
                $files[] = $path;
445
                continue;
446
            }
447
448 2
            $files[] = $kernel->locateResource($path);
449
        }
450 2
451
        return Fixtures::load($files, $om);
452
    }
453
454
    /**
455
     * Callback function to be executed after Schema creation.
456
     * Use this to execute acl:init or other things necessary.
457 23
     */
458
    protected function postFixtureSetup()
459 23
    {
460
    }
461
462
    /**
463
     * Callback function to be executed after Schema restore.
464
     *
465
     * @return WebTestCase
466
     */
467
    protected function postFixtureRestore()
468
    {
469 23
    }
470
471 23
    /**
472
     * Callback function to be executed before Schema restore.
473
     *
474
     * @param ObjectManager            $manager             The object manager
475
     * @param ProxyReferenceRepository $referenceRepository The reference repository
476
     *
477
     * @return WebTestCase
478
     */
479
    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...
480
    {
481
    }
482 2
483
    /**
484 2
     * Callback function to be executed after save of references.
485
     *
486
     * @param ObjectManager    $manager        The object manager
487
     * @param AbstractExecutor $executor       Executor of the data fixtures
488
     * @param string           $backupFilePath Path of file used to backup the references of the data fixtures
489
     *
490
     * @return WebTestCase
491
     */
492
    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...
493
    {
494
    }
495 2
496
    /**
497 2
     * Callback function to be executed before save of references.
498
     *
499
     * @param ObjectManager    $manager        The object manager
500
     * @param AbstractExecutor $executor       Executor of the data fixtures
501
     * @param string           $backupFilePath Path of file used to backup the references of the data fixtures
502
     *
503
     * @return WebTestCase
504
     */
505
    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...
506
    {
507 2
    }
508
509 2
    /**
510 2
     * Retrieve Doctrine DataFixtures loader.
511 2
     *
512
     * @param ContainerInterface $container
513 2
     * @param array              $classNames
514
     *
515 2
     * @return Loader
516
     */
517 2
    protected function getFixtureLoader(ContainerInterface $container, array $classNames)
518 1
    {
519 2
        $loaderClass = class_exists('Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader')
520
            ? 'Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader'
521 2
            : (class_exists('Doctrine\Bundle\FixturesBundle\Common\DataFixtures\Loader')
522
                ? 'Doctrine\Bundle\FixturesBundle\Common\DataFixtures\Loader'
523
                : 'Symfony\Bundle\DoctrineFixturesBundle\Common\DataFixtures\Loader');
524
525
        $loader = new $loaderClass($container);
526
527
        foreach ($classNames as $className) {
528
            $this->loadFixtureClass($loader, $className);
529
        }
530 1
531
        return $loader;
532 1
    }
533
534 1
    /**
535
     * Load a data fixture class.
536
     *
537
     * @param Loader $loader
538
     * @param string $className
539
     */
540 1
    protected function loadFixtureClass($loader, $className)
541
    {
542 1
        $fixture = new $className();
543
544
        if ($loader->hasFixture($fixture)) {
545
            unset($fixture);
546
547 1
            return;
548
        }
549
550
        $loader->addFixture($fixture);
551
552
        if ($fixture instanceof DependentFixtureInterface) {
553
            foreach ($fixture->getDependencies() as $dependency) {
554
                $this->loadFixtureClass($loader, $dependency);
555
            }
556
        }
557
    }
558
559
    /**
560
     * Creates an instance of a lightweight Http client.
561
     *
562
     * If $authentication is set to 'true' it will use the content of
563
     * 'liip_functional_test.authentication' to log in.
564 24
     *
565
     * $params can be used to pass headers to the client, note that they have
566 24
     * to follow the naming format used in $_SERVER.
567 5
     * Example: 'HTTP_X_REQUESTED_WITH' instead of 'X-Requested-With'
568 3
     *
569 3
     * @param bool|array $authentication
570
     * @param array      $params
571 5
     *
572 5
     * @return Client
573 5
     */
574 5
    protected function makeClient($authentication = false, array $params = array())
575 5
    {
576
        if ($authentication) {
577 24
            if ($authentication === true) {
578
                $authentication = $this->getContainer()->getParameter('liip_functional_test.authentication');
579 24
            }
580
581 1
            $params = array_merge($params, array(
582
                'PHP_AUTH_USER' => $authentication['username'],
583 1
                'PHP_AUTH_PW' => $authentication['password'],
584
            ));
585
        }
586
587 1
        $client = static::createClient(array('environment' => $this->environment), $params);
588
589 1
        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...
590 1
            // has to be set otherwise "hasPreviousSession" in Request returns false.
591 1
            $options = $client->getContainer()->getParameter('session.storage.options');
592
593 1
            if (!$options || !isset($options['name'])) {
594
                throw new \InvalidArgumentException('Missing session.storage.options#name');
595
            }
596 1
597 1
            $session = $client->getContainer()->get('session');
598
            // Since the namespace of the session changed in symfony 2.1, instanceof can be used to check the version.
599
            if ($session instanceof Session) {
600
                $session->setId(uniqid());
601 1
            }
602 1
603 1
            $client->getCookieJar()->set(new Cookie($options['name'], $session->getId()));
604
605
            /** @var $user UserInterface */
606
            foreach ($this->firewallLogins as $firewallName => $user) {
607
                $token = $this->createUserToken($user, $firewallName);
608
609
                // BC: security.token_storage is available on Symfony 2.6+
610 1
                // see http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
611 1
                if ($client->getContainer()->has('security.token_storage')) {
612 1
                    $tokenStorage = $client->getContainer()->get('security.token_storage');
613
                } else {
614 1
                    // This block will never be reached with Symfony 2.5+
615 1
                    // @codeCoverageIgnoreStart
616
                    $tokenStorage = $client->getContainer()->get('security.context');
617 24
                    // @codeCoverageIgnoreEnd
618
                }
619
620
                $tokenStorage->setToken($token);
621
                $session->set('_security_'.$firewallName, serialize($token));
622
            }
623
624
            $session->save();
625
        }
626
627
        return $client;
628
    }
629
630
    /**
631
     * Create User Token.
632
     *
633 1
     * Factory method for creating a User Token object for the firewall based on
634
     * the user object provided. By default it will be a Username/Password
635 1
     * Token based on the user's credentials, but may be overridden for custom
636 1
     * tokens in your applications.
637 1
     *
638 1
     * @param UserInterface $user         The user object to base the token off of
639 1
     * @param string        $firewallName name of the firewall provider to use
640 1
     *
641
     * @return TokenInterface The token to be used in the security context
642
     */
643
    protected function createUserToken(UserInterface $user, $firewallName)
644
    {
645
        return new UsernamePasswordToken(
646
            $user,
647
            null,
648
            $firewallName,
649
            $user->getRoles()
650
        );
651
    }
652 1
653
    /**
654 1
     * Extracts the location from the given route.
655
     *
656
     * @param string $route    The name of the route
657
     * @param array  $params   Set of parameters
658
     * @param bool   $absolute
659
     *
660
     * @return string
661
     */
662
    protected function getUrl($route, $params = array(), $absolute = UrlGeneratorInterface::ABSOLUTE_PATH)
663
    {
664 7
        return $this->getContainer()->get('router')->generate($route, $params, $absolute);
665
    }
666
667 7
    /**
668 7
     * Checks the success state of a response.
669 7
     *
670 2
     * @param Response $response Response object
671 2
     * @param bool     $success  to define whether the response is expected to be successful
672 5
     * @param string   $type
673
     */
674 7
    public function isSuccessful($response, $success = true, $type = 'text/html')
675
    {
676
        try {
677
            $crawler = new Crawler();
678 7
            $crawler->addContent($response->getContent(), $type);
679 5
            if (!count($crawler->filter('title'))) {
680 5
                $title = '['.$response->getStatusCode().'] - '.$response->getContent();
681 2
            } else {
682
                $title = $crawler->filter('title')->text();
683 7
            }
684
        } catch (\Exception $e) {
685
            $title = $e->getMessage();
686
        }
687
688
        if ($success) {
689
            $this->assertTrue($response->isSuccessful(), 'The Response was not successful: '.$title);
690
        } else {
691
            $this->assertFalse($response->isSuccessful(), 'The Response was successful: '.$title);
692
        }
693
    }
694
695
    /**
696
     * Executes a request on the given url and returns the response contents.
697 1
     *
698
     * This method also asserts the request was successful.
699 1
     *
700 1
     * @param string $path           path of the requested page
701
     * @param string $method         The HTTP method to use, defaults to GET
702 1
     * @param bool   $authentication Whether to use authentication, defaults to false
703 1
     * @param bool   $success        to define whether the response is expected to be successful
704 1
     *
705 1
     * @return string
706
     */
707 1
    public function fetchContent($path, $method = 'GET', $authentication = false, $success = true)
708
    {
709
        $client = $this->makeClient($authentication);
710
        $client->request($method, $path);
711
712
        $content = $client->getResponse()->getContent();
713
        if (is_bool($success)) {
714
            $this->isSuccessful($client->getResponse(), $success);
715
        }
716
717
        return $content;
718
    }
719
720
    /**
721
     * Executes a request on the given url and returns a Crawler object.
722 1
     *
723
     * This method also asserts the request was successful.
724 1
     *
725 1
     * @param string $path           path of the requested page
726
     * @param string $method         The HTTP method to use, defaults to GET
727 1
     * @param bool   $authentication Whether to use authentication, defaults to false
728
     * @param bool   $success        Whether the response is expected to be successful
729 1
     *
730
     * @return Crawler
731
     */
732
    public function fetchCrawler($path, $method = 'GET', $authentication = false, $success = true)
733
    {
734
        $client = $this->makeClient($authentication);
735
        $crawler = $client->request($method, $path);
736
737 1
        $this->isSuccessful($client->getResponse(), $success);
738
739 1
        return $crawler;
740
    }
741 1
742
    /**
743
     * @param UserInterface $user
744
     *
745
     * @return WebTestCase
746
     */
747
    public function loginAs(UserInterface $user, $firewallName)
748
    {
749
        $this->firewallLogins[$firewallName] = $user;
750
751
        return $this;
752 13
    }
753
754 13
    /**
755
     * Asserts that the HTTP response code of the last request performed by
756 13
     * $client matches the expected code. If not, raises an error with more
757
     * information.
758
     *
759
     * @param $expectedStatusCode
760
     * @param Client $client
761
     */
762
    public function assertStatusCode($expectedStatusCode, Client $client)
763
    {
764
        $helpfulErrorMessage = null;
765
766
        if ($expectedStatusCode !== $client->getResponse()->getStatusCode()) {
767
            // Get a more useful error message, if available
768
            if ($exception = $client->getContainer()->get('liip_functional_test.exception_listener')->getLastException()) {
769
                $helpfulErrorMessage = $exception->getMessage();
770
            } elseif (count($validationErrors = $client->getContainer()->get('liip_functional_test.validator')->getLastErrors())) {
771 13
                $helpfulErrorMessage = "Unexpected validation errors:\n";
772 13
773
                foreach ($validationErrors as $error) {
774
                    $helpfulErrorMessage .= sprintf("+ %s: %s\n", $error->getPropertyPath(), $error->getMessage());
775
                }
776
            } else {
777
                $helpfulErrorMessage = substr($client->getResponse(), 0, 200);
778
            }
779
        }
780
781 2
        self::assertEquals($expectedStatusCode, $client->getResponse()->getStatusCode(), $helpfulErrorMessage);
782
    }
783 2
784 2
    /**
785 2
     * Assert that the last validation errors within $container match the
786
     * expected keys.
787 2
     *
788 1
     * @param array              $expected  A flat array of field names
789
     * @param ContainerInterface $container
790
     */
791
    public function assertValidationErrors(array $expected, ContainerInterface $container)
792
    {
793
        self::assertThat(
794
            $container->get('liip_functional_test.validator')->getLastErrors(),
795
            new ValidationErrorsConstraint($expected),
796
            'Validation errors should match.'
797
        );
798
    }
799
}
800