FixturesCommand   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 8
c 3
b 1
f 0
lcom 1
cbo 8
dl 0
loc 75
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 16 1
A execute() 0 16 2
B loadFixtures() 0 38 5
1
<?php
2
3
namespace AppBundle\Command;
4
5
use Symfony\Component\Console\Input\InputOption;
6
use Symfony\Component\Console\Input\InputInterface;
7
use Symfony\Component\Console\Output\OutputInterface;
8
use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader as DataFixturesLoader;
9
use Doctrine\Bundle\DoctrineBundle\Command\DoctrineCommand;
10
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
11
use Doctrine\Common\DataFixtures\FixtureInterface;
12
use Doctrine\ORM\EntityManager;
13
use AppBundle\Entity\Internal\Fixture;
14
15
class FixturesCommand extends DoctrineCommand
16
{
17
    protected function configure()
18
    {
19
        $this
20
            ->setName('app:fixtures')
21
            ->setDescription('Load data fixtures to your database.')
22
            ->addOption('em', null, InputOption::VALUE_REQUIRED, 'The entity manager to use for this command.')
23
            ->setHelp(<<<EOT
24
The <info>%command.name%</info> command loads data fixtures from your bundles:
25
It loads only ones which were not appended already.
26
27
<info>php %command.full_name%</info>
28
<info>php %command.full_name% --env=prod</info>
29
30
EOT
31
        );
32
    }
33
34
    protected function execute(InputInterface $input, OutputInterface $output)
35
    {
36
        $doctrine = $this->getContainer()->get('doctrine');
37
        $em = $doctrine->getManager($input->getOption('em'));
38
39
        $alreadyLoaded = $em->getRepository("AppBundle:Internal\Fixture")->findAll();
40
        // may support more managers
41
        $loaded = $this->loadFixtures($output, $em, $alreadyLoaded);
42
43
        foreach ($loaded as $fixture) {
44
            $added = new Fixture();
45
            $added->setName(get_class($fixture));
46
            $em->persist($added);
47
        }
48
        $em->flush();
49
    }
50
51
    private function loadFixtures(OutputInterface $output, EntityManager $em, array $loaded)
52
    {
53
        $logger = function($message) use ($output) {
54
            $output->writeln(sprintf('  <comment>></comment> <info>%s</info>', $message));
55
        };
56
        $executor = new ORMExecutor($em);
57
58
        $paths = [];
59
        foreach ($this->getApplication()->getKernel()->getBundles() as $bundle) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Console\Application as the method getKernel() does only exist in the following sub-classes of Symfony\Component\Console\Application: Symfony\Bundle\FrameworkBundle\Console\Application. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
60
            $paths[] = $bundle->getPath() . '/Fixture';
61
        }
62
63
        $loader = new DataFixturesLoader($this->getContainer());
64
        foreach ($paths as $path) {
65
            if (is_dir($path)) {
66
                $loader->loadFromDirectory($path);
67
            }
68
        }
69
        $env = $this->getContainer()->getParameter('kernel.environment');
0 ignored issues
show
Unused Code introduced by
$env is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
70
        $output->writeln("Loading <comment>fixtures</comment>...");
71
72
        $has = array_map(function(Fixture $fixture) {
73
            return $fixture->getName();
74
        }, $loaded);
75
76
        $fixtures = array_filter($loader->getFixtures(), function(FixtureInterface $fixture) use($has) {
77
            return !in_array(get_class($fixture), $has);
78
        });
79
80
        if (!$fixtures) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fixtures 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...
81
            $output->writeln("  Could not find any new <comment>fixtures</comment> to load..");
82
            return [];
83
        }
84
85
        $executor->setLogger($logger);
86
        $executor->execute($fixtures, true);
87
        return $fixtures;
88
    }
89
}
90