Passed
Push — main ( 55c455...253058 )
by Michael
04:34
created

BootsCallProxies::bootCallProxies()   A

Complexity

Conditions 6
Paths 2

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 9
Bugs 0 Features 0
Metric Value
cc 6
eloc 11
c 9
b 0
f 0
nc 2
nop 1
dl 0
loc 18
ccs 12
cts 12
cp 1
crap 6
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MichaelRubel\EnhancedContainer\Traits;
6
7
use Illuminate\Support\Fluent;
8
9
trait BootsCallProxies
10
{
11
    /**
12
     * @var Fluent|null
13
     */
14
    protected ?Fluent $proxy = null;
15
16
    /**
17
     * Boots the fluent object of call proxies.
18
     *
19
     * @param string|null $method
20
     *
21
     * @return void
22
     */
23 5
    public function bootCallProxies(?string $method = null): void
24
    {
25 5
        $reflection = new \ReflectionClass(static::class);
26
27 5
        $method = $this->getMethod($method, $reflection);
28
29 5
        $dependencies = $method?->getParameters();
30
31 5
        if (! empty($dependencies)) {
32 5
            $this->makeFluentObject();
33
34 5
            collect($dependencies)->map(function ($param) {
35 5
                $class = $param->getType()->getName();
36
37 5
                if (class_exists($class) || interface_exists($class)) {
38 5
                    property_exists(static::class, $param->getName()) && is_object($this->{$param->getName()})
39 3
                        ? $this->proxy->{$param->getName()} = call($this->{$param->getName()})
40 3
                        : $this->proxy->{$param->getName()} = call($class);
41
                }
42 5
            });
43
        }
44 5
    }
45
46
    /**
47
     * Determines which method to use.
48
     *
49
     * @param string|null      $method
50
     * @param \ReflectionClass $reflectionClass
51
     *
52
     * @return \ReflectionMethod|null
53
     */
54 5
    private function getMethod(?string $method, \ReflectionClass $reflectionClass): ?\ReflectionMethod
55
    {
56 5
        return is_null($method)
57 4
            ? $reflectionClass->getConstructor()
58 5
            : $reflectionClass->getMethod($method);
59
    }
60
61
    /**
62
     * Instantiate the Fluent object if it doesn't exist.
63
     *
64
     * @return void
65
     */
66 5
    private function makeFluentObject(): void
67
    {
68 5
        if (! $this->proxy instanceof Fluent) {
69 5
            $this->proxy = new Fluent();
70
        }
71 5
    }
72
}
73