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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
<?php
namespace GeniBase\Storager;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Gedcomx\Common\ExtensibleData;
use GeniBase\Util;
use Gedcomx\Conclusion\Identifier;
class IdentifierStorager extends GeniBaseStorager
{
protected function getObject($o = null)
{
return new Identifier($o);
}
public function save($entity, ExtensibleData $context = null, $o = null)
{
if (! $entity instanceof Identifier) {
$entity = $this->getObject($entity);
}
$t_ids = $this->dbs->getTableName('identifiers');
$ent = $entity->toArray();
$data = Util::arraySliceKeys($ent, 'value');
if (empty($id = $context->getId())) {
throw new \UnexpectedValueException('Context ID required!');
} else {
$data['id'] = $id;
}
if (! empty($ent['type']) && (! empty($r = (int) $this->getTypeId($ent['type'])))) {
$data['type_id'] = $r;
}
parent::save($entity, $context, $o);
try {
$this->dbs->getDb()->insert($t_ids, $data);
} catch (UniqueConstraintViolationException $e) {
unset($data['id']);
$this->dbs->getDb()->update($t_ids, $data, ['id' => $id]);
}
return $entity;
}
protected function loadListRaw($context, $o)
{
if (empty($id = $context->getId())) {
throw new \UnexpectedValueException('Context local ID required!');
}
$t_ids = $this->dbs->getTableName('identifiers');
$t_types = $this->dbs->getTableName('types');
$result = $this->dbs->getDb()->fetchAll(
"SELECT id.*, tp.uri AS type FROM $t_ids AS id " .
"LEFT JOIN $t_types AS tp ON (id.type_id = tp._id) ".
"WHERE id.id = ?",
[$id]
);
return $result;
}
public function getIdByIdentifier($identifiers)
{
if (! is_array($identifiers)) {
$identifiers = [$identifiers];
}
$ids = [];
foreach ($identifiers as $x) {
if ($x instanceof Identifier) {
$ids[] = $x->getValue();
} elseif (is_array($x)) {
foreach ($x as $y) {
if ($y instanceof Identifier) {
$ids[] = $y->getValue();
} else {
$ids[] = $y;
}
}
} else {
$ids[] = $x;
}
}
$t_ids = $this->dbs->getTableName('identifiers');
$q = "SELECT id FROM $t_ids WHERE value IN (?) LIMIT 1";
$result = $this->dbs->getDb()->fetchColumn(
$q,
[$ids],
0,
[\Doctrine\DBAL\Connection::PARAM_STR_ARRAY]
);
return $result;
}
}