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

BelongsToLoader::__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
 * Load parent data. Similar to HasOne but use POSTLOAD as default method.
23
 */
24
class BelongsToLoader extends JoinableLoader
25
{
26
    /**
27
     * Default set of relation options. Child implementation might defined their of default options.
28
     *
29
     * @var array
30
     */
31
    protected $options = [
32
        'constrain' => true,
33
        'method'    => self::POSTLOAD,
34
        'minify'    => true,
35
        'as'        => null,
36
        'using'     => null,
37
        'where'     => null,
38
    ];
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    protected function configureQuery(SelectQuery $query, array $outerKeys = []): SelectQuery
44
    {
45
        if (!empty($this->options['using'])) {
46
            // use pre-defined query
47
            return parent::configureQuery($query, $outerKeys);
48
        }
49
50
        $localKey = $this->localKey(Relation::OUTER_KEY);
51
52
        if ($this->isJoined()) {
53
            $query->join(
54
                $this->getJoinMethod(),
55
                $this->getJoinTable()
56
            )->on(
57
                $localKey,
58
                $this->parentKey(Relation::INNER_KEY)
59
            );
60
        } else {
61
            // relation is loaded using external query
62
            $query->where($localKey, 'IN', new Parameter($outerKeys));
63
        }
64
65
        return parent::configureQuery($query);
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    protected function initNode(): AbstractNode
72
    {
73
        $node = new SingularNode(
74
            $this->columnNames(),
75
            $this->define(Schema::PRIMARY_KEY),
76
            $this->schema[Relation::OUTER_KEY],
77
            $this->schema[Relation::INNER_KEY]
78
        );
79
80
        $typecast = $this->define(Schema::TYPECAST);
81
        if ($typecast !== null) {
82
            $node->setTypecast(new Typecast($typecast, $this->getSource()->getDatabase()));
83
        }
84
85
        return $node;
86
    }
87
}