Completed
Pull Request — master (#5964)
by Marco
65:20
created

DeadEntitiesCommand::findMissingEntities()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
dl 0
loc 23
rs 8.7972
c 4
b 0
f 0
cc 4
eloc 17
nc 5
nop 2
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\ORM\Tools\Console\Command;
21
22
use Doctrine\ORM\Mapping\MappingException;
23
use Symfony\Component\Console\Input\InputInterface;
24
use Symfony\Component\Console\Output\OutputInterface;
25
use Symfony\Component\Console\Command\Command;
26
use Doctrine\ORM\Query\QueryException;
27
28
/**
29
 * Show information about dead entities.
30
 *
31
 * Dead entities appear in a database where data has been inserted improperly.
32
 * For example someone can disable referential integrity checks, delete the
33
 * parent row in a parent-child relationship, and then enable referential
34
 * integrity checks.
35
 *
36
 * Even worse we could face the nightmare of having to work with a database
37
 * designed before referential integrity, and data modeling, was conceived by
38
 * the humar race. And yes, there a countries where this still happens!
39
 *
40
 * @link    www.doctrine-project.org
41
 * @since   2.6
42
 * @author  Marco Buschini <[email protected]>
43
 */
44
class DeadEntitiesCommand extends Command
45
{
46
    /**
47
     * {@inheritdoc}
48
     */
49
    protected function configure()
50
    {
51
        $this
52
            ->setName('orm:deadentities')
53
            ->setDescription('Checks for dead entities in the DB')
54
            ->setHelp(<<<EOT
55
The <info>%command.name%</info> shows entities that have a reference to a
56
missing entity, such as children with a parent that has been deleted.
57
EOT
58
        );
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    protected function execute(InputInterface $input, OutputInterface $output)
65
    {
66
        /* @var $entityManager \Doctrine\ORM\EntityManager */
67
        $entityManager = $this->getHelper('em')->getEntityManager();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method getEntityManager() does only exist in the following implementations of said interface: Doctrine\ORM\Tools\Conso...per\EntityManagerHelper.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
68
        $schema = $entityManager->getConnection()->getSchemaManager();
69
70
        $classNames = $entityManager->getConfiguration()->getMetadataDriverImpl()->getAllClassNames();
71
72
        if (!$classNames) {
73
            throw new \Exception(
74
                'You do not have any mapped Doctrine ORM entities according to the current configuration. '.
75
                'If you have entities or mapping files you should check your mapping configuration for errors.'
76
            );
77
        }
78
79
        $output->writeln(sprintf("Found <info>%d</info> mapped entities:", count($classNames)));
80
81
        $tableNames = array();
82
        foreach($classNames as $className) {
83
            $tableNames[$entityManager->getClassMetadata($className)->getTableName()] = $className;
84
        }
85
        $failure = false;
86
        $entity = array();
0 ignored issues
show
Unused Code introduced by
$entity 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...
87
        foreach ($classNames as $className) {
88
            try {
89
                $tableName = array_search($className, $tableNames);
90
                $keys = $schema->listTableForeignKeys($tableName);
91
                $output->writeln('<info>'.$className.'('.$tableName.')'.'</info> '.count($keys).' foreign key(s)');
92
                $assoc = $entityManager->getClassMetadata($className)->getAssociationMappings();
93
                foreach($assoc as $a) {
94
                    if(array_key_exists('sourceToTargetKeyColumns', $a)) {
95
                        $output->writeln('-> Entity: '.$a['targetEntity'].'('.array_search($a['targetEntity'], $tableNames).')');
96
                        $sourceFields = array();
97
                        $sourceColumns = array();
98
                        foreach ($a['joinColumnFieldNames'] as $column => $field) {
99
                            $output->writeln("\tField: $field($column)");
100
                            $sourceFields[] = $field;
101
                            $sourceColumns[] = $column;
102
                        }
103
                        $targetFields = array();
104
                        $targetColumns = array();
105
                        foreach($a['sourceToTargetKeyColumns'] as $fcolumn => $ffield) {
106
                            $output->writeln("\t\tForeign key: $ffield($fcolumn)");
107
                            $targetFields[] = $ffield;
108
                            $targetColumns[] = $fcolumn;
109
                        }
110
                        $missing = $this->findMissingEntities($a, $output);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $missing is correct as $this->findMissingEntities($a, $output) (which targets Doctrine\ORM\Tools\Conso...::findMissingEntities()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Unused Code introduced by
$missing 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...
111
                    }
112
                }
113
            } catch (MappingException $e) {
114
                $output->writeln("<error>[FAIL]</error> ".$className);
115
                $output->writeln(sprintf("<comment>%s</comment>", $e->getMessage()));
116
                $output->writeln('');
117
118
                $failure = true;
119
            }
120
        }
121
        return $failure ? 1 : 0;
122
    }
123
124
    private function findMissingEntities($entity, $output) {
125
        $dql = "SELECT _inner, _outer\n"
126
              ."  FROM ".$entity['sourceEntity']." _inner\n"
127
              ."  LEFT JOIN ".$entity['targetEntity']." _outer"
128
              .$this->with($entity)
129
              .$this->where($entity);
130
        
131
        $entityManager = $this->getHelper('em')->getEntityManager();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method getEntityManager() does only exist in the following implementations of said interface: Doctrine\ORM\Tools\Conso...per\EntityManagerHelper.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
132
        try {
133
            $query = $entityManager->createQuery($dql);
134
            $ret = $query->getResult();
135
        } catch(QueryException $e) {
136
            $output->writeln("<error>Data model too complex to analyze.</error>");
137
            return;
138
        }
139
140
        foreach($ret as $key) {
141
            if($key == null) {
142
                continue;
143
            }
144
            $output->writeln("\t".$entity['targetEntity'].' id with missing reference '.$key->getId());
145
        }
146
    }
147
    
148
    private function with($entity) {
149
        if(count($entity['joinColumns']) == 1 || true) {
150
            return "\n  WITH _inner.".$entity['fieldName']." = _outer";
151
        }
152
        $ret = "\n  WITH ";
153
        foreach($entity['joinColumns'] as $column) {
154
            $ret .= "_inner.".$column['name']." = _outer.".$column['referencedColumnName']."\n   AND ";
155
        }
156
        return substr($ret, 0, strlen($ret) - 6);
157
    }
158
    
159
    private function where($entity) {
160
        if(count($entity['joinColumns']) != 0) {
161
            $ret = "\n WHERE ";
162
            foreach($entity['joinColumns'] as $column) {
163
                $ret .= "_outer.".$column['referencedColumnName']." IS NULL\n   AND ";
164
            }
165
            return substr($ret, 0, strlen($ret) - 6);
166
        } else {
167
            return "\n WHERE _outer IS NULL";
168
        }
169
    }
170
}
171