Completed
Push — master ( 9c8755...82e13f )
by Jared
01:28
created

src/Relation/BelongsTo.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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\Model;
15
use Pulsar\Query;
16
17
/**
18
 * Represents a belongs-to relationship.
19
 */
20
final class BelongsTo extends AbstractRelation
21
{
22 View Code Duplication
    protected function initQuery(Query $query): Query
0 ignored issues
show
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...
23
    {
24
        $id = $this->localModel->{$this->localKey};
25
26
        if (null === $id) {
27
            $this->empty = true;
28
        }
29
30
        $query->where($this->foreignKey, $id)
31
            ->limit(1);
32
33
        return $query;
34
    }
35
36
    public function getResults()
37
    {
38
        $query = $this->getQuery();
39
        if ($this->empty) {
40
            return null;
41
        }
42
43
        return $query->first();
44
    }
45
46
    public function save(Model $model): Model
47
    {
48
        $model->saveOrFail();
49
        $this->attach($model);
50
51
        return $model;
52
    }
53
54
    public function create(array $values = []): Model
55
    {
56
        $class = $this->foreignModel;
57
        $model = new $class();
58
        $model->create($values);
59
60
        $this->attach($model);
61
62
        return $model;
63
    }
64
65
    /**
66
     * Attaches this model to an owning model.
67
     *
68
     * @param Model $model owning model
69
     *
70
     * @return $this
71
     */
72
    public function attach(Model $model)
73
    {
74
        $this->localModel->{$this->localKey} = $model->{$this->foreignKey};
75
        $this->localModel->saveOrFail();
76
77
        return $this;
78
    }
79
80
    /**
81
     * Detaches this model from the owning model.
82
     *
83
     * @return $this
84
     */
85
    public function detach()
86
    {
87
        $this->localModel->{$this->localKey} = null;
88
        $this->localModel->saveOrFail();
89
90
        return $this;
91
    }
92
}
93