Failed Conditions
Push — master ( 8fb951...fb1394 )
by Arnold
03:15
created

ClassLoader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jasny\Container\Loader;
6
7
use Psr\Container\ContainerInterface;
8
9
use function Jasny\expect_type;
10
11
/**
12
 * Load entries from class.
13
 */
14
class ClassLoader extends AbstractLoader
15
{
16
    /**
17
     * Logic to create entries
18
     * @var callable
19
     */
20
    protected $apply;
21
22
23
    /**
24
     * MappingGenerator constructor.
25
     *
26
     * @param \Iterator $classes
27
     * @param callable  $apply    Logic to create entries for a class
28
     */
29 8
    public function __construct(\Iterator $classes, callable $apply = null)
30
    {
31 8
        $this->apply = $apply ?? [$this, 'createEntry'];
32
33 8
        parent::__construct($classes);
34 7
    }
35
36
37
    /**
38
     * Create new entries
39
     *
40
     * @return void
41
     */
42 8
    protected function prepareNext(): void
43
    {
44 8
        if (!$this->items->valid()) {
45 2
            return;
46
        }
47
48 6
        $class = $this->items->current();
49 6
        $entries = call_user_func($this->apply, $class);
50
51 6
        expect_type($entries, 'array', \UnexpectedValueException::class,
52 6
            "Failed to load container entries for '$class': Expected array, callback returned %s");
53
54 5
        $this->entries = new \ArrayIterator($entries);
55
56 5
        $this->items->next();
57 5
    }
58
59
    /**
60
     * Create a container entry for a class using autowiring.
61
     *
62
     * @param string $class
63
     * @return \Closure[]
64
     */
65 1
    protected function createEntry(string $class)
66
    {
67
        return [
68
            $class => function (ContainerInterface $container) use ($class) {
69 1
                return $container->get('Jasny\Autowire\AutowireInterface')->instantiate($class);
70 1
            }
71
        ];
72
    }
73
}
74