Completed
Pull Request — master (#905)
by Gabriel
01:56
created

DoctrineBundle::build()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 14
rs 9.7998
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Doctrine\Bundle\DoctrineBundle;
4
5
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\EntityListenerPass;
6
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\ServiceRepositoryCompilerPass;
7
use Doctrine\Common\Util\ClassUtils;
8
use Doctrine\ORM\EntityManager;
9
use Doctrine\ORM\Proxy\Autoloader;
10
use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\DoctrineValidationPass;
11
use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass;
12
use Symfony\Bridge\Doctrine\DependencyInjection\Security\UserProvider\EntityFactory;
13
use Symfony\Component\Console\Application;
14
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
15
use Symfony\Component\DependencyInjection\ContainerBuilder;
16
use Symfony\Component\HttpKernel\Bundle\Bundle;
17
18
/**
19
 * Bundle.
20
 */
21
class DoctrineBundle extends Bundle
22
{
23
    /** @var callable|null */
24
    private $autoloader;
25
26
    /**
27
     * {@inheritDoc}
28
     */
29
    public function build(ContainerBuilder $container)
30
    {
31
        parent::build($container);
32
33
        $container->addCompilerPass(new RegisterEventListenersAndSubscribersPass('doctrine.connections', 'doctrine.dbal.%s_connection.event_manager', 'doctrine'), PassConfig::TYPE_BEFORE_OPTIMIZATION);
34
35
        if ($container->hasExtension('security')) {
36
            $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...
37
        }
38
39
        $container->addCompilerPass(new DoctrineValidationPass('orm'));
40
        $container->addCompilerPass(new EntityListenerPass());
41
        $container->addCompilerPass(new ServiceRepositoryCompilerPass());
42
    }
43
44
    /**
45
     * {@inheritDoc}
46
     */
47
    public function boot()
48
    {
49
        // Register an autoloader for proxies to avoid issues when unserializing them
50
        // when the ORM is used.
51
        if (! $this->container->hasParameter('doctrine.orm.proxy_namespace')) {
52
            return;
53
        }
54
55
        $namespace      = $this->container->getParameter('doctrine.orm.proxy_namespace');
56
        $dir            = $this->container->getParameter('doctrine.orm.proxy_dir');
57
        $proxyGenerator = null;
58
59
        if ($this->container->getParameter('doctrine.orm.auto_generate_proxy_classes')) {
60
            // See https://github.com/symfony/symfony/pull/3419 for usage of references
61
            $container = &$this->container;
62
63
            $proxyGenerator = static function ($proxyDir, $proxyNamespace, $class) use (&$container) {
64
                $originalClassName = ClassUtils::getRealClass($class);
65
                /** @var Registry $registry */
66
                $registry = $container->get('doctrine');
67
68
                // Tries to auto-generate the proxy file
69
                /** @var EntityManager $em */
70
                foreach ($registry->getManagers() as $em) {
71
                    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...
72
                        continue;
73
                    }
74
75
                    $metadataFactory = $em->getMetadataFactory();
76
77
                    if ($metadataFactory->isTransient($originalClassName)) {
78
                        continue;
79
                    }
80
81
                    $classMetadata = $metadataFactory->getMetadataFor($originalClassName);
82
83
                    $em->getProxyFactory()->generateProxyClasses([$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...
84
85
                    clearstatcache(true, Autoloader::resolveFile($proxyDir, $proxyNamespace, $class));
86
87
                    break;
88
                }
89
            };
90
        }
91
92
        $this->autoloader = Autoloader::register($dir, $namespace, $proxyGenerator);
93
    }
94
95
    /**
96
     * {@inheritDoc}
97
     */
98
    public function shutdown()
99
    {
100
        if ($this->autoloader !== null) {
101
            spl_autoload_unregister($this->autoloader);
102
            $this->autoloader = null;
103
        }
104
105
        // Clear all entity managers to clear references to entities for GC
106
        if ($this->container->hasParameter('doctrine.entity_managers')) {
107 View Code Duplication
            foreach ($this->container->getParameter('doctrine.entity_managers') as $id) {
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...
108
                if (method_exists($this->container, 'initialized') && ! $this->container->initialized($id)) {
109
                    continue;
110
                }
111
112
                $this->container->get($id)->clear();
113
            }
114
        }
115
116
        // Close all connections to avoid reaching too many connections in the process when booting again later (tests)
117
        if (! $this->container->hasParameter('doctrine.connections')) {
118
            return;
119
        }
120
121 View Code Duplication
        foreach ($this->container->getParameter('doctrine.connections') as $id) {
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...
122
            if (method_exists($this->container, 'initialized') && ! $this->container->initialized($id)) {
123
                continue;
124
            }
125
126
            $this->container->get($id)->close();
127
        }
128
    }
129
130
    /**
131
     * {@inheritDoc}
132
     */
133
    public function registerCommands(Application $application)
134
    {
135
    }
136
}
137