LookupTrait::key()
last analyzed

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
nc 1
1
<?php
2
/**
3
 * Spiral, Core Components
4
 *
5
 * @author Wolfy-J
6
 */
7
8
namespace Spiral\ORM\Entities\Relations\Traits;
9
10
use Spiral\ORM\ContextualCommandInterface;
11
use Spiral\ORM\RecordInterface;
12
13
/**
14
 * Looks for key values in command context AND in outer field if possible.
15
 */
16
trait LookupTrait
17
{
18
    /**
19
     * @param int                        $key
20
     * @param RecordInterface            $record
21
     * @param ContextualCommandInterface $command
22
     *
23
     * @return mixed|null
24
     */
25
    protected function lookupKey(
26
        int $key,
27
        RecordInterface $record,
28
        ContextualCommandInterface $command = null
29
    ) {
30
        $key = $this->key($key);
31
32
        if (!empty($command)) {
33
            $context = $command->getContext();
34
            if (!empty($context[$key])) {
35
                //Key value found in a context
36
                return $context[$key];
37
            }
38
39
            if ($key == $this->primaryColumnOf($record)) {
40
                return $command->primaryKey();
41
            }
42
        }
43
44
        //Fallback lookup in a record
45
        return $record->getField($key, null);
46
    }
47
48
    /**
49
     * Key name.
50
     *
51
     * @param int $key
52
     *
53
     * @return string|null
54
     */
55
    abstract protected function key(int $key);
56
57
    /**
58
     * Get primary key column
59
     *
60
     * @param RecordInterface $record
61
     *
62
     * @return string
63
     */
64
    abstract protected function primaryColumnOf(RecordInterface $record): string;
65
}