Completed
Branch feature/pre-split (9269d3)
by Anton
05:27
created

DuplicateTrait   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 59
rs 10
c 0
b 0
f 0
wmc 3
lcom 1
cbo 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A deduplicate() 0 17 2
A duplicateCriteria() 0 4 1
1
<?php
2
/**
3
 * components
4
 *
5
 * @author    Wolfy-J
6
 */
7
namespace Spiral\ORM\Entities\Nodes\Traits;
8
9
/**
10
 * Trait provides ability for Node to ensure that given data is unique in selection.
11
 */
12
trait DuplicateTrait
13
{
14
    /**
15
     * @var string
16
     */
17
    private $primaryKey = '';
18
19
    /**
20
     * Aggregated duplicate data.
21
     *
22
     * @invisible
23
     * @var array
24
     */
25
    private $duplicates = [];
26
27
    /**
28
     * In many cases (for example if you have inload of HAS_MANY relation) record data can be
29
     * replicated by many result rows (duplicated). To prevent wrong data linking we have to
30
     * deduplicate such records. This is only internal loader functionality and required due data
31
     * tree are built using php references.
32
     *
33
     * Method will return true if data is unique handled before and false in opposite case.
34
     * Provided data array will be automatically linked with it's unique state using references.
35
     *
36
     * @param array $data Reference to parsed record data, reference will be pointed to valid and
37
     *                    existed data segment if such data was already parsed.
38
     *
39
     * @return bool
40
     */
41
    protected function deduplicate(array &$data): bool
42
    {
43
        $criteria = $this->duplicateCriteria($data);
44
45
        if (isset($this->duplicates[$criteria])) {
46
            //Duplicate is presented, let's reduplicate
47
            $data = $this->duplicates[$criteria];
48
49
            //Duplicate is presented
50
            return false;
51
        }
52
53
        //Remember record to prevent future duplicates
54
        $this->duplicates[$criteria] = &$data;
55
56
        return true;
57
    }
58
59
    /**
60
     * Calculate duplication criteria.
61
     *
62
     * @param array $data
63
     *
64
     * @return mixed
65
     */
66
    protected function duplicateCriteria(array &$data)
67
    {
68
        return $data[$this->primaryKey];
69
    }
70
}