CollectionUpdaterTrait   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 1
dl 0
loc 45
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B updateCollection() 0 33 6
1
<?php
2
3
namespace AurimasNiekis\DoctrineCollectionUpdater;
4
5
use Doctrine\Common\Collections\Collection;
6
7
/**
8
 * Trait CollectionUpdaterTrait
9
 *
10
 * @package AurimasNiekis\DoctrineCollectionUpdater
11
 * @author  Aurimas Niekis <[email protected]>
12
 */
13
trait CollectionUpdaterTrait
14
{
15
    /**
16
     * @param Collection    $collection        Collection to update
17
     * @param array         $input             Array of comparators for e.g. id's
18
     * @param callable      $extractComparator A callback to extract comparator from Element
19
     * @param callable      $createElement     A callback to create new element for Collection
20
     * @param callable|null $removeElement     A callback to remove an element for Collection
21
     *
22
     * @return Collection
23
     */
24 3
    public function updateCollection(
25
        Collection $collection,
26
        array $input,
27
        callable $extractComparator,
28
        callable $createElement,
29
        callable $removeElement = null
30
    ): Collection {
31 3
        $existingElements = [];
32
33 3
        foreach ($collection as $element) {
34 2
            $key = $extractComparator($element);
35
36 2
            $existingElements[$key] = $element;
37
        }
38
39 3
        foreach ($input as $value) {
40 2
            if (true !== isset($existingElements[$value])) {
41 2
                $collection->add($createElement($value));
42
            }
43
44 2
            unset($existingElements[$value]);
45
        }
46
47 3
        foreach ($existingElements as $key => $element) {
48 2
            $collection->removeElement($element);
49
50 2
            if (null !== $removeElement) {
51 2
                $removeElement($element);
52
            }
53
        }
54
55 3
        return $collection;
56
    }
57
}