html_importer-8.x-2.x-dev/src/Controller/ListImportNodesController.php
src/Controller/ListImportNodesController.php
<?php
namespace Drupal\html_importer\Controller;
use Drupal\Core\Url;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Link;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Database\Connection;
/**
* Controller to list down created node.
*
* @package Drupal\html_importer.
*/
class ListImportNodesController extends ControllerBase {
/**
* Database connection.
*
* @var \Drupal\Core\Database\Connection
*/
protected $databaseConnection;
/**
* Constructs Dashboard object.
*
* @param \Drupal\Core\Database\Connection $database_connection
* The database connection service.
*/
public function __construct(Connection $database_connection) {
$this->databaseConnection = $database_connection;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
// Instantiates this form class.
return new static(
// Load the service required to construct this class.
$container->get('database')
);
}
/**
* Dashboard to list down node created by HTMl file.
*/
public function nodeDashboard() {
$uri = \Drupal::config('system.file')->get('default_scheme') . "://html_file/";
$files = $this->getDirFiles($uri);
$header = [
['data' => $this->t('Sr. No')],
['data' => $this->t('File name')],
['data' => $this->t('Operations')],
];
$rows = [];
$number = 1;
foreach ($files as $file) {
$file = str_replace("\\", "/", $file);
$fid = $this->getFileId($file);
$row = [];
// Prepare row of dashboard table.
$row[] = $number;
$row[] = $file;
if ($fid) {
$row[] = Link::fromTextAndUrl($this->t('Delete'), Url::fromRoute('html.delete.file', ['source' => $fid]));
}
else {
$sub_dir = pathinfo($file);
$extract_val = explode("/", $sub_dir['dirname']);
$base_dir = end($extract_val);
$file_name = $sub_dir['filename'];
$row[] = Link::fromTextAndUrl($this->t('Delete'), Url::fromRoute('html.delete.file', ['source' => $base_dir . '-' . $file_name]));
}
// Add result into dashboard table.
$rows[] = ['data' => $row];
$number++;
}
// Prepare dashboard.
$build['table'] = [
'#type' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => $this->t("No data found"),
];
// Add pager into dashboard table.
$build['pager'] = ['#type' => 'pager'];
return $build;
}
/**
* List the files inside directory.
*
* @param string $path
* The file path.
*
* @return array
* Return files.
*/
public function getDirFiles($path) {
$rii = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
$files = [];
foreach ($rii as $file) {
if (!$file->isDir()) {
$files[] = $file->getPathname();
}
}
return $files;
}
/**
* Get file Fid.
*
* @param string $uri
* The file path.
*
* @return mixed
* Return file uri.
*/
public function getFileId($uri) {
$query = $this->databaseConnection->select('file_managed', 'f')
->condition('f.uri', $uri)
->fields('f', ['fid'])
->execute();
$result = $query->fetchField();
return $result;
}
}
