Completed
Push — master ( a318f5...917f2c )
by Jared
01:37
created

HasOne::save()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
/**
4
 * @author Jared King <[email protected]>
5
 *
6
 * @see http://jaredtking.com
7
 *
8
 * @copyright 2015 Jared King
9
 * @license MIT
10
 */
11
12
namespace Pulsar\Relation;
13
14
use Pulsar\Exception\ModelException;
15
use Pulsar\Model;
16
use Pulsar\Query;
17
18
/**
19
 * Represents a has-one relationship.
20
 */
21
final class HasOne extends AbstractRelation
22
{
23 View Code Duplication
    protected function initQuery(Query $query): Query
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...
24
    {
25
        $id = $this->localModel->{$this->localKey};
26
27
        if (null === $id) {
28
            $this->empty = true;
29
        }
30
31
        $query->where($this->foreignKey, $id)
32
            ->limit(1);
33
34
        return $query;
35
    }
36
37
    public function getResults()
38
    {
39
        $query = $this->getQuery();
40
        if ($this->empty) {
41
            return null;
42
        }
43
44
        return $query->first();
45
    }
46
47
    public function save(Model $model): Model
48
    {
49
        $model->{$this->foreignKey} = $this->localModel->{$this->localKey};
50
        $model->saveOrFail();
51
52
        return $model;
53
    }
54
55
    public function create(array $values = []): Model
56
    {
57
        $class = $this->foreignModel;
58
        $model = new $class();
59
        $model->{$this->foreignKey} = $this->localModel->{$this->localKey};
60
        $model->create($values);
61
62
        return $model;
63
    }
64
65
    /**
66
     * Attaches a child model to this model.
67
     *
68
     * @param Model $model child model
69
     *
70
     * @throws ModelException when the operation fails
71
     *
72
     * @return $this
73
     */
74
    public function attach(Model $model)
75
    {
76
        $model->{$this->foreignKey} = $this->localModel->{$this->localKey};
77
        $model->saveOrFail();
78
79
        return $this;
80
    }
81
82
    /**
83
     * Detaches the child model from this model.
84
     *
85
     * @throws ModelException when the operation fails
86
     *
87
     * @return $this
88
     */
89
    public function detach()
90
    {
91
        $model = $this->getResults();
92
93
        if ($model) {
94
            $model->{$this->foreignKey} = null;
95
            $model->saveOrFail();
96
        }
97
98
        return $this;
99
    }
100
}
101