Completed
Pull Request — master (#615)
by Filippo
14:02 queued 03:29
created

AllowRemoveByValue   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 66.67%

Importance

Changes 0
Metric Value
wmc 4
c 0
b 0
f 0
lcom 1
cbo 3
dl 0
loc 38
ccs 12
cts 18
cp 0.6667
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B hydrate() 0 32 4
1
<?php
2
3
namespace DoctrineModule\Stdlib\Hydrator\Strategy;
4
5
use Doctrine\Common\Collections\Collection;
6
use LogicException;
7
use Doctrine\Common\Collections\ArrayCollection;
8
9
/**
10
 * When this strategy is used for Collections, if the new collection does not contain elements that are present in
11
 * the original collection, then this strategy remove elements from the original collection. For instance, if the
12
 * collection initially contains elements A and B, and that the new collection contains elements B and C, then the
13
 * final collection will contain elements B and C (while element A will be asked to be removed).
14
 *
15
 * This strategy is by value, this means it will use the public API (in this case, adder and remover)
16
 *
17
 * @license MIT
18
 * @link    http://www.doctrine-project.org/
19
 * @since   0.7.0
20
 * @author  Michael Gallego <[email protected]>
21
 */
22
class AllowRemoveByValue extends AbstractCollectionStrategy
23
{
24
    /**
25
     * {@inheritDoc}
26
     */
27 10
    public function hydrate($value)
28
    {
29
        // AllowRemove strategy need "adder" and "remover"
30 10
        $adder   = 'add' . ucfirst($this->collectionName);
31 10
        $remover = 'remove' . ucfirst($this->collectionName);
32
33 10
        if (! method_exists($this->object, $adder) || ! method_exists($this->object, $remover)) {
34
            throw new LogicException(
35
                sprintf(
36
                    'AllowRemove strategy for DoctrineModule hydrator requires both %s and %s to be defined in %s
37
                     entity domain code, but one or both seem to be missing',
38
                    $adder,
39
                    $remover,
40
                    get_class($this->object)
41
                )
42
            );
43
        }
44
45 10
        $collection = $this->getCollectionFromObjectByValue();
46
47 10
        if ($collection instanceof Collection) {
48 9
            $collection = $collection->toArray();
49
        }
50
51 10
        $toAdd    = new ArrayCollection(array_udiff($value, $collection, [$this, 'compareObjects']));
52 10
        $toRemove = new ArrayCollection(array_udiff($collection, $value, [$this, 'compareObjects']));
53
54 10
        $this->object->$adder($toAdd);
55 10
        $this->object->$remover($toRemove);
56
57 10
        return $collection;
58
    }
59
}
60