Completed
Push — master ( b794f5...f9eb18 )
by Andrii
03:04
created

EntityManager::findId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * HiAPI Yii2 base project for building API
4
 *
5
 * @link      https://github.com/hiqdev/hiapi
6
 * @package   hiapi
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiapi\components;
12
13
use Yii;
14
15
class EntityManager extends \yii\base\Component implements EntityManagerInterface
16
{
17
    /**
18
     * @var array
19
     */
20
    public $repositories = [];
21
22
    /**
23
     * @var ConnectionInterface
24
     */
25
    public $db;
26
27
    public function __construct(
28
        ConnectionInterface $db,
29
        array $config = []
30
    ) {
31
        $this->db = $db;
32
33
        parent::__construct($config);
34
    }
35
36
    /**
37
     * Get database connection.
38
     * @return ConnectionInterface
39
     */
40
    public function getConnection()
41
    {
42
        return $this->db;
43
    }
44
45
    /**
46
     * Get entity repository by entity or class.
47
     * @param object|string $entityClass entity or class
48
     * @return RepositoryInterface
49
     */
50
    public function getRepository($entityClass)
51
    {
52
        if (is_object($entityClass)) {
53
            $entityClass = get_class($entityClass);
54
        }
55
56
        if (!isset($this->repositories[$entityClass])) {
57
            throw new \Exception("no repository defined for: $entityClass");
58
        }
59
60
        if (!is_object($this->repositories[$entityClass])) {
61
            $this->repositories[$entityClass] = Yii::createObject($this->repositories[$entityClass]);
62
        }
63
64
        return $this->repositories[$entityClass];
65
    }
66
67
    /**
68
     * Save given entity into it's repository.
69
     * @param object $entity
70
     */
71
    public function save($entity)
72
    {
73
        $repo = $this->getRepository($entity);
74
        $repo->save($entity);
75
    }
76
77
    /**
78
     * Create entity of given class with given data.
79
     * @param string $entityClass
80
     * @param array $data
81
     * @return object
82
     */
83
    public function create($entityClass, array $data)
84
    {
85
        return $this->getRepository($entityClass)->create($data);
86
    }
87
88
    /**
89
     * XXX TODO think of the whole process:
90
     * alternative: find and populate whole entity
91
     * @param object $entity 
92
     * @return string|int
93
     */
94
    public function findId($entity)
95
    {
96
        return $this->getRepository($entity)->findId($entity);
97
    }
98
}
99