Passed
Push — master ( b36cf1...75a4a8 )
by Aleksei
02:25
created

OrmFactory::__invoke()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 4
c 2
b 0
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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 6
    public function __construct($promiseFactory = null)
24
    {
25 6
        $this->promiseFactory = $promiseFactory;
26 6
    }
27
28 6
    public function __invoke(ContainerInterface $container)
29
    {
30 6
        $schema = $container->get(SchemaInterface::class);
31 6
        $factory = $container->get(FactoryInterface::class);
32
33 6
        $orm = new ORM($factory, $schema);
34
35 6
        return $this->addPromiseFactory($orm, $container);
36
    }
37
38 6
    private function addPromiseFactory(ORM $orm, ContainerInterface $container): ORM
39
    {
40 6
        if ($this->promiseFactory === null) {
41 2
            return $orm;
42
        }
43 4
        $promiseFactory = is_string($this->promiseFactory)
44 2
            ? $container->get($this->promiseFactory)
45 4
            : $this->promiseFactory;
46
47
48 4
        if (!$promiseFactory instanceof PromiseFactoryInterface) {
49 2
            throw new BadDeclarationException('Promise factory', PromiseFactoryInterface::class, $promiseFactory);
50
        }
51 2
        return $orm->withPromiseFactory($promiseFactory);
52
    }
53
}
54