Completed
Push — master ( c39839...6b5ada )
by Pavel
29s
created

Castable   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 2
dl 0
loc 36
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A scopeCast() 0 10 3
A findCaster() 0 10 2
1
<?php
2
3
namespace Koch\Casters\Behavior;
4
5
use Koch\Casters\Contracts\Caster;
6
7
trait Castable
8
{
9
    /**
10
     * Casts either a collection or a single model.
11
     *
12
     * @param  \Illuminate\Database\Eloquent\Builder  $query
13
     * @param  \Koch\Casters\Contracts\Caster|null  $caster
14
     * @return array
15
     */
16
    public function scopeCast($query, Caster $caster = null)
17
    {
18
        $caster = $caster ?: $this->findCaster();
19
20
        if ($this->exists) {
0 ignored issues
show
Bug introduced by
The property exists does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
21
            return $caster->cast($this);
22
        }
23
24
        return $caster->cast($query->get());
25
    }
26
27
    /**
28
     * Resolves the caster name and returns its instance.
29
     *
30
     * @return \Koch\Casters\Contracts\Caster
31
     */
32
    protected function findCaster()
33
    {
34
        if (property_exists($this, 'caster')) {
35
            return new $this->caster;
0 ignored issues
show
Bug introduced by
The property caster does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
36
        }
37
38
        $name = 'App\\Casters\\'.class_basename($this).'Caster';
39
40
        return new $name;
41
    }
42
}
43