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

HasMany::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 9
Ratio 100 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 9
loc 9
rs 9.6666
cc 1
eloc 6
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 View Code Duplication
class HasMany extends Relation
0 ignored issues
show
Duplication introduced by
This class 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...
16
{
17
    protected function initQuery()
18
    {
19
        $localKey = $this->localKey;
20
        $value = $this->localModel->$localKey;
21
22
        if ($value === null) {
23
            $this->empty = true;
24
        }
25
26
        $this->query->where($this->foreignKey, $value);
27
    }
28
29
    public function getResults()
30
    {
31
        if ($this->empty) {
32
            return;
33
        }
34
35
        return $this->query->execute();
36
    }
37
38
    public function create(array $values = [])
39
    {
40
        $class = $this->foreignModel;
41
        $model = new $class();
42
        $model->{$this->foreignKey} = $this->localModel->{$this->localKey};
43
        $model->create($values);
44
45
        return $model;
46
    }
47
48
    /**
49
     * Attaches a child model from this model.
50
     *
51
     * @param Model $model child model
52
     *
53
     * @return self
54
     */
55
    public function attach(Model $model)
56
    {
57
        $model->{$this->foreignKey} = $this->localModel->{$this->localKey};
58
        $model->save();
59
60
        return $this;
61
    }
62
63
    /**
64
     * Detaches a child model from this model.
65
     *
66
     * @param Model $model child model
67
     *
68
     * @return self
69
     */
70
    public function detach(Model $model)
71
    {
72
        $model->{$this->foreignKey} = null;
73
        $model->save();
74
75
        return $this;
76
    }
77
}
78