Completed
Push — master ( 62d3ac...e8b70a )
by Jared
02:18
created

BelongsTo::attach()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
/**
4
 * @author Jared King <[email protected]>
5
 *
6
 * @link http://jaredtking.com
7
 *
8
 * @copyright 2015 Jared King
9
 * @license MIT
10
 */
11
namespace Pulsar\Relation;
12
13
use Pulsar\Model;
14
15
class BelongsTo extends Relation
16
{
17
    protected function initQuery()
18
    {
19
        $value = $this->localModel->{$this->localKey};
20
21
        if ($value === null) {
22
            $this->empty = true;
23
        }
24
25
        $this->query->where($this->foreignKey, $value)
26
                    ->limit(1);
27
    }
28
29
    public function getResults()
30
    {
31
        if ($this->empty) {
32
            return;
33
        }
34
35
        return $this->query->first();
36
    }
37
38 View Code Duplication
    public function create(array $values = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
39
    {
40
        $class = $this->foreignModel;
41
        $model = new $class();
42
        $model->create($values);
43
44
        $this->attach($model);
45
46
        return $model;
47
    }
48
49
    /**
50
     * Attaches this model to an owning model.
51
     *
52
     * @param Model $model owning model
53
     *
54
     * @return self
55
     */
56
    public function attach(Model $model)
57
    {
58
        $this->localModel->{$this->localKey} = $model->{$this->foreignKey};
59
        $this->localModel->save();
60
61
        return $this;
62
    }
63
64
    /**
65
     * Detaches this model from the owning model.
66
     *
67
     * @return self
68
     */
69
    public function detach()
70
    {
71
        $this->localModel->{$this->localKey} = null;
72
        $this->localModel->save();
73
74
        return $this;
75
    }
76
}
77