View source
<?php
namespace Drupal\library\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Drupal\library\Entity\LibraryItem;
class OverdueOverview extends ControllerBase {
public function listing() : string {
$renderer = \Drupal::service('renderer');
$manager = \Drupal::entityTypeManager();
$itemStorage = $manager
->getStorage('library_item');
$transactionStorage = $manager
->getStorage('library_transaction');
$nodeStorage = $manager
->getStorage('node');
$userStorage = $manager
->getStorage('user');
$dateFormatter = \Drupal::service('date.formatter');
$data['elements'] = [
'#type' => 'table',
'#title' => $this
->t('Item history'),
'#header' => [
'Item',
'Patron',
'Due Date',
'Last comment',
'Edit',
],
];
$items = $itemStorage
->getQuery()
->condition('library_status', LibraryItem::ITEM_UNAVAILABLE)
->execute();
$loadedItems = $itemStorage
->loadMultiple($items);
foreach ($loadedItems as $item) {
$format_title = '';
if ($item
->get('nid')
->getValue()) {
$node = $nodeStorage
->load($item
->get('nid')
->getValue()[0]['target_id']);
$label = $node
->getTitle();
if ($item
->get('barcode')->value) {
$label .= ' (' . $item
->get('barcode')->value . ')';
}
$format_title = [
'#type' => 'link',
'#title' => $label,
'#url' => Url::fromRoute('entity.node.canonical', [
'node' => $node
->id(),
]),
];
$format_title = $renderer
->render($format_title);
}
$transaction = $item
->getLatestTransactionDue();
if ($transaction && count($transaction) == 1) {
$loadedTransaction = $transactionStorage
->load(array_pop($transaction));
$patronName = '';
if ($loadedTransaction
->get('uid')
->getValue()) {
$patron = $userStorage
->load($loadedTransaction
->get('uid')
->getValue()[0]['target_id']);
if ($patron) {
$patronName = [
'#type' => 'link',
'#title' => $patron
->getDisplayName(),
'#url' => Url::fromRoute('entity.user.canonical', [
'user' => $patron
->id(),
]),
];
$patronName = $renderer
->render($patronName);
$patronId = $patron
->id();
}
}
$due = '';
if ($loadedTransaction
->get('due_date')->value > 0) {
$due = $dateFormatter
->format($loadedTransaction
->get('due_date')->value, 'short');
}
$editLink = [
'#type' => 'link',
'#title' => $this
->t('Add note'),
'#url' => Url::fromRoute('library.edit_transaction', [
'transaction' => $loadedTransaction
->id(),
]),
];
$data['elements']['#rows'][$patronId . '_' . $item
->id()] = [
$format_title,
$patronName,
$due,
$this
->formatMarkup($loadedTransaction
->get('notes')->value),
$renderer
->render($editLink),
];
ksort($data['elements']['#rows']);
}
}
return $data;
}
private function formatMarkup($data) : string {
$escaped = [
'#markup' => nl2br($data),
];
$formatted = \Drupal::service('renderer')
->render($escaped);
return $formatted;
}
}