Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
30.77% covered (danger)
30.77%
4 / 13
33.33% covered (danger)
33.33%
1 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
ChainedClassInstantiator
30.77% covered (danger)
30.77%
4 / 13
33.33% covered (danger)
33.33%
1 / 3
23.26
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 supports
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 create
37.50% covered (danger)
37.50%
3 / 8
0.00% covered (danger)
0.00%
0 / 1
5.20
1<?php
2namespace Apie\StorageMetadata\ClassInstantiators;
3
4use Apie\Core\ValueObjects\Utils;
5use Apie\StorageMetadata\Interfaces\ClassInstantiatorInterface;
6use Apie\StorageMetadata\Interfaces\StorageDtoInterface;
7use ReflectionClass;
8use RuntimeException;
9
10final class ChainedClassInstantiator implements ClassInstantiatorInterface
11{
12    /** @var array<int, ClassInstantiatorInterface> */
13    private array $classInstantiators;
14
15    public function __construct(ClassInstantiatorInterface... $classInstantiators)
16    {
17        $this->classInstantiators = $classInstantiators;
18    }
19
20
21    public function supports(ReflectionClass $class, ?StorageDtoInterface $storageObject = null): bool
22    {
23        foreach ($this->classInstantiators as $classInstantiator) {
24            if ($classInstantiator->supports($class, $storageObject)) {
25                return true;
26            }
27        }
28
29        return false;
30    }
31
32    public function create(ReflectionClass $class, ?StorageDtoInterface $storageObject = null): object
33    {
34        foreach ($this->classInstantiators as $classInstantiator) {
35            if ($classInstantiator->supports($class, $storageObject)) {
36                return $classInstantiator->create($class, $storageObject);
37            }
38        }
39        throw new RuntimeException(sprintf(
40            'Class "%s" for storage object "%s" not supported for instantiation',
41            Utils::displayMixedAsString($class->name),
42            Utils::displayMixedAsString($storageObject),
43        ));
44    }
45}