UserData.php in Drupal 10
File
core/modules/user/src/UserData.php
View source
<?php
namespace Drupal\user;
use Drupal\Core\Database\Connection;
class UserData implements UserDataInterface {
protected $connection;
public function __construct(Connection $connection) {
$this->connection = $connection;
}
public function get($module, $uid = NULL, $name = NULL) {
$query = $this->connection
->select('users_data', 'ud')
->fields('ud')
->condition('module', $module);
if (isset($uid)) {
$query
->condition('uid', $uid);
}
if (isset($name)) {
$query
->condition('name', $name);
}
$result = $query
->execute();
if (isset($name) && isset($uid)) {
$result = $result
->fetchAllAssoc('uid');
if (isset($result[$uid])) {
return $result[$uid]->serialized ? unserialize($result[$uid]->value) : $result[$uid]->value;
}
return NULL;
}
$return = [];
if (isset($uid)) {
foreach ($result as $record) {
$return[$record->name] = $record->serialized ? unserialize($record->value) : $record->value;
}
return $return;
}
if (isset($name)) {
foreach ($result as $record) {
$return[$record->uid] = $record->serialized ? unserialize($record->value) : $record->value;
}
return $return;
}
foreach ($result as $record) {
$return[$record->uid][$record->name] = $record->serialized ? unserialize($record->value) : $record->value;
}
return $return;
}
public function set($module, $uid, $name, $value) {
$serialized = (int) (!is_scalar($value));
if ($serialized) {
$value = serialize($value);
}
$this->connection
->merge('users_data')
->keys([
'uid' => $uid,
'module' => $module,
'name' => $name,
])
->fields([
'value' => $value,
'serialized' => $serialized,
])
->execute();
}
public function delete($module = NULL, $uid = NULL, $name = NULL) {
$query = $this->connection
->delete('users_data');
if (isset($module)) {
$query
->condition('module', (array) $module, 'IN');
}
if (isset($uid)) {
$query
->condition('uid', (array) $uid, 'IN');
}
if (isset($name)) {
$query
->condition('name', (array) $name, 'IN');
}
$query
->execute();
}
}