Completed
Push — master ( c5047e...3a177f )
by Gabriel
03:52
created

BelongsTo::buildDictionary()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 6
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 6
1
<?php
2
3
namespace Nip\Records\Relations;
4
5
use Nip\Database\Query\AbstractQuery;
6
use Nip\Records\Collections\Collection as RecordCollection;
7
8
/**
9
 * Class BelongsTo
10
 * @package Nip\Records\Relations
11
 */
12
class BelongsTo extends Relation
13
{
14
15
    /**
16
     * @var string
17
     */
18
    protected $type = 'belongsTo';
19
20
    /** @noinspection PhpMissingParentCallCommonInspection
21
     * @return string
22
     */
23 1
    public function generateFK()
24
    {
25 1
        return $this->getWith()->getPrimaryFK();
26
    }
27
28 2
    public function initResults()
29
    {
30 2
        $manager = $this->getWith();
31 2
        $fk = $this->getItem()->{$this->getFK()};
32 2
        $this->setResults($manager->findOne($fk));
33 2
    }
34
35
    /**
36
     * @param $dictionary
37
     * @param $collection
38
     * @param $record
39
     * @return mixed
40
     */
41
    public function getResultsFromCollectionDictionary($dictionary, $collection, $record)
42
    {
43
        $pk = $record->{$this->getFK()};
44
        if (isset($dictionary[$pk])) {
45
            return $dictionary[$pk];
46
        }
47
48
        return false;
49
    }
50
51
    /**
52
     * Build model dictionary keyed by the relation's foreign key.
53
     *
54
     * @param RecordCollection $collection
55
     * @return array
56
     */
57
    protected function buildDictionary(RecordCollection $collection)
58
    {
59
        $dictionary = [];
60
        $withPK = $this->getWithPK();
61
        foreach ($collection as $record) {
62
            $dictionary[$record->{$withPK}] = $record;
63
        }
64
65
        return $dictionary;
66
    }
67
68
    /**
69
     * @inheritdoc
70
     */
71
    public function populateQuerySpecific(AbstractQuery $query)
72
    {
73
    }
74
}
75