Completed
Branch feature/pre-split (289154)
by Anton
03:22
created

LookupTrait::primaryColumnOf()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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