You are here

protected function TemporaryFilesUsagesSensorPlugin::buildTableRows in Monitoring 8

Builds the rows of a table.

Parameters

array $results: Array of query results.

Return value

array $rows The render array with the table rows.

Overrides DatabaseAggregatorSensorPlugin::buildTableRows

File

src/Plugin/monitoring/SensorPlugin/TemporaryFilesUsagesSensorPlugin.php, line 79

Class

TemporaryFilesUsagesSensorPlugin
Monitors temporary files usages.

Namespace

Drupal\monitoring\Plugin\monitoring\SensorPlugin

Code

protected function buildTableRows(array $results) {
  $entity_type_manager = \Drupal::entityTypeManager();
  $rows = [];
  foreach ($results as $delta => $row) {
    $types = [];
    $fid = $row->fid;
    $file = File::load($fid);

    /** @var \Drupal\file\FileUsage\FileUsageInterface $file_usage */
    $file_usage = \Drupal::service('file.usage');

    // List usages for the file.
    foreach ($file_usage
      ->listUsage($file) as $usages) {
      foreach ($usages as $type => $usage) {
        foreach ($usage as $id => $value) {

          // Check if the entity type has a definition for this type.
          if ($entity_type_manager
            ->hasDefinition($type)) {
            $entity = $entity_type_manager
              ->getStorage($type)
              ->load($id);

            // Create the link.
            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,
            ];
          }

          // Separate the files usages list with a comma.
          $types[] = [
            '#markup' => ', ',
          ];
        }
      }
    }

    // If there are usages, format the rows to be rendered.
    if (!empty($types)) {

      // Delete the last unnecessary comma.
      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;
}