-
-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathTablePrefixTrait.php
55 lines (42 loc) · 1.42 KB
/
TablePrefixTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
declare(strict_types=1);
/**
* @author Rix Beck <[email protected]>
*/
namespace Bolt\Doctrine;
use Bolt\Common\Str;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\ObjectManager;
use InvalidArgumentException;
trait TablePrefixTrait
{
/** @var string[] */
private $tablePrefixes = [];
/** @var ManagerRegistry */
private $registry;
protected function setTablePrefix(ObjectManager $manager, string $prefix)
{
$key = spl_object_hash($manager);
$this->tablePrefixes[$key] = empty($prefix) ? '' : Str::ensureEndsWith($prefix, '_');
return $this;
}
protected function setTablePrefixes($tablePrefixes, ManagerRegistry $managerRegistry)
{
$prefixes = (array) $tablePrefixes;
$this->registry = $managerRegistry;
foreach ($prefixes as $em => $prefix) {
try {
$manager = $managerRegistry->getManager(is_int($em) ? 'default' : $em);
$this->setTablePrefix($manager, $prefix);
} catch (InvalidArgumentException $exception) {
throw new InvalidArgumentException(sprintf("'%s' entity manager not defined for table prefix '%s'", $em, $prefix));
}
}
return $this;
}
protected function getTablePrefix(ObjectManager $manager): string
{
$key = spl_object_hash($manager);
return $this->tablePrefixes[$key] ?? '';
}
}