Completed
Push — develop ( 9ee49b...09fe33 )
by Martin
02:19
created

HasRivetsTrait::attach()   B

Complexity

Conditions 6
Paths 11

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 22
rs 8.6737
cc 6
eloc 14
nc 11
nop 3
1
<?php
2
3
namespace Luminark\Rivet\Traits;
4
5
use Luminark\Rivet\Models\Rivet;
6
use Luminark\Rivet\Events\AttachingToModel;
7
use Luminark\Rivet\Events\AttachedToModel;
8
use Rutorika\Sortable\MorphToSortedManyTrait;
9
use InvalidArgumentException;
10
11
trait HasRivetsTrait
12
{
13
    use MorphToSortedManyTrait;
14
    
15
    protected function getRivetsConfig()
16
    {
17
        return $this->rivets ?: ['rivets' => []];
0 ignored issues
show
Documentation introduced by
The property rivets does not exist on object<Luminark\Rivet\Traits\HasRivetsTrait>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
18
    }
19
    
20
    protected function getRivetClass()
21
    {
22
        return Rivet::class;
23
    }
24
    
25
    public function attach($attribute, $rivet, $relationShouldLoad = false)
26
    {
27
        list($type, $class) = $this->getRivetConfig($attribute);
28
        
29
        if (is_numeric($rivet)) {
30
            $rivet = $class::findOrFail($rivet);
31
        } elseif ( ! $rivet instanceof $class) {
32
            throw new InvalidArgumentException("Invalid object provided for attaching to $attribute. Expected $class, got " . get_class($rivet) . ".");
33
        }
34
        
35
        if ($type == 'property') {
36
            $this->attachAsProperty($attribute, $rivet);
37
        } elseif ($type == 'collection') {
38
            $this->attachToCollection($attribute, $rivet);
39
        } else {
40
            throw new InvalidArgumentException("Invalid type [$type] provided for attaching to $attribute.");
41
        }
42
        
43
        if($relationShouldLoad) {
44
            $this->load($attribute);
45
        }
46
    }
47
    
48
    protected function attachAsProperty($attribute, Rivet $rivet)
49
    {
50
        if ($this->$attribute) {
51
            $this->removeRivet($attribute, $this->$attribute->id);
52
        }
53
        
54
        return $this->attachToCollection($attribute, $rivet);
55
    }
56
    
57
    protected function attachToCollection($collection, Rivet $rivet)
58
    {
59
        $dispatcher = static::getEventDispatcher();
60
        $dispatcher->fire(new AttachingToModel($this, $collection, $rivet));
61
        
62
        $rivet->save();
63
        $this->$collection()->attach($rivet, ['collection' => $collection]);
64
        
65
        $dispatcher->fire(new AttachedToModel($this, $collection, $rivet));
66
        
67
        return $rivet;
68
    }
69
    
70
    public function removeRivet($attribute, $rivet, $relationShouldLoad = false)
71
    {
72
        list(, $class) = $this->getRivetConfig($attribute);
73
        
74
        $result = null;
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
75
        if (is_numeric($rivet)) {
76
            $result = $this->$attribute()->detach($rivet);
77
        } elseif ($rivet instanceof $class) {
78
            $result = $this->$attribute()->detach($rivet->id);
79
        } else {
80
            throw new InvalidArgumentException('Only an ID or a Rivet object can be passed to removeRivet method.');
81
        }
82
        
83
        if ( ! $result) {
84
            throw new InvalidArgumentException('Unrelated ID or Rivet object passed to removeRivet method.');
85
        }
86
        
87
        if($relationShouldLoad) {
88
            $this->load($attribute);
89
        }
90
        
91
        return $this;
92
    }
93
    
94
    public function __call($name, $arguments)
95
    {
96 View Code Duplication
        if (preg_match('/^set(\w+)/', $name, $matches)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
97
            && in_array($property = lcfirst($matches[1]), array_keys($this->getRivetsConfig()))) {
98
            array_unshift($arguments, $property);
99
            return call_user_func_array([$this, 'attach'], $arguments);
100
        }
101
        
102 View Code Duplication
        if (preg_match('/^add(\w+)/', $name, $matches)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
103
            && in_array($collection = str_plural(lcfirst($matches[1])), array_keys($this->getRivetsConfig()))) {
104
            array_unshift($arguments, $collection);
105
            return call_user_func_array([$this, 'attach'], $arguments);
106
        }
107
        
108 View Code Duplication
        if (preg_match('/^unset(\w+)/', $name, $matches)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
109
            && in_array($property = lcfirst($matches[1]), array_keys($this->getRivetsConfig()))) {
110
            array_unshift($arguments, $property);
111
            return call_user_func_array([$this, 'removeRivet'], $arguments);
112
        }
113
        
114 View Code Duplication
        if (preg_match('/^remove(\w+)/', $name, $matches)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
115
            && in_array($collection = str_plural(lcfirst($matches[1])), array_keys($this->getRivetsConfig()))) {
116
            array_unshift($arguments, $collection);
117
            return call_user_func_array([$this, 'removeRivet'], $arguments);
118
        }
119
        
120
        if ( ! in_array($name, array_keys($this->getRivetsConfig()))) {
121
            return parent::__call($name, $arguments);
122
        }
123
        
124
        list($type, $class) = $this->getRivetConfig($name);
125
        
126
        if ($type == 'property') {
127
            return $this->getRivetProperty($class, $name);
128
        }
129
        if ($type == 'collection') {
130
            return $this->getRivetCollection($class, $name);
131
        }
132
    }
133
    
134
    public function __get($name)
135
    {
136
        $result = parent::__get($name);
137
        
138
        if ( ! in_array($name, array_keys($this->getRivetsConfig()))) {
139
            return $result;
140
        }
141
        
142
        if ( ! $result) {
143
            $this->load($name);
144
            $result = $this->getAttribute($name);
145
        }
146
        
147
        list($type) = $this->getRivetConfig($name);
148
        if ($type == 'property') {
149
            return $result->first();
150
        }
151
        
152
        return $result;
153
    }
154
    
155
    protected function getRivetConfig($name)
156
    {
157
        return $this->getRivetsConfig()[$name]
158
            + ['collection', $this->getRivetClass()];
159
    }
160
    
161
    protected function getRivetProperty($class, $name)
162
    {
163
        return $this->getRivetCollection($class, $name);
164
    }
165
    
166
    protected function getRivetCollection($class, $name)
167
    {
168
        return $this->morphToSortedMany(
169
            $class, 
170
            'rivetable',
171
            'position', 
172
            null, 
173
            null,
174
            $class::getMorphToSortableManyOtherKey()
175
        )->wherePivot('collection', snake_case($name));
176
    }
177
    
178
    abstract public function getAttribute($key);
179
    
180
    abstract public function load($relations);
181
}
182