EntityUuidMapper.php in Commerce Core 8.2
File
src/EntityUuidMapper.php
View source
<?php
namespace Drupal\commerce;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
class EntityUuidMapper implements EntityUuidMapperInterface {
protected $database;
protected $entityTypeManager;
protected $map = [];
public function __construct(Connection $database, EntityTypeManagerInterface $entity_type_manager) {
$this->database = $database;
$this->entityTypeManager = $entity_type_manager;
}
public function mapToIds($entity_type_id, array $uuids) {
$ids = [];
foreach ($uuids as $index => $uuid) {
if (isset($this->map[$entity_type_id][$uuid])) {
$ids[$uuid] = $this->map[$entity_type_id][$uuid];
unset($uuids[$index]);
}
}
if (!empty($uuids)) {
$entity_type = $this->entityTypeManager
->getDefinition($entity_type_id);
$id_key = $entity_type
->getKey('id');
$uuid_key = $entity_type
->getKey('uuid');
$loaded_uuids = $this->database
->select($entity_type
->getBaseTable(), 't')
->fields('t', [
$uuid_key,
$id_key,
])
->condition($uuid_key, $uuids, 'IN')
->execute()
->fetchAllKeyed(1, 0);
foreach ($loaded_uuids as $id => $uuid) {
$ids[$uuid] = $id;
$this->map[$entity_type_id][$uuid] = $id;
}
}
return $ids;
}
public function mapFromIds($entity_type_id, array $ids) {
$uuids = [];
foreach ($ids as $index => $id) {
if (isset($this->map[$entity_type_id])) {
$uuid = array_search($id, $this->map[$entity_type_id]);
if ($uuid) {
$uuids[$id] = $uuid;
unset($ids[$index]);
}
}
}
if (!empty($ids)) {
$entity_type = $this->entityTypeManager
->getDefinition($entity_type_id);
$id_key = $entity_type
->getKey('id');
$uuid_key = $entity_type
->getKey('uuid');
$loaded_ids = $this->database
->select($entity_type
->getBaseTable(), 't')
->fields('t', [
$uuid_key,
$id_key,
])
->condition($id_key, $ids, 'IN')
->execute()
->fetchAllKeyed(0, 1);
foreach ($loaded_ids as $uuid => $id) {
$uuids[$id] = $uuid;
$this->map[$entity_type_id][$uuid] = $id;
}
}
return $uuids;
}
}