Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 98
0.00% covered (danger)
0.00%
0 / 24
CRAP
0.00% covered (danger)
0.00%
0 / 1
EntityManager
0.00% covered (danger)
0.00%
0 / 98
0.00% covered (danger)
0.00%
0 / 24
2352
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setUseEntityHashName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 addColumn
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 tableNameByClass
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 simpleClassName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 tableNames
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 tableName
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 tableColumns
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 primaryKey
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
42
 isColumn
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 primaryKeyValue
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 primaryKeyCondition
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 primaryKeyConditionParams
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 isPrimaryKeyAutoIncrement
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 safeTableName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 allTableColumns
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 insert
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 update
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 findById
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 deleteById
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 deleteByIds
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 save
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 setByDataArray
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 fetchDataArray
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3namespace Dynart\Micro\Entities;
4
5use Dynart\Micro\ConfigInterface;
6use Dynart\Micro\EventServiceInterface;
7
8class EntityManager {
9
10    const COLUMN_TYPE = 'type';
11    const COLUMN_SIZE = 'size';
12    const COLUMN_FIX_SIZE = 'fixSize';
13    const COLUMN_NOT_NULL = 'notNull';
14    const COLUMN_AUTO_INCREMENT = 'autoIncrement';
15    const COLUMN_DEFAULT = 'default';
16    const COLUMN_PRIMARY_KEY = 'primaryKey';
17    const COLUMN_FOREIGN_KEY = 'foreignKey';
18    const COLUMN_ON_DELETE = 'onDelete';
19    const COLUMN_ON_UPDATE = 'onUpdate';
20
21    const TYPE_INT = 'int';
22    const TYPE_LONG = 'long';
23    const TYPE_FLOAT = 'float';
24    const TYPE_DOUBLE = 'double';
25    const TYPE_NUMERIC = 'numeric';
26    const TYPE_STRING = 'string';
27    const TYPE_BOOL = 'bool';
28    const TYPE_DATE = 'date';
29    const TYPE_TIME = 'time';
30    const TYPE_DATETIME = 'datetime';
31    const TYPE_BLOB = 'blob';
32
33    const DEFAULT_NOW = 'now';
34
35    const ACTION_CASCADE = 'cascade';
36    const ACTION_SET_NULL = 'set_null';
37
38    protected array $tableColumns = [];
39    protected array $tableNames = [];
40    protected array $primaryKeys = [];
41    protected string $tableNamePrefix = '';
42    protected bool $useEntityHashName = false;
43
44    public function __construct(
45        protected ConfigInterface $config,
46        protected Database $db,
47        protected EventServiceInterface $events,
48    ) {
49        $this->tableNamePrefix = $db->configValue('table_prefix');
50    }
51
52    public function setUseEntityHashName(bool $value): void {
53        $this->useEntityHashName = $value;
54    }
55
56    public function addColumn(string $className, string $columnName, array $columnData): void {
57        if (!array_key_exists($className, $this->tableNames)) {
58            $this->tableNames[$className] = $this->tableNameByClass($className);
59            $this->tableColumns[$className] = [];
60        }
61        $this->tableColumns[$className][$columnName] = $columnData;
62    }
63
64    public function tableNameByClass(string $className, bool $withPrefix = true): string {
65        $simpleClassName = $this->simpleClassName($className);
66        if ($this->useEntityHashName) {
67            return '#'.$simpleClassName;
68        }
69        return ($withPrefix ? $this->tableNamePrefix : '').strtolower($simpleClassName);
70    }
71
72    protected function simpleClassName(string $fullClassName): string {
73        return substr(strrchr($fullClassName, '\\'), 1);
74    }
75
76    public function tableNames(): array {
77        return $this->tableNames;
78    }
79
80    public function tableName(string $className): string {
81        if (!array_key_exists($className, $this->tableNames)) {
82            throw new EntityManagerException("Table definition doesn't exist for ".$className);
83        }
84        return $this->tableNames[$className];
85    }
86
87    public function tableColumns(string $className): array {
88        if (!array_key_exists($className, $this->tableColumns)) {
89            throw new EntityManagerException("Table definition doesn't exist for ".$className);
90        }
91        return $this->tableColumns[$className];
92    }
93
94    public function primaryKey(string $className): string|array|null {
95        if (array_key_exists($className, $this->primaryKeys)) {
96            return $this->primaryKeys[$className];
97        }
98        $primaryKey = [];
99        foreach ($this->tableColumns($className) as $columnName => $column) {
100            if ($this->isColumn($column, self::COLUMN_PRIMARY_KEY)) {
101                $primaryKey[] = $columnName;
102            }
103        }
104        $result = empty($primaryKey) ? null : (count($primaryKey) > 1 ? $primaryKey : $primaryKey[0]);
105        $this->primaryKeys[$className] = $result;
106        return $result;
107    }
108
109    public function isColumn(array $column, string $name): bool {
110        return array_key_exists($name, $column) && $column[$name] === true;
111    }
112
113    public function primaryKeyValue(string $className, array $data): mixed {
114        $primaryKey = $this->primaryKey($className);
115        if (is_array($primaryKey)) {
116            $result = [];
117            foreach ($primaryKey as $pk) {
118                $result[] = $data[$pk];
119            }
120            return $result;
121        } else {
122            return $data[$primaryKey];
123        }
124    }
125
126    public function primaryKeyCondition(string $className): string {
127        $primaryKey = $this->primaryKey($className);
128        if (is_array($primaryKey)) {
129            $conditions = [];
130            foreach ($primaryKey as $i => $pk) {
131                $conditions[] = $this->db->escapeName($pk).' = :pkValue'.$i;
132            }
133            return join(' and ', $conditions);
134        } else {
135            return $this->db->escapeName($primaryKey).' = :pkValue';
136        }
137    }
138
139    public function primaryKeyConditionParams(string $className, mixed $pkValue): array {
140        $result = [];
141        $primaryKey = $this->primaryKey($className);
142        if (is_array($primaryKey) && is_array($pkValue)) {
143            foreach ($pkValue as $i => $v) {
144                $result[':pkValue'.$i] = $v;
145            }
146        } else {
147            $result[':pkValue'] = $pkValue;
148        }
149        return $result;
150    }
151
152    public function isPrimaryKeyAutoIncrement(string $className): bool {
153        $pkName = $this->primaryKey($className);
154        if (is_array($pkName)) { // multi-column primary keys can't be auto incremented
155            return false;
156        }
157        $pkColumn = $this->tableColumns[$className][$pkName];
158        return $this->isColumn($pkColumn, self::COLUMN_AUTO_INCREMENT);
159    }
160
161    public function safeTableName(string $className, bool $withPrefix = true): string {
162        return $this->db->escapeName($this->tableNameByClass($className, $withPrefix));
163    }
164
165    public function allTableColumns(): array {
166        return $this->tableColumns;
167    }
168
169    public function insert(string $className, array $data): string|false {
170        $this->db->insert($this->tableName($className), $data);
171        return $this->db->lastInsertId();
172    }
173
174    public function update(string $className, array $data, string $condition = '', array $conditionParams = []): void {
175        $this->db->update($this->tableName($className), $data, $condition, $conditionParams);
176    }
177
178    public function findById(string $className, mixed $id): Entity {
179        $condition = $this->primaryKeyCondition($className);
180        $safeTableName = $this->safeTableName($className);
181        $sql = "select * from $safeTableName where $condition";
182        $params = $this->primaryKeyConditionParams($className, $id);
183        $result = $this->db->fetch($sql, $params, $className);
184        $result->setNew(false);
185        return $result;
186    }
187
188    public function deleteById(string $className, int $id): void {
189        $sql = "delete from {$this->safeTableName($className)} where id = :id limit 1";
190        $this->db->query($sql, [':id' => $id]);
191    }
192
193    public function deleteByIds(string $className, array $ids): void {
194        [$condition, $params] = $this->db->getInConditionAndParams($ids);
195        $sql = "delete from {$this->safeTableName($className)} where id in ($condition)";
196        $this->db->query($sql, $params);
197    }
198
199    public function save(Entity $entity): void {
200        $this->events->emit($entity->beforeSaveEvent(), [$entity]);
201        $className = get_class($entity);
202        $tableName = $this->tableName($className);
203        $data = $this->fetchDataArray($entity);
204        if ($entity->isNew()) {
205            $this->db->insert($tableName, $data);
206            if ($this->isPrimaryKeyAutoIncrement($className)) {
207                $pkName = $this->primaryKey($className);
208                $entity->$pkName = $this->db->lastInsertId();
209            }
210        } else {
211            $this->db->update(
212                $tableName, $data,
213                $this->primaryKeyCondition($className),
214                $this->primaryKeyConditionParams($className, $this->primaryKeyValue($className, $data))
215            );
216        }
217        $this->events->emit($entity->afterSaveEvent(), [$entity]);
218    }
219
220    public function setByDataArray(Entity $entity, array $data): void {
221        $className = get_class($entity);
222        $columnKeys = array_keys($this->tableColumns($className));
223        foreach ($data as $n => $v) {
224            if (!array_key_exists($n, $columnKeys)) {
225                throw new EntityManagerException("Column '$n' doesn't exist in $className");
226            }
227            $entity->$n = $v;
228        }
229    }
230
231    public function fetchDataArray(Entity $entity): array {
232        $columnKeys = array_keys($this->tableColumns(get_class($entity)));
233        $data = [];
234        foreach ($columnKeys as $ck) {
235            $data[$ck] = $entity->$ck;
236        }
237        return $data;
238    }
239}