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

Castable::findCaster()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
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