DisconnectedMetadataFactory   A
last analyzed

Complexity

Total Complexity 21

Size/Duplication

Total Lines 172
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 6
dl 0
loc 172
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getBundleMetadata() 0 15 2
A getClassMetadata() 0 11 2
A getNamespaceMetadata() 0 11 2
A findNamespaceAndPathForMetadata() 0 19 3
A getBasePathForClass() 0 12 2
A getMetadataForNamespace() 0 13 3
A getMetadataForClass() 0 13 3
A getAllMetadata() 0 13 3
1
<?php
2
3
namespace Doctrine\Bundle\DoctrineBundle\Mapping;
4
5
use Doctrine\ORM\Mapping\ClassMetadata;
6
use Doctrine\ORM\Mapping\MappingException;
7
use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory;
8
use Doctrine\Persistence\ManagerRegistry;
9
use ReflectionClass;
10
use RuntimeException;
11
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
12
13
/**
14
 * This class provides methods to access Doctrine entity class metadata for a
15
 * given bundle, namespace or entity class, for generation purposes
16
 */
17
class DisconnectedMetadataFactory
18
{
19
    /** @var ManagerRegistry */
20
    private $registry;
21
22
    /**
23
     * @param ManagerRegistry $registry A ManagerRegistry instance
24
     */
25
    public function __construct(ManagerRegistry $registry)
26
    {
27
        $this->registry = $registry;
28
    }
29
30
    /**
31
     * Gets the metadata of all classes of a bundle.
32
     *
33
     * @param BundleInterface $bundle A BundleInterface instance
34
     *
35
     * @return ClassMetadataCollection A ClassMetadataCollection instance
36
     *
37
     * @throws RuntimeException When bundle does not contain mapped entities.
38
     */
39
    public function getBundleMetadata(BundleInterface $bundle)
40
    {
41
        $namespace = $bundle->getNamespace();
42
        $metadata  = $this->getMetadataForNamespace($namespace);
43
        if (! $metadata->getMetadata()) {
44
            throw new RuntimeException(sprintf('Bundle "%s" does not contain any mapped entities.', $bundle->getName()));
45
        }
46
47
        $path = $this->getBasePathForClass($bundle->getName(), $bundle->getNamespace(), $bundle->getPath());
48
49
        $metadata->setPath($path);
50
        $metadata->setNamespace($bundle->getNamespace());
51
52
        return $metadata;
53
    }
54
55
    /**
56
     * Gets the metadata of a class.
57
     *
58
     * @param string $class A class name
59
     * @param string $path  The path where the class is stored (if known)
0 ignored issues
show
Documentation introduced by
Should the type for parameter $path not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
60
     *
61
     * @return ClassMetadataCollection A ClassMetadataCollection instance
62
     *
63
     * @throws MappingException When class is not valid entity or mapped superclass.
64
     */
65
    public function getClassMetadata($class, $path = null)
66
    {
67
        $metadata = $this->getMetadataForClass($class);
68
        if (! $metadata->getMetadata()) {
69
            throw MappingException::classIsNotAValidEntityOrMappedSuperClass($class);
70
        }
71
72
        $this->findNamespaceAndPathForMetadata($metadata, $path);
73
74
        return $metadata;
75
    }
76
77
    /**
78
     * Gets the metadata of all classes of a namespace.
79
     *
80
     * @param string $namespace A namespace name
81
     * @param string $path      The path where the class is stored (if known)
0 ignored issues
show
Documentation introduced by
Should the type for parameter $path not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
82
     *
83
     * @return ClassMetadataCollection A ClassMetadataCollection instance
84
     *
85
     * @throws RuntimeException When namespace not contain mapped entities.
86
     */
87
    public function getNamespaceMetadata($namespace, $path = null)
88
    {
89
        $metadata = $this->getMetadataForNamespace($namespace);
90
        if (! $metadata->getMetadata()) {
91
            throw new RuntimeException(sprintf('Namespace "%s" does not contain any mapped entities.', $namespace));
92
        }
93
94
        $this->findNamespaceAndPathForMetadata($metadata, $path);
95
96
        return $metadata;
97
    }
98
99
    /**
100
     * Find and configure path and namespace for the metadata collection.
101
     *
102
     * @param string|null $path
103
     *
104
     * @throws RuntimeException When unable to determine the path.
105
     */
106
    public function findNamespaceAndPathForMetadata(ClassMetadataCollection $metadata, $path = null)
107
    {
108
        $all = $metadata->getMetadata();
109
        if (class_exists($all[0]->name)) {
110
            $r    = new ReflectionClass($all[0]->name);
111
            $path = $this->getBasePathForClass($r->getName(), $r->getNamespaceName(), dirname($r->getFilename()));
0 ignored issues
show
Bug introduced by
Consider using $r->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
112
            $ns   = $r->getNamespaceName();
113
        } elseif ($path) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $path of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
114
            // Get namespace by removing the last component of the FQCN
115
            $nsParts = explode('\\', $all[0]->name);
116
            array_pop($nsParts);
117
            $ns = implode('\\', $nsParts);
118
        } else {
119
            throw new RuntimeException(sprintf('Unable to determine where to save the "%s" class (use the --path option).', $all[0]->name));
120
        }
121
122
        $metadata->setPath($path);
123
        $metadata->setNamespace($ns);
124
    }
