Completed
Pull Request — master (#658)
by Magnus
02:24
created

DoctrineBundle::build()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.4285
cc 2
eloc 8
nc 2
nop 1
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\Bundle\DoctrineBundle\DependencyInjection\Compiler\RepositoryAliasPass;
24
use Doctrine\ORM\Proxy\Autoloader;
25
use Symfony\Component\Console\Application;
26
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
27
use Symfony\Component\DependencyInjection\ContainerBuilder;
28
use Symfony\Component\DependencyInjection\IntrospectableContainerInterface;
29
use Symfony\Component\HttpKernel\Bundle\Bundle;
30
use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\DoctrineValidationPass;
31
use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass;
32
use Symfony\Bridge\Doctrine\DependencyInjection\Security\UserProvider\EntityFactory;
33
34
/**
35
 * Bundle.
36
 *
37
 * @author Fabien Potencier <[email protected]>
38
 * @author Jonathan H. Wage <[email protected]>
39
 */
40
class DoctrineBundle extends Bundle
41
{
42
    private $autoloader;
43
44
    /**
45
     * {@inheritDoc}
46
     */
47
    public function build(ContainerBuilder $container)
48
    {
49
        parent::build($container);
50
51
        $container->addCompilerPass(new RegisterEventListenersAndSubscribersPass('doctrine.connections', 'doctrine.dbal.%s_connection.event_manager', 'doctrine'), PassConfig::TYPE_BEFORE_OPTIMIZATION);
52
53
        if ($container->hasExtension('security')) {
54
            $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...
55
        }
56
57
        $container->addCompilerPass(new DoctrineValidationPass('orm'));
58
        $container->addCompilerPass(new EntityListenerPass());
59
        $container->addCompilerPass(new RepositoryAliasPass());
60
    }
61
62
    /**
63
     * {@inheritDoc}
64
     */
65
    public function boot()
66
    {
67
        // Register an autoloader for proxies to avoid issues when unserializing them
68
        // when the ORM is used.
69
        if ($this->container->hasParameter('doctrine.orm.proxy_namespace')) {
70
            $namespace = $this->container->getParameter('doctrine.orm.proxy_namespace');
71
            $dir = $this->container->getParameter('doctrine.orm.proxy_dir');
72
            $proxyGenerator = null;
73
74
            if ($this->container->getParameter('doctrine.orm.auto_generate_proxy_classes')) {
75
                // See https://github.com/symfony/symfony/pull/3419 for usage of references
76
                $container = &$this->container;
77
78
                $proxyGenerator = function ($proxyDir, $proxyNamespace, $class) use (&$container) {
79
                    $originalClassName = ClassUtils::getRealClass($class);
80
                    /** @var $registry Registry */
81
                    $registry = $container->get('doctrine');
82
83
                    // Tries to auto-generate the proxy file
84
                    /** @var $em \Doctrine\ORM\EntityManager */
85
                    foreach ($registry->getManagers() as $em) {
86
                        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...
87
                            continue;
88
                        }
89
90
                        $metadataFactory = $em->getMetadataFactory();
91
92
                        if ($metadataFactory->isTransient($originalClassName)) {
93
                            continue;
94
                        }
95
96
                        $classMetadata = $metadataFactory->getMetadataFor($originalClassName);
97
98
                        $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...
99
100
                        clearstatcache(true, Autoloader::resolveFile($proxyDir, $proxyNamespace, $class));
101
102
                        break;
103
                    }
104
                };
105
            }
106
107
            $this->autoloader = Autoloader::register($dir, $namespace, $proxyGenerator);
108
        }
109
    }
110
111
    /**
112
     * {@inheritDoc}
113
     */
114
    public function shutdown()
115
    {
116
        if (null !== $this->autoloader) {
117
            spl_autoload_unregister($this->autoloader);
118
            $this->autoloader = null;
119
        }
120
121
        // Clear all entity managers to clear references to entities for GC
122 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...
123
            foreach ($this->container->getParameter('doctrine.entity_managers') as $id) {
124
                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...
125
                    $this->container->get($id)->clear();
126
                }
127
            }
128
        }
129
130
        // Close all connections to avoid reaching too many connections in the process when booting again later (tests)
131 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...
132
            foreach ($this->container->getParameter('doctrine.connections') as $id) {
133
                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...
134
                    $this->container->get($id)->close();
135
                }
136
            }
137
        }
138
    }
139
140
    /**
141
     * {@inheritDoc}
142
     */
143
    public function registerCommands(Application $application)
144
    {
145
        // Use the default logic when the ORM is available.
146
        // This avoids listing all ORM commands by hand.
147
        if (class_exists('Doctrine\\ORM\\Version')) {
148
            parent::registerCommands($application);
149
150
            return;
151
        }
152
153
        // Register only the DBAL commands if the ORM is not available.
154
        $application->add(new CreateDatabaseDoctrineCommand());
155
        $application->add(new DropDatabaseDoctrineCommand());
156
        $application->add(new RunSqlDoctrineCommand());
157
        $application->add(new ImportDoctrineCommand());
158
    }
159
}
160