Passed
Push — factory-and-get-factory ( 85d8e3 )
by Chema
03:36
created

FactoryResolverAwareTrait::__call()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 2
nop 2
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework;
6
7
use Gacela\Framework\ClassResolver\Factory\FactoryResolver;
8
use RuntimeException;
9
10
/**
11
 * @method AbstractFactory factory()
12
 * @method AbstractFactory getFactory()
13
 */
14
trait FactoryResolverAwareTrait
15
{
16
    private ?AbstractFactory $factory = null;
17
18
    /**
19
     * Syntax sugar to access the factory from static methods.
20
     */
21
    public static function __callStatic(string $name, array $arguments): AbstractFactory
22
    {
23
        if ($name === 'factory' || $name === 'getFactory') {
24
            return (new static())->doGetFactory();
25
        }
26
27
        throw new RuntimeException("Method unknown: {$name}");
28
    }
29
30
    public function __call(string $name, array $arguments): AbstractFactory
31
    {
32
        if ($name === 'factory' || $name === 'getFactory') {
33
            return $this->doGetFactory();
34
        }
35
36
        throw new RuntimeException("Method unknown: {$name}");
37
    }
38
39
    private function doGetFactory(): AbstractFactory
40
    {
41
        if ($this->factory === null) {
42
            $this->factory = (new FactoryResolver())->resolve($this);
43
        }
44
45
        return $this->factory;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->factory could return the type null which is incompatible with the type-hinted return Gacela\Framework\AbstractFactory. Consider adding an additional type-check to rule them out.
Loading history...
46
    }
47
}
48