DuplicateTrait::deduplicate()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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