Completed
Pull Request — master (#620)
by
unknown
02:48
created

DoctrineBundle::shutdown()   D

Complexity

Conditions 10
Paths 16

Size

Total Lines 25
Code Lines 12

Duplication

Lines 14
Ratio 56 %

Importance

Changes 0
Metric Value
dl 14
loc 25
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 12
nc 16
nop 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\DependencyInjection\IntrospectableContainerInterface;
28
use Symfony\Component\HttpKernel\Bundle\Bundle;
29
use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\DoctrineValidationPass;
30
use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass;
31
use Symfony\Bridge\Doctrine\DependencyInjection\Security\UserProvider\EntityFactory;
32
33
/**
34
 * Bundle.
35
 *
36
 * @author Fabien Potencier <[email protected]>
37
 * @author Jonathan H. Wage <[email protected]>
38
 */
39
class DoctrineBundle extends Bundle
40
{
41
    private $autoloader;
42
43
    /**
44
     * {@inheritDoc}
45
     */
46
    public function build(ContainerBuilder $container)
47
    {
48
        parent::build($container);
49
50
        $container->addCompilerPass(new RegisterEventListenersAndSubscribersPass('doctrine.connections', 'doctrine.dbal.%s_connection.event_manager', 'doctrine'), PassConfig::TYPE_BEFORE_OPTIMIZATION);
51
52
        if ($container->hasExtension('security')) {
53
            $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...
54
        }
55
56
        $container->addCompilerPass(new DoctrineValidationPass('orm'));
57
        $container->addCompilerPass(new EntityListenerPass());
58
    }
59
60
    /**
61
     * {@inheritDoc}
62
     */
63
    public function boot()
64
    {
65
        // Register an autoloader for proxies to avoid issues when unserializing them
66
        // when the ORM is used.
67
        if ($this->container->hasParameter('doctrine.orm.proxy_namespace')) {
68
            $namespace = $this->container->getParameter('doctrine.orm.proxy_namespace');
69
            $dir = $this->container->getParameter('doctrine.orm.proxy_dir');
70
            $proxyGenerator = null;
71
72
            if ($this->container->getParameter('doctrine.orm.auto_generate_proxy_classes')) {
73
                // See https://github.com/symfony/symfony/pull/3419 for usage of references
74
                $container = &$this->container;
75
76
                $proxyGenerator = function ($proxyDir, $proxyNamespace, $class) use (&$container) {
77
                    $originalClassName = ClassUtils::getRealClass($class);
78
                    /** @var $registry Registry */
79
                    $registry = $container->get('doctrine');
80
81
                    // Tries to auto-generate the proxy file
82
                    /** @var $em \Doctrine\ORM\EntityManager */
83
                    foreach ($registry->getManagers() as $em) {
84
                        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...
85
                            continue;
86
                        }
87
88
                        $metadataFactory = $em->getMetadataFactory();
89
90
                        if ($metadataFactory->isTransient($originalClassName)) {
91
                            continue;
92
                        }
93
94
                        $classMetadata = $metadataFactory->getMetadataFor($originalClassName);
95
96
                        $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...
97
98
                        clearstatcache(true, Autoloader::resolveFile($proxyDir, $proxyNamespace, $class));
99
100
                        break;
101
                    }
102
                };
103
            }
104
105
            $this->autoloader = Autoloader::register($dir, $namespace, $proxyGenerator);
106
        }
107
    }
108
109
    /**
110
     * {@inheritDoc}
111
     */
112
    public function shutdown()
113
    {
114
        if (null !== $this->autoloader) {
115
            spl_autoload_unregister($this->autoloader);
116
            $this->autoloader = null;
117
        }
118
119
        // Clear all entity managers to clear references to entities for GC
120 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...
121
            foreach ($this->container->getParameter('doctrine.entity_managers') as $id) {
122
                if (!$this->container instanceof IntrospectableContainerInterface || $this->container->initialized($id)) {
0 ignored issues
show
Bug introduced by
The class Symfony\Component\Depend...tableContainerInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
123
                    $this->container->get($id)->clear();
124
                }
125
            }
126
        }
127
128
        // Close all connections to avoid reaching too many connections in the process when booting again later (tests)
129 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...
130
            foreach ($this->container->getParameter('doctrine.connections') as $id) {
131
                if (!$this->container instanceof IntrospectableContainerInterface || $this->container->initialized($id)) {
0 ignored issues
show
Bug introduced by
The class Symfony\Component\Depend...tableContainerInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
132
                    $this->container->get($id)->close();
133
                }
134
            }
135
        }
136
    }
137
138
    /**
139
     * {@inheritDoc}
140
     */
141
    public function registerCommands(Application $application)
142
    {
143
        // Use the default logic when the ORM is available.
144
        // This avoids listing all ORM commands by hand.
145
        if (class_exists('Doctrine\\ORM\\Version')) {
146
            parent::registerCommands($application);
147
148
            return;
149
        }
150
151
        // Register only the DBAL commands if the ORM is not available.
152
        $application->add(new CreateDatabaseDoctrineCommand());
153
        $application->add(new DropDatabaseDoctrineCommand());
154
        $application->add(new RunSqlDoctrineCommand());
155
        $application->add(new ImportDoctrineCommand());
156
    }
157
}
158