Completed
Push — master ( be821e...418a4d )
by James Ekow Abaka
03:23
created

BelongsToRelationship::runSetup()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
rs 9.4285
ccs 8
cts 8
cp 1
cc 3
eloc 7
nc 4
nop 0
crap 3
1
<?php
2
3
/*
4
 * The MIT License
5
 *
6
 * Copyright 2015 ekow.
7
 *
8
 * Permission is hereby granted, free of charge, to any person obtaining a copy
9
 * of this software and associated documentation files (the "Software"), to deal
10
 * in the Software without restriction, including without limitation the rights
11
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
 * copies of the Software, and to permit persons to whom the Software is
13
 * furnished to do so, subject to the following conditions:
14
 *
15
 * The above copyright notice and this permission notice shall be included in
16
 * all copies or substantial portions of the Software.
17
 *
18
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
 * THE SOFTWARE.
25
 */
26
27
namespace ntentan\nibii\relationships;
28
29
use ntentan\nibii\QueryParameters;
30
use ntentan\utils\Text;
31
use ntentan\nibii\Context;
32
33
class BelongsToRelationship extends \ntentan\nibii\Relationship {
34
35
    protected $type = self::BELONGS_TO;
36
    
37 20
    public function __construct(Context $context) {
38 20
        $this->container = $context->getContainer();
39 20
        $this->context = $context;
40 20
    }
41
42 4
    public function getQuery($data) {
43 4
        $query = (new QueryParameters($this->getModelInstance()->getDBStoreInformation()['table']))
44 4
            ->addFilter($this->options['foreign_key'], [$data[$this->options['local_key']]])
45 4
            ->setFirstOnly(true);
46 4
        return $query;
47
    }
48
49 4
    public function runSetup() {
50 4
        $model = $this->container->resolve($this->context->getClassName($this->options['model'], self::BELONGS_TO));
51 4
        $table = $model->getDBStoreInformation()['table'];
52 4
        if ($this->options['foreign_key'] == null) {
53 4
            $this->options['foreign_key'] = $model->getDescription()->getPrimaryKey()[0];
54
        }
55 4
        if ($this->options['local_key'] == null) {
56 4
            $this->options['local_key'] = Text::singularize($table) . '_id';
57
        }
58 4
    }
59
60
}
61