Completed
Pull Request — master (#1032)
by Andreas
01:35
created

DoctrineBundle.php (3 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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