Passed
Pull Request — master (#50)
by Anton
04:19
created

DuplicateTrait::duplicateCriteria()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Cycle DataMapper ORM
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Cycle\ORM\Parser\Traits;
13
14
/**
15
 * Trait provides ability for Node to ensure that given data is unique in selection. Primary key
16
 * would be used to tie duplicate nodes together.
17
 */
18
trait DuplicateTrait
19
{
20
    /** @var string @internal */
21
    protected $duplicateCriteria;
22
23
    /** @var array @internal */
24
    protected $duplicates = [];
25
26
    /**
27
     * @param string $column
28
     */
29
    protected function setDuplicateCriteria(string $column): void
30
    {
31
        $this->duplicateCriteria = $column;
32
    }
33
34
    /**
35
     * In many cases (for example if you have inload of HAS_MANY relation) record data can be
36
     * replicated by many result rows (duplicated). To ensure proper data links we have to
37
     * deduplicate such records. This method use reference based feedback loop.
38
     *
39
     * @param array $data Reference to parsed record data, reference will be pointed to valid and
40
     *                    existed data segment if such data was already parsed.
41
     * @return bool Return true if data is unique.
42
     */
43
    final protected function deduplicate(array &$data): bool
44
    {
45
        if ($this->duplicateCriteria === null) {
46
            return true;
47
        }
48
49
        $criteria = (string)$data[$this->duplicateCriteria];
50
51
        if (isset($this->duplicates[$criteria])) {
52
            // duplicate is presented, let's reduplicate
53
            $data = $this->duplicates[$criteria];
54
55
            return false;
56
        }
57
58
        // remember record to prevent future duplicates
59
        $this->duplicates[$criteria] = &$data;
60
61
        return true;
62
    }
63
}
64