Completed
Pull Request — master (#5860)
by Peter
10:08
created

getTargetEntityMetadata()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
/*
4
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
13
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
14
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
 *
16
 * This software consists of voluntary contributions made by many individuals
17
 * and is licensed under the MIT license. For more information, see
18
 * <http://www.doctrine-project.org>.
19
 */
20
21
namespace Doctrine\ORM\Cache\Persister\Collection;
22
23
use Doctrine\Common\Collections\Criteria;
24
use Doctrine\ORM\Cache\EntityCacheKey;
25
use Doctrine\ORM\Cache\CollectionCacheKey;
26
use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister;
27
use Doctrine\ORM\Persisters\Collection\CollectionPersister;
28
use Doctrine\ORM\PersistentCollection;
29
use Doctrine\ORM\EntityManagerInterface;
30
use Doctrine\ORM\Cache\Region;
31
use Doctrine\Common\Util\ClassUtils;
32
33
/**
34
 * @author Fabio B. Silva <[email protected]>
35
 * @author Guilherme Blanco <[email protected]>
36
 * @since 2.5
37
 */
38
abstract class AbstractCollectionPersister implements CachedCollectionPersister
39
{
40
     /**
41
     * @var \Doctrine\ORM\UnitOfWork
42
     */
43
    protected $uow;
44
45
    /**
46
     * @var \Doctrine\ORM\Mapping\ClassMetadataFactory
47
     */
48
    protected $metadataFactory;
49
50
    /**
51
     * @var \Doctrine\ORM\Persisters\Collection\CollectionPersister
52
     */
53
    protected $persister;
54
55
    /**
56
     * @var \Doctrine\ORM\Mapping\ClassMetadata
57
     */
58
    protected $sourceEntity;
59
60
    /**
61
     * @var \Doctrine\ORM\Mapping\ClassMetadata
62
     */
63
    protected $targetEntity;
64
65
    /**
66
     * @var array
67
     */
68
    protected $association;
69
70
     /**
71
     * @var array
72
     */
73
    protected $queuedCache = array();
74
75
    /**
76
     * @var \Doctrine\ORM\Cache\Region
77
     */
78
    protected $region;
79
80
    /**
81
     * @var string
82
     */
83
    protected $regionName;
84
85
    /**
86
     * @var \Doctrine\ORM\Cache\CollectionHydrator
87
     */
88
    protected $hydrator;
89
90
    /**
91
     * @var \Doctrine\ORM\Cache\Logging\CacheLogger
92
     */
93
    protected $cacheLogger;
94
95
    /**
96
     * @param \Doctrine\ORM\Persisters\Collection\CollectionPersister $persister   The collection persister that will be cached.
97
     * @param \Doctrine\ORM\Cache\Region                              $region      The collection region.
98
     * @param \Doctrine\ORM\EntityManagerInterface                    $em          The entity manager.
99
     * @param array                                                   $association The association mapping.
100
     */
101 114
    public function __construct(CollectionPersister $persister, Region $region, EntityManagerInterface $em, array $association)
102
    {
103 114
        $configuration  = $em->getConfiguration();
104 114
        $cacheConfig    = $configuration->getSecondLevelCacheConfiguration();
105 114
        $cacheFactory   = $cacheConfig->getCacheFactory();
106
107 114
        $this->region           = $region;
108 114
        $this->persister        = $persister;
109 114
        $this->association      = $association;
110 114
        $this->regionName       = $region->getName();
111 114
        $this->uow              = $em->getUnitOfWork();
112 114
        $this->metadataFactory  = $em->getMetadataFactory();
113 114
        $this->cacheLogger      = $cacheConfig->getCacheLogger();
114 114
        $this->hydrator         = $cacheFactory->buildCollectionHydrator($em, $association);
115 114
        $this->sourceEntity     = $em->getClassMetadata($association['sourceEntity']);
116 114
        $this->targetEntity     = $em->getClassMetadata($association['targetEntity']);
117 114
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122 61
    public function getCacheRegion()
123
    {
124 61
        return $this->region;
125
    }
126
127
    /**
128
     * {@inheritdoc}
129
     */
130
    public function getSourceEntityMetadata()
131
    {
132
        return $this->sourceEntity;
133
    }
134
135
    /**
136
     * {@inheritdoc}
137
     */
138
    public function getTargetEntityMetadata()
139
    {
140
        return $this->targetEntity;
141
    }
142
143
    /**
144
     * @param \Doctrine\ORM\PersistentCollection     $collection
145
     * @param \Doctrine\ORM\Cache\CollectionCacheKey $key
146
     *
147
     * @return \Doctrine\ORM\PersistentCollection|null
148
     */
149 16
    public function loadCollectionCache(PersistentCollection $collection, CollectionCacheKey $key)
150
    {
151 16
        if (($cache = $this->region->get($key)) === null) {
152 12
            return null;
153
        }
154
155 15
        if (($cache = $this->hydrator->loadCacheEntry($this->sourceEntity, $key, $cache, $collection)) === null) {
0 ignored issues
show
Compatibility introduced by
$cache of type object<Doctrine\ORM\Cache\CacheEntry> is not a sub-type of object<Doctrine\ORM\Cache\CollectionCacheEntry>. It seems like you assume a concrete implementation of the interface Doctrine\ORM\Cache\CacheEntry 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...
156
            return null;
157
        }
158
159 15
        return $cache;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $cache; (array) is incompatible with the return type declared by the interface Doctrine\ORM\Cache\Persi...er::loadCollectionCache of type Doctrine\ORM\PersistentCollection|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
160
    }
161
162
    /**
163
     * {@inheritdoc}
164
     */
165 42
    public function storeCollectionCache(CollectionCacheKey $key, $elements)
166
    {
167
        /* @var $targetPersister CachedEntityPersister */
168 42
        $associationMapping = $this->sourceEntity->associationMappings[$key->association];
169 42
        $targetPersister    = $this->uow->getEntityPersister($this->targetEntity->rootEntityName);
170 42
        $targetRegion       = $targetPersister->getCacheRegion();
171 42
        $targetHydrator     = $targetPersister->getEntityHydrator();
172
173
        // Only preserve ordering if association configured it
174 42
        if ( ! (isset($associationMapping['indexBy']) && $associationMapping['indexBy'])) {
175
            // Elements may be an array or a Collection
176 42
            $elements = array_values(is_array($elements) ? $elements : $elements->getValues());
177
        }
178
179 42
        $entry = $this->hydrator->buildCacheEntry($this->targetEntity, $key, $elements);
180
181 42
        foreach ($entry->identifiers as $index => $entityKey) {
182 42
            if ($targetRegion->contains($entityKey)) {
183 42
                continue;
184
            }
185
186 10
            $class      = $this->targetEntity;
187 10
            $className  = ClassUtils::getClass($elements[$index]);
188
189 10
            if ($className !== $this->targetEntity->name) {
190 2
                $class = $this->metadataFactory->getMetadataFor($className);
191
            }
192
193 10
            $entity       = $elements[$index];
194 10
            $entityEntry  = $targetHydrator->buildCacheEntry($class, $entityKey, $entity);
195
196 10
            $targetRegion->put($entityKey, $entityEntry);
197
        }
198
199 42
        $cached = $this->region->put($key, $entry);
200
201 42
        if ($this->cacheLogger && $cached) {
202 42
            $this->cacheLogger->collectionCachePut($this->regionName, $key);
203
        }
204 42
    }
205
206
    /**
207
     * {@inheritdoc}
208
     */
209 3
    public function contains(PersistentCollection $collection, $element)
210
    {
211 3
        return $this->persister->contains($collection, $element);
212
    }
213
214
    /**
215
     * {@inheritdoc}
216
     */
217 3
    public function containsKey(PersistentCollection $collection, $key)
218
    {
219 3
        return $this->persister->containsKey($collection, $key);
220
    }
221
222
    /**
223
     * {@inheritdoc}
224
     */
225 4
    public function count(PersistentCollection $collection)
226
    {
227 4
        $ownerId = $this->uow->getEntityIdentifier($collection->getOwner());
228 4
        $key     = new CollectionCacheKey($this->sourceEntity->rootEntityName, $this->association['fieldName'], $ownerId);
229 4
        $entry   = $this->region->get($key);
230
231 4
        if ($entry !== null) {
232 1
            return count($entry->identifiers);
0 ignored issues
show
Bug introduced by
Accessing identifiers on the interface Doctrine\ORM\Cache\CacheEntry suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
233
        }
234
235 4
        return $this->persister->count($collection);
236
    }
237
238
    /**
239
     * {@inheritdoc}
240
     */
241 3
    public function get(PersistentCollection $collection, $index)
242
    {
243 3
        return $this->persister->get($collection, $index);
244
    }
245
246
    /**
247
     * {@inheritdoc}
248
     */
249 3
    public function removeElement(PersistentCollection $collection, $element)
250
    {
251 3
        if ($persisterResult = $this->persister->removeElement($collection, $element)) {
252
            $this->evictCollectionCache($collection);
253
            $this->evictElementCache($this->sourceEntity->rootEntityName, $collection->getOwner());
254
            $this->evictElementCache($this->targetEntity->rootEntityName, $element);
255
        }
256
257 3
        return $persisterResult;
258
    }
259
260
    /**
261
     * {@inheritdoc}
262
     */
263 3
    public function slice(PersistentCollection $collection, $offset, $length = null)
264
    {
265 3
        return $this->persister->slice($collection, $offset, $length);
266
    }
267
268
    /**
269
     * {@inheritDoc}
270
     */
271
    public function loadCriteria(PersistentCollection $collection, Criteria $criteria)
272
    {
273
        return $this->persister->loadCriteria($collection, $criteria);
274
    }
275
276
    /**
277
     * Clears cache entries related to the current collection
278
     *
279
     * @param PersistentCollection $collection
280
     */
281
    protected function evictCollectionCache(PersistentCollection $collection)
282
    {
283
        $key = new CollectionCacheKey(
284
            $this->sourceEntity->rootEntityName,
285
            $this->association['fieldName'],
286
            $this->uow->getEntityIdentifier($collection->getOwner())
287
        );
288
289
        $this->region->evict($key);
290
291
        if ($this->cacheLogger) {
292
            $this->cacheLogger->collectionCachePut($this->regionName, $key);
293
        }
294
    }
295
296
    /**
297
     * @param string $targetEntity
298
     * @param object $element
299
     */
300
    protected function evictElementCache($targetEntity, $element)
301
    {
302
        /* @var $targetPersister CachedEntityPersister */
303
        $targetPersister = $this->uow->getEntityPersister($targetEntity);
304
        $targetRegion    = $targetPersister->getCacheRegion();
305
        $key             = new EntityCacheKey($targetEntity, $this->uow->getEntityIdentifier($element));
306
307
        $targetRegion->evict($key);
308
309
        if ($this->cacheLogger) {
310
            $this->cacheLogger->entityCachePut($targetRegion->getName(), $key);
311
        }
312
    }
313
}
314