View source
<?php
namespace Drupal\monitoring\Plugin\monitoring\SensorPlugin;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
class TemporaryFilesUsagesSensorPlugin extends DatabaseAggregatorSensorPlugin {
protected $configurableConditions = FALSE;
protected $configurableTable = FALSE;
protected $configurableVerboseOutput = FALSE;
protected function getQuery() {
$query = parent::getQuery();
$query
->innerJoin('file_usage', 'fu', 'fu.fid = file_managed.fid');
$query
->groupBy('file_managed.fid');
return $query;
}
protected function getAggregateQuery() {
$query = parent::getAggregateQuery();
$query
->innerJoin('file_usage', 'fu', 'fu.fid = file_managed.fid');
return $query;
}
protected function addAggregateExpression(SelectInterface $select) {
$select
->addExpression('COUNT(DISTINCT file_managed.fid)', 'records_count');
}
public function buildTableHeader($rows = []) {
return [
t('ID'),
t('Filename'),
t('Usages'),
t('Status'),
];
}
protected function buildTableRows(array $results) {
$entity_type_manager = \Drupal::entityTypeManager();
$rows = [];
foreach ($results as $delta => $row) {
$types = [];
$fid = $row->fid;
$file = File::load($fid);
$file_usage = \Drupal::service('file.usage');
foreach ($file_usage
->listUsage($file) as $usages) {
foreach ($usages as $type => $usage) {
foreach ($usage as $id => $value) {
if ($entity_type_manager
->hasDefinition($type)) {
$entity = $entity_type_manager
->getStorage($type)
->load($id);
if ($entity && $entity
->hasLinkTemplate('canonical')) {
$types[] = $entity
->toLink()
->toRenderable();
}
else {
$types[] = [
'#markup' => t('Missing @type/@id', [
'@type' => $type,
'@id' => $id,
]),
];
}
}
else {
$types[] = [
'#markup' => $type . '/' . $id,
];
}
$types[] = [
'#markup' => ', ',
];
}
}
}
if (!empty($types)) {
array_pop($types);
$filename = Link::fromTextAndUrl($file
->getFilename(), Url::fromUri(file_create_url($file
->getFileUri())));
$status = Link::createFromRoute('Make permanent', 'monitoring.make_file_permanent', [
'monitoring_sensor_config' => $this->sensorConfig
->id(),
'file' => $fid,
]);
$rows[] = [
'fid' => $fid,
'filename' => $filename,
'usages' => render($types),
'status' => $status,
];
}
}
return $rows;
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$form['aggregation']['#access'] = FALSE;
return $form;
}
}