Completed
Push — master ( d9ba74...595cfb )
by Stefano
20:57
created

DataMapperManager::getDataMapperForEntity()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 2

Importance

Changes 5
Bugs 1 Features 2
Metric Value
c 5
b 1
f 2
dl 0
loc 22
ccs 14
cts 14
cp 1
rs 9.2
cc 2
eloc 13
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * @author Stefano Torresi (http://stefanotorresi.it)
4
 * @license See the file LICENSE.txt for copying permission.
5
 * ************************************************
6
 */
7
8
namespace Thorr\Persistence\DataMapper\Manager;
9
10
use Assert\Assertion;
11
use Thorr\Persistence\DataMapper\DataMapperInterface;
12
use Zend\ServiceManager\AbstractPluginManager;
13
use Zend\ServiceManager\ConfigInterface;
14
use Zend\ServiceManager\Exception;
15
16
/**
17
 * @method DataMapperInterface get($name)
18
 */
19
class DataMapperManager extends AbstractPluginManager implements DataMapperManagerInterface
20
{
21
    /**
22
     * @var array
23
     */
24
    protected $entityDataMapperMap;
25
26
    /**
27
     * {@inheritdoc}
28
     */
29 18
    public function __construct(ConfigInterface $configuration = null)
30
    {
31 18
        parent::__construct($configuration);
32
33 18
        if (! $configuration) {
34 10
            return;
35
        }
36
37 9
        Assertion::isInstanceOf($configuration, DataMapperManagerConfig::class);
38
        /* @var $configuration DataMapperManagerConfig */
39
40 8
        $this->entityDataMapperMap = $configuration->getEntityDataMapperMap();
41 8
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 8
    public function validatePlugin($dataMapper)
47
    {
48 8
        Assertion::isInstanceOf($dataMapper, DataMapperInterface::class, 'Invalid data mapper');
49 7
        Assertion::classExists($dataMapper->getEntityClass(), 'Invalid entity class');
50 6
    }
51
52
    /**
53
     * @param string $entityClass
54
     *
55
     * @return DataMapperInterface
56
     */
57 8
    public function getDataMapperForEntity($entityClass)
58
    {
59 8
        Assertion::keyIsset($this->entityDataMapperMap, $entityClass, sprintf(
60 8
            "Could not find data mapper service name for entity class '%s'",
61
            $entityClass
62 8
        ));
63
64 5
        $entityDMServiceName = $this->entityDataMapperMap[$entityClass];
65
66 5
        $dataMapper = $this->get($entityDMServiceName);
67
68 5
        if (! is_a($dataMapper->getEntityClass(), $entityClass, true)) {
69 1
            throw new Exception\RuntimeException(sprintf(
70 1
                '"%s" entity class mismatch: expected "%s", got "%s"',
71 1
                $entityDMServiceName,
72 1
                $entityClass,
73 1
                $dataMapper->getEntityClass()
74 1
            ));
75
        }
76
77 4
        return $dataMapper;
78
    }
79
}
80