Passed
Push — master ( a4a283...561882 )
by Anton
01:37
created

HasOneLoader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 4
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
namespace Spiral\Cycle\Select\Loader;
11
12
use Spiral\Cycle\Parser\AbstractNode;
13
use Spiral\Cycle\Parser\SingularNode;
14
use Spiral\Cycle\Parser\Typecast;
15
use Spiral\Cycle\Relation;
16
use Spiral\Cycle\Schema;
17
use Spiral\Cycle\Select\JoinableLoader;
18
use Spiral\Database\Injection\Parameter;
19
use Spiral\Database\Query\SelectQuery;
20
21
/**
22
 * Dedicated to load HAS_ONE relations, by default loader will prefer to join data into query.
23
 * Loader support MORPH_KEY.
24
 *
25
 * Please note that OUTER and INNER keys defined from perspective of parent (reversed for our
26
 * purposes).
27
 */
28
class HasOneLoader extends JoinableLoader
29
{
30
    /**
31
     * Default set of relation options. Child implementation might defined their of default options.
32
     *
33
     * @var array
34
     */
35
    protected $options = [
36
        'constrain' => true,
37
        'method'    => self::INLOAD,
38
        'minify'    => true,
39
        'as'        => null,
40
        'using'     => null,
41
    ];
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    protected function configureQuery(SelectQuery $query, array $outerKeys = []): SelectQuery
47
    {
48
        if (!empty($this->options['using'])) {
49
            // use pre-defined query
50
            return parent::configureQuery($query, $outerKeys);
51
        }
52
53
        $localKey = $this->localKey(Relation::OUTER_KEY);
54
55
        if ($this->isJoined()) {
56
            $query->join(
57
                $this->getJoinMethod(),
58
                $this->getJoinTable()
59
            )->on(
60
                $localKey,
61
                $this->parentKey(Relation::INNER_KEY)
62
            );
63
        } else {
64
            // relation is loaded using external query
65
            $query->where($localKey, 'IN', new Parameter($outerKeys));
66
        }
67
68
        return parent::configureQuery($query);
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    protected function initNode(): AbstractNode
75
    {
76
        $node = new SingularNode(
77
            $this->columnNames(),
78
            $this->define(Schema::PRIMARY_KEY),
79
            $this->schema[Relation::OUTER_KEY],
80
            $this->schema[Relation::INNER_KEY]
81
        );
82
83
        $typecast = $this->define(Schema::TYPECAST);
84
        if ($typecast !== null) {
85
            $node->setTypecast(new Typecast($typecast, $this->getSource()->getDatabase()));
86
        }
87
88
        return $node;
89
    }
90
}