EntityManagerFactoryProviderTrait   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 22
c 1
b 0
f 0
dl 0
loc 51
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A getEntityManager() 0 38 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\LaminasDoctrine\Factory\Service\EntityManager;
6
7
use Arp\LaminasDoctrine\Service\EntityManager\EntityManagerProvider;
8
use Arp\LaminasDoctrine\Service\EntityManager\EntityManagerProviderInterface;
9
use Arp\LaminasDoctrine\Service\EntityManager\Exception\EntityManagerProviderException;
10
use Doctrine\ORM\EntityManagerInterface;
11
use Laminas\ServiceManager\Exception\ServiceNotCreatedException;
12
use Psr\Container\ContainerExceptionInterface;
13
use Psr\Container\ContainerInterface;
14
use Psr\Container\NotFoundExceptionInterface;
15
16
trait EntityManagerFactoryProviderTrait
17
{
18
    /**
19
     * @param ContainerInterface                  $container
20
     * @param string|EntityManagerInterface|mixed $name
21
     * @param string                              $serviceName
22
     *
23
     * @return EntityManagerInterface
24
     *
25
     * @throws ServiceNotCreatedException
26
     * @throws ContainerExceptionInterface
27
     * @throws NotFoundExceptionInterface
28
     */
29
    protected function getEntityManager(
30
        ContainerInterface $container,
31
        $name,
32
        string $serviceName
33
    ): EntityManagerInterface {
34
        $entityManager = $name;
35
36
        if (is_string($name)) {
37
            /** @var EntityManagerProviderInterface $entityManagerProvider */
38
            $entityManagerProvider = $container->get(EntityManagerProvider::class);
39
40
            try {
41
                $entityManager = $entityManagerProvider->getEntityManager($name);
42
            } catch (EntityManagerProviderException $e) {
43
                throw new ServiceNotCreatedException(
44
                    sprintf(
45
                        'The entity manager \'%s\' could not be found for service \'%s\'',
46
                        $name,
47
                        $serviceName
48
                    ),
49
                    $e->getCode(),
50
                    $e
51
                );
52
            }
53
        }
54
55
        if (!$entityManager instanceof EntityManagerInterface) {
56
            throw new ServiceNotCreatedException(
57
                sprintf(
58
                    'The entity manager must be an object of type \'%s\'; \'%s\' provided for service \'%s\'',
59
                    EntityManagerInterface::class,
60
                    is_object($entityManager) ? get_class($entityManager) : gettype($entityManager),
61
                    $serviceName
62
                )
63
            );
64
        }
65
66
        return $entityManager;
67
    }
68
}
69