public function LastLoginBlock::build in Login History 8
Builds and returns the renderable array for this block plugin.
If a block should not be rendered because it has no content, then this method must also ensure to return no content: it must then only return an empty array, or an empty array with #cache set (with cacheability metadata indicating the circumstances for it being empty).
Return value
array A renderable array representing the content of the block.
Overrides BlockPluginInterface::build
See also
\Drupal\block\BlockViewBuilder
File
- src/
Plugin/ Block/ LastLoginBlock.php, line 82
Class
- LastLoginBlock
- Provides a block with information about the user's last login.
Namespace
Drupal\login_history\Plugin\BlockCode
public function build() {
$build = [];
$last_login = FALSE;
if (!$this->currentUser
->isAnonymous()) {
// Get the previous login information.
$last_login = \Drupal::database()
->select('login_history', 'lh')
->fields('lh', [
'login',
'hostname',
'one_time',
'user_agent',
])
->condition('uid', $this->currentUser
->id())
->orderBy('login', 'DESC')
->range(1, 1)
->execute()
->fetch();
}
if ($last_login) {
$request = $this->requestStack
->getCurrentRequest();
$hostname = $last_login->hostname == $request
->getClientIP() ? $this
->t('this IP address') : $last_login->hostname;
$user_agent = $last_login->user_agent == $request->server
->get('HTTP_USER_AGENT') ? $this
->t('this browser') : $last_login->user_agent;
$build['last_login']['#markup'] = '<p>' . $this
->t('You last logged in from @hostname using @user_agent.', [
'@hostname' => $hostname,
'@user_agent' => $user_agent,
]) . '</p>';
if ($this->currentUser
->hasPermission('view own login history')) {
$build['view_report'] = [
'#type' => 'more_link',
'#title' => $this
->t('View your login history'),
'#url' => Url::fromRoute('login_history.user_report', [
'user' => $this->currentUser
->id(),
]),
];
}
}
// Cache by session.
$build['#cache'] = [
'contexts' => [
'session',
],
];
return $build;
}