Issues (12)

src/Json/HasMorphClassesAttributes.php (2 issues)

Labels
Severity
1
<?php
2
3
namespace JsonFieldCast\Json;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\Relations\Relation;
7
8
trait HasMorphClassesAttributes
9
{
10 2
    public function toMorph(string $key, Model $value, string $idKeyName = 'id', string $classKeyName = 'class'): static
11
    {
12 2
        $this->setAttribute($key ? "{$key}.{$idKeyName}" : $idKeyName, $value->getKey());
0 ignored issues
show
It seems like setAttribute() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

12
        $this->/** @scrutinizer ignore-call */ 
13
               setAttribute($key ? "{$key}.{$idKeyName}" : $idKeyName, $value->getKey());
Loading history...
13 2
        $this->setAttribute($key ? "{$key}.{$classKeyName}" : $classKeyName, $value->getMorphClass());
14
15 2
        return $this;
16
    }
17
18 4
    public function fromMorph(string $key = '', ?Model $default = null, string $idKeyName = 'id', string $classKeyName = 'class'): ?Model
19
    {
20 4
        $id    = $this->getAttribute($key ? "{$key}.{$idKeyName}" : $idKeyName);
0 ignored issues
show
It seems like getAttribute() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

20
        /** @scrutinizer ignore-call */ 
21
        $id    = $this->getAttribute($key ? "{$key}.{$idKeyName}" : $idKeyName);
Loading history...
21 4
        $class = $this->getAttribute($key ? "{$key}.{$classKeyName}" : $classKeyName);
22 4
        if (!$id || !$class) {
23 4
            return $default;
24
        }
25
26 4
        $class = Relation::getMorphedModel($class) ?? $class;
27 4
        if (!is_a($class, Model::class, true)) {
28 2
            return $default;
29
        }
30
31 4
        $model = $class::find($id);
32 4
        if (!$model) {
33 2
            return $default;
34
        }
35
36 2
        return $model;
37
    }
38
}
39