PropertyEntityReference.php in User Merge 2.x
File
src/Plugin/UserMerge/Property/PropertyEntityReference.php
View source
<?php
namespace Drupal\usermerge\Plugin\UserMerge\Property;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\user\UserInterface;
use Drupal\usermerge\Exception\UserMergeException;
use Symfony\Component\DependencyInjection\ContainerInterface;
class PropertyEntityReference extends UserMergePropertyBase {
protected $connection;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, Connection $connection) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager);
$this->connection = $connection;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'), $container
->get('database'));
}
public function process(UserInterface $retired, UserInterface $retained, array $settings = []) : void {
try {
$fields = $this
->getUserReferenceFields();
} catch (InvalidPluginDefinitionException|PluginNotFoundException $e) {
throw new UserMergeException('An error occurred during searching for user reference fields.');
}
foreach ($fields as $field) {
try {
$table_mapping = $this->entityTypeManager
->getStorage($field
->getTargetEntityTypeId())
->getTableMapping();
} catch (InvalidPluginDefinitionException|PluginNotFoundException $e) {
throw new UserMergeException('An error occurred during loading field storage.');
}
$tables = [];
$tables[] = $table_mapping
->getDedicatedDataTableName($field);
$tables[] = $table_mapping
->getDedicatedRevisionTableName($field);
$field_name = $field
->getName() . '_target_id';
foreach ($tables as $table_name) {
$exists = $this->connection
->schema()
->tableExists($table_name);
if (!$exists) {
continue;
}
$this->connection
->update($table_name)
->fields([
$field_name => $retained
->id(),
])
->condition($field_name, $retired
->id())
->execute();
}
}
}
private function getUserReferenceFields() {
$references = [];
$fields = $this->entityTypeManager
->getStorage('field_storage_config')
->loadMultiple();
foreach ($fields as $field) {
if ($field
->getType() != 'entity_reference') {
continue;
}
if ($field
->getSetting('target_type') != 'user') {
continue;
}
$references[] = $field;
}
return $references;
}
}