ValueFactory::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Zenstruck\Callback;
4
5
use Zenstruck\Callback;
6
7
/**
8
 * @author Kevin Bond <[email protected]>
9
 */
10
final class ValueFactory
11
{
12
    /** @var callable */
13
    private $factory;
14
15
    /**
16
     * @param callable<string|array|Argument|null> $factory
17
     */
18
    public function __construct(callable $factory)
19
    {
20
        $this->factory = $factory;
21
    }
22
23
    public function __invoke(Argument $argument)
24
    {
25
        $stringTypeFactory = Parameter::factory(function() use ($argument) {
26
            if ($argument->isUnionType()) {
27
                throw new \LogicException(\sprintf('ValueFactory does not support union types. Inject "%s" instead.', Argument::class));
28
            }
29
30
            return $argument->type();
31
        });
32
33
        return Callback::createFor($this->factory)
34
            ->invoke(Parameter::union(
35
                Parameter::typed(Argument::class, $argument),
36
                Parameter::typed('array', $argument->types()),
37
                Parameter::typed('string', $stringTypeFactory),
38
                Parameter::untyped($stringTypeFactory)
39
            )->optional())
40
        ;
41
    }
42
}
43