Completed
Push — master ( d5e46b...77750d )
by Matthew
16:31
created

GridSourceManager::setReflectionAllowedEntities()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 3
nc 4
nop 1
1
<?php
2
3
namespace Dtc\GridBundle\Manager;
4
5
use Doctrine\Common\Annotations\Reader;
6
use Doctrine\Common\Persistence\AbstractManagerRegistry;
7
use Doctrine\Common\Persistence\ObjectManager;
8
use Doctrine\ODM\MongoDB\DocumentManager;
9
use Doctrine\ORM\EntityManager;
10
use Doctrine\ORM\EntityManagerInterface;
11
use Dtc\GridBundle\Grid\Source\DocumentGridSource;
12
use Dtc\GridBundle\Grid\Source\EntityGridSource;
13
use Dtc\GridBundle\Grid\Source\GridSourceInterface;
14
15
class GridSourceManager
16
{
17
    protected $sourcesByClass;
18
    protected $sourcesByName;
19
20
    protected $reader;
21
    protected $cacheDir;
22
    protected $debug;
23
24
    /** @var AbstractManagerRegistry */
25
    protected $registry;
26
27
    /** @var AbstractManagerRegistry */
28
    protected $mongodbRegistry;
29
30
    protected $customManagerMappings;
31
32
    protected $extraGridSources;
33
34
    /**
35
     * @var array|null Null means all entities allowed, empty array means no entities allowed
36
     */
37
    protected $reflectionAllowedEntities;
38
39
    /**
40
     * GridSourceManager constructor.
41
     *
42
     * @param string $cacheDir
43
     * @param bool   $debug
44
     */
45
    public function __construct(Reader $reader, $cacheDir, $debug = false)
46
    {
47
        $this->cacheDir = $cacheDir;
48
        $this->reader = $reader;
49
        $this->reflectionAllowedEntities = [];
50
        $this->debug = $debug;
51
        $this->sources = array();
0 ignored issues
show
Bug introduced by
The property sources does not seem to exist. Did you mean sourcesByClass?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
52
    }
53
54
    /**
55
     * @param array|string $allowedEntities Array of allowed entities or string '*' to allow all entities. Use empty array to specify no entities allowed for reflection.
56
     */
57
    public function setReflectionAllowedEntities($allowedEntities) {
58
        $this->reflectionAllowedEntities = is_array($allowedEntities) ? array_flip($allowedEntities) : ('*' === $allowedEntities ? null : []);
59
    }
60
61
    public function setRegistry(AbstractManagerRegistry $registry)
62
    {
63
        $this->registry = $registry;
64
    }
65
66
    public function setMongodbRegistry(AbstractManagerRegistry $registry)
67
    {
68
        $this->mongodbRegistry = $registry;
69
    }
70
71
    /**
72
     * @return string
73
     */
74
    protected function getCacheDir()
75
    {
76
        return $this->cacheDir;
77
    }
78
79
    /**
80
     * @return bool
81
     */
82
    protected function getDebug()
83
    {
84
        return $this->debug;
85
    }
86
87
    public function add($id, GridSourceInterface $gridSource)
88
    {
89
        $this->extraGridSources[$id] = $gridSource;
90
    }
91
92
    /**
93
     * @param ObjectManager $manager
94
     * @param $entityOrDocument
95
     *
96
     * @return DocumentGridSource|EntityGridSource|null
97
     */
98
    protected function getGridSource($manager, $entityOrDocument)
99
    {
100
        $repository = $manager->getRepository($entityOrDocument);
101
        if ($repository) {
102
            $className = $repository->getClassName();
103
            $classMetadata = $manager->getClassMetadata($className);
104
            $name = $classMetadata->getName();
105
            $reflectionClass = $classMetadata->getReflectionClass();
106
            $annotation = $this->reader->getClassAnnotation($reflectionClass, 'Dtc\GridBundle\Annotation\Grid');
107
            if (!$annotation && !isset($this->reflectionAllowedEntities[$entityOrDocument]) && null !== $this->reflectionAllowedEntities) {
108
                throw new \Exception("GridSource requested for '$entityOrDocument' but no Grid annotation found");
109
            }
110
            if ($manager instanceof EntityManagerInterface) {
111
                $gridSource = new EntityGridSource($manager, $name);
0 ignored issues
show
Compatibility introduced by
$manager of type object<Doctrine\ORM\EntityManagerInterface> is not a sub-type of object<Doctrine\ORM\EntityManager>. It seems like you assume a concrete implementation of the interface Doctrine\ORM\EntityManagerInterface 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...
112
            } else {
113
                $gridSource = new DocumentGridSource($manager, $name);
0 ignored issues
show
Compatibility introduced by
$manager of type object<Doctrine\Common\Persistence\ObjectManager> is not a sub-type of object<Doctrine\ODM\MongoDB\DocumentManager>. It seems like you assume a concrete implementation of the interface Doctrine\Common\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...
114
            }
115
            $gridSource->setAnnotationReader($this->reader);
116
            $gridSource->setCacheDir($this->cacheDir);
117
118
            $gridSource->setDebug($this->debug);
119
            $gridSource->autoDiscoverColumns();
120
            $this->sourcesByName[$name] = $gridSource;
121
            $this->sourcesByClass[$className] = $gridSource;
122
            $gridSource->setId($className);
123
124
            return $gridSource;
125
        }
126
127
        return null;
128
    }
129
130
    /**
131
     * Get a gridsource.
132
     *
133
     * @param string                             $id      Entity or Document
0 ignored issues
show
Bug introduced by
There is no parameter named $id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
134
     * @param EntityManager|DocumentManager|null $manager (optional) Entity or Document manager to use (overrides default)
0 ignored issues
show
Bug introduced by
There is no parameter named $manager. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
135
     *
136
     * @return GridSourceInterface|null
137
     *
138
     * @throws \Exception
139
     */
140
    public function get($entityOrDocumentNameOrId)
141
    {
142
        // @Support legacy method of adding/removing grid sources
143
        if (isset($this->extraGridSources[$entityOrDocumentNameOrId])) {
144
            return $this->extraGridSources[$entityOrDocumentNameOrId];
145
        }
146
147
        if (isset($this->sourcesByClass[$entityOrDocumentNameOrId])) {
148
            return $this->sourcesByClass[$entityOrDocumentNameOrId];
149
        }
150
151
        if (isset($this->sourcesByName[$entityOrDocumentNameOrId])) {
152
            return $this->sourcesByName[$entityOrDocumentNameOrId];
153
        }
154
155
        try {
156 View Code Duplication
            if ($this->registry && ($manager = $this->registry->getManagerForClass($entityOrDocumentNameOrId)) &&
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...
157
                $gridSource = $this->getGridSource($manager, $entityOrDocumentNameOrId)) {
158
                return $gridSource;
159
            }
160
        } catch (\ReflectionException $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
161
        }
162
163 View Code Duplication
        if ($this->mongodbRegistry && ($manager = $this->mongodbRegistry->getManagerForClass($entityOrDocumentNameOrId)) &&
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...
164
            $gridSource = $this->getGridSource($manager, $entityOrDocumentNameOrId)) {
165
            return $gridSource;
166
        }
167
        throw new \Exception("Can't find grid source for $entityOrDocumentNameOrId");
168
    }
169
170
    public function all()
171
    {
172
        return isset($this->sourcesByName) ? array_values($this->sourcesByName) : [];
173
    }
174
175
    public function setEntityManager(EntityManager $entityManager)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $entityManager. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
176
    {
177
        $this->entityManager = $entityManager;
0 ignored issues
show
Bug introduced by
The property entityManager does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
178
    }
179
180
    public function setDocumentManager(DocumentManager $documentManager)
181
    {
182
        $this->documentManager = $documentManager;
0 ignored issues
show
Bug introduced by
The property documentManager does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
183
    }
184
}
185