Passed
Push — main ( 2054fe...0c6c03 )
by Breno
02:23
created

AutoDetection::isArrayDefinition()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 14
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace Habemus\Definition;
5
6
use Closure;
7
use Habemus\Container;
8
use Habemus\Definition\Build\ArrayDefinition;
9
use Habemus\Definition\Build\ReferenceDefinition;
10
use Habemus\Definition\Build\ClassDefinition;
11
use Habemus\Definition\Build\FnDefinition;
12
use Habemus\Definition\Build\RawDefinition;
13
14
class AutoDetection implements DefinitionDetection
15
{
16
    /**
17
     * @var Container
18
     */
19
    protected $container;
20
21
    public function __construct(Container $container)
22
    {
23
        $this->container = $container;
24
    }
25
26
    public function detect($value): Definition
27
    {
28
        if ($value instanceof Definition) {
29
            return $value;
30
        }
31
32
        if (is_null($value)) {
33
            return new RawDefinition($value);
34
        }
35
36
        if ($this->isClosure($value)) {
37
            return new FnDefinition($value);
38
        }
39
40
        if ($this->isAutowire($value)) {
41
            return new ClassDefinition($value);
42
        }
43
44
        if ($this->isArrayDefinition($value)) {
45
            return new ArrayDefinition($value, true);
46
        }
47
48
        return new RawDefinition($value);
49
    }
50
51
    /**
52
     * @param mixed $value
53
     * @return bool
54
     */
55
    protected function isClosure($value): bool
56
    {
57
        return !is_scalar($value) && !is_array($value) && !is_resource($value) && get_class($value) === Closure::class;
58
    }
59
60
    /**
61
     * @param mixed $value
62
     * @return bool
63
     */
64
    protected function isAutowire($value): bool
65
    {
66
        return $this->container->autowireEnabled() && !is_object($value) && is_string($value) && class_exists($value);
67
    }
68
69
    /**
70
     * @param mixed $value
71
     * @return bool
72
     */
73
    protected function isArrayDefinition($value): bool
74
    {
75
        if (!is_array($value)) {
76
            return false;
77
        }
78
79
        $hasDefinitionInside = false;
80
        array_walk_recursive($value, function ($item) use (&$hasDefinitionInside) {
81
            if ($item instanceof ReferenceDefinition) {
82
                $hasDefinitionInside = true;
83
            }
84
        });
85
86
        return $hasDefinitionInside;
87
    }
88
}
89