125
126
    /**
127
     * Get a base path for a class
128
     *
129
     * @throws RuntimeException When base path not found.
130
     */
131
    private function getBasePathForClass(string $name, string $namespace, string $path) : string
132
    {
133
        $namespace   = str_replace('\\', '/', $namespace);
134
        $search      = str_replace('\\', '/', $path);
135
        $destination = str_replace('/' . $namespace, '', $search, $c);
136
137
        if ($c !== 1) {
138
            throw new RuntimeException(sprintf('Can\'t find base path for "%s" (path: "%s", destination: "%s").', $name, $path, $destination));
139
        }
140
141
        return $destination;
142
    }
143
144
    private function getMetadataForNamespace(string $namespace) : ClassMetadataCollection
145
    {
146
        $metadata = [];
147
        foreach ($this->getAllMetadata() as $m) {
148
            if (strpos($m->name, $namespace) !== 0) {
149
                continue;
150
            }
151
152
            $metadata[] = $m;
153
        }
154
155
        return new ClassMetadataCollection($metadata);
156
    }
157
158
    private function getMetadataForClass(string $entity) : ClassMetadataCollection
159
    {
160
        foreach ($this->registry->getManagers() as $em) {
161
            $cmf = new DisconnectedClassMetadataFactory();
162
            $cmf->setEntityManager($em);
0 ignored issues
show
Compatibility introduced by
$em of type object<Doctrine\Persistence\ObjectManager> is not a sub-type of object<Doctrine\ORM\EntityManagerInterface>. It seems like you assume a child interface of the interface Doctrine\Persistence\ObjectManager to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
163
164
            if (! $cmf->isTransient($entity)) {
165
                return new ClassMetadataCollection([$cmf->getMetadataFor($entity)]);
0 ignored issues
show
Documentation introduced by
array($cmf->getMetadataFor($entity)) is of type array<integer,object<Doc...ping\\ClassMetadata>"}>, but the function expects a array<integer,object<Doc...Mapping\ClassMetadata>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
166
            }
167
        }
168
169
        return new ClassMetadataCollection([]);
170
    }
171
172
    /**
173
     * @return ClassMetadata[]
174
     */
175
    private function getAllMetadata() : array
176
    {
177
        $metadata = [];
178
        foreach ($this->registry->getManagers() as $em) {
179
            $cmf = new DisconnectedClassMetadataFactory();
180
            $cmf->setEntityManager($em);
0 ignored issues
show
Compatibility introduced by
$em of type object<Doctrine\Persistence\ObjectManager> is not a sub-type of object<Doctrine\ORM\EntityManagerInterface>. It seems like you assume a child interface of the interface Doctrine\Persistence\ObjectManager to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
181
            foreach ($cmf->getAllMetadata() as $m) {
182
                $metadata[] = $m;
183
            }
184
        }
185
186
        return $metadata;
187
    }
188
}
189