Completed
Push — master ( 819c1f...5e21a3 )
by Fabien
02:02
created

DoctrineBundle   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 106
Duplicated Lines 13.21 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 19
c 4
b 0
f 0
lcom 1
cbo 12
dl 14
loc 106
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A build() 0 13 2
B boot() 0 45 6
D shutdown() 14 25 10
A registerCommands() 0 3 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/*
4
 * This file is part of the Doctrine Bundle
5
 *
6
 * The code was originally distributed inside the Symfony framework.
7
 *
8
 * (c) Fabien Potencier <[email protected]>
9
 * (c) Doctrine Project, Benjamin Eberlei <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Doctrine\Bundle\DoctrineBundle;
16
17
use Doctrine\Common\Util\ClassUtils;
18
use Doctrine\Bundle\DoctrineBundle\Command\CreateDatabaseDoctrineCommand;
19
use Doctrine\Bundle\DoctrineBundle\Command\DropDatabaseDoctrineCommand;
20
use Doctrine\Bundle\DoctrineBundle\Command\Proxy\ImportDoctrineCommand;
21
use Doctrine\Bundle\DoctrineBundle\Command\Proxy\RunSqlDoctrineCommand;
22
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\EntityListenerPass;
23
use Doctrine\ORM\Proxy\Autoloader;
24
use Symfony\Component\Console\Application;
25
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
26
use Symfony\Component\DependencyInjection\ContainerBuilder;
27
use Symfony\Component\HttpKernel\Bundle\Bundle;
28
use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\DoctrineValidationPass;
29
use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass;
30
use Symfony\Bridge\Doctrine\DependencyInjection\Security\UserProvider\EntityFactory;
31
32
/**
33
 * Bundle.
34
 *
35
 * @author Fabien Potencier <[email protected]>
36
 * @author Jonathan H. Wage <[email protected]>
37
 */
38
class DoctrineBundle extends Bundle
39
{
40
    private $autoloader;
41
42
    /**
43
     * {@inheritDoc}
44
     */
45
    public function build(ContainerBuilder $container)
46
    {
47
        parent::build($container);
48
49
        $container->addCompilerPass(new RegisterEventListenersAndSubscribersPass('doctrine.connections', 'doctrine.dbal.%s_connection.event_manager', 'doctrine'), PassConfig::TYPE_BEFORE_OPTIMIZATION);
50
51
        if ($container->hasExtension('security')) {
52
            $container->getExtension('security')->addUserProviderFactory(new EntityFactory('entity', 'doctrine.orm.security.user.provider'));
0 ignored issues
show
Bug introduced by
The method addUserProviderFactory() does not seem to exist on object<Symfony\Component...ion\ExtensionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
53
        }
54
55
        $container->addCompilerPass(new DoctrineValidationPass('orm'));
56
        $container->addCompilerPass(new EntityListenerPass());
57
    }
58
59
    /**
60
     * {@inheritDoc}
61
     */
62
    public function boot()
63
    {
64
        // Register an autoloader for proxies to avoid issues when unserializing them
65
        // when the ORM is used.
66
        if ($this->container->hasParameter('doctrine.orm.proxy_namespace')) {
67
            $namespace = $this->container->getParameter('doctrine.orm.proxy_namespace');
68
            $dir = $this->container->getParameter('doctrine.orm.proxy_dir');
69
            $proxyGenerator = null;
70
71
            if ($this->container->getParameter('doctrine.orm.auto_generate_proxy_classes')) {
72
                // See https://github.com/symfony/symfony/pull/3419 for usage of references
73
                $container = &$this->container;
74
75
                $proxyGenerator = function ($proxyDir, $proxyNamespace, $class) use (&$container) {
76
                    $originalClassName = ClassUtils::getRealClass($class);
77
                    /** @var $registry Registry */
78
                    $registry = $container->get('doctrine');
79
80
                    // Tries to auto-generate the proxy file
81
                    /** @var $em \Doctrine\ORM\EntityManager */
82
                    foreach ($registry->getManagers() as $em) {
83
                        if (!$em->getConfiguration()->getAutoGenerateProxyClasses()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Common\Persistence\ObjectManager as the method getConfiguration() does only exist in the following implementations of said interface: Doctrine\ORM\Decorator\EntityManagerDecorator, Doctrine\ORM\EntityManager.

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...
84
                            continue;
85
                        }
86
87
                        $metadataFactory = $em->getMetadataFactory();
88
89
                        if ($metadataFactory->isTransient($originalClassName)) {
90
                            continue;
91
                        }
92
93
                        $classMetadata = $metadataFactory->getMetadataFor($originalClassName);
94
95
                        $em->getProxyFactory()->generateProxyClasses(array($classMetadata));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Common\Persistence\ObjectManager as the method getProxyFactory() does only exist in the following implementations of said interface: Doctrine\ORM\Decorator\EntityManagerDecorator, Doctrine\ORM\EntityManager.

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...
96
97
                        clearstatcache(true, Autoloader::resolveFile($proxyDir, $proxyNamespace, $class));
98
99
                        break;
100
                    }
101
                };
102
            }
103
104
            $this->autoloader = Autoloader::register($dir, $namespace, $proxyGenerator);
105
        }
106
    }
107
108
    /**
109
     * {@inheritDoc}
110
     */
111
    public function shutdown()
112
    {
113
        if (null !== $this->autoloader) {
114
            spl_autoload_unregister($this->autoloader);
115
            $this->autoloader = null;
116
        }
117
118
        // Clear all entity managers to clear references to entities for GC
119 View Code Duplication
        if ($this->container->hasParameter('doctrine.entity_managers')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
120
            foreach ($this->container->getParameter('doctrine.entity_managers') as $id) {
121
                if (!method_exists($this->container, 'initialized') || $this->container->initialized($id)) {
122
                    $this->container->get($id)->clear();
123
                }
124
            }
125
        }
126
127
        // Close all connections to avoid reaching too many connections in the process when booting again later (tests)
128 View Code Duplication
        if ($this->container->hasParameter('doctrine.connections')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
129
            foreach ($this->container->getParameter('doctrine.connections') as $id) {
130
                if (!method_exists($this->container, 'initialized') || $this->container->initialized($id)) {
131
                    $this->container->get($id)->close();
132
                }
133
            }
134
        }
135
    }
136
137
    /**
138
     * {@inheritDoc}
139
     */
140
    public function registerCommands(Application $application)
141
    {
142
    }
143
}
144