Passed
Pull Request — master (#53)
by Alexander
23:13 queued 06:44
created

OrmFactory::addPromiseFactory()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 14
ccs 0
cts 2
cp 0
rs 10
cc 4
nc 5
nop 2
crap 20
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Cycle\Factory;
6
7
use Cycle\ORM\FactoryInterface;
8
use Cycle\ORM\ORM;
9
use Cycle\ORM\PromiseFactoryInterface;
10
use Cycle\ORM\SchemaInterface;
11
use Psr\Container\ContainerInterface;
12
use Yiisoft\Yii\Cycle\Exception\BadDeclarationException;
13
14
final class OrmFactory
15
{
16
    /** @var null|PromiseFactoryInterface|string  */
17
    private $promiseFactory = null;
18
19
    /**
20
     * OrmFactory constructor.
21
     * @param null|PromiseFactoryInterface|string $promiseFactory
22
     */
23
    public function __construct($promiseFactory = null)
24
    {
25
        $this->promiseFactory = $promiseFactory;
26
    }
27
28
    public function __invoke(ContainerInterface $container)
29
    {
30
        $schema = $container->get(SchemaInterface::class);
31
        $factory = $container->get(FactoryInterface::class);
32
33
        $orm = new ORM($factory, $schema);
34
35
        return $this->addPromiseFactory($orm, $container);
36
    }
37
38
    private function addPromiseFactory(ORM $orm, ContainerInterface $container): ORM
39
    {
40
        if ($this->promiseFactory === null) {
41
            return $orm;
42
        }
43
        $promiseFactory = is_string($this->promiseFactory)
44
            ? $container->get($this->promiseFactory)
45
            : $this->promiseFactory;
46
47
48
        if (!$promiseFactory instanceof PromiseFactoryInterface) {
49
            throw new BadDeclarationException('Promise factory', PromiseFactoryInterface::class, $promiseFactory);
50
        }
51
        return $orm->withPromiseFactory($promiseFactory);
52
    }
53
}
54