html_importer-8.x-2.x-dev/src/BatchHandler/ImportBatchManager.php
src/BatchHandler/ImportBatchManager.php
<?php
namespace Drupal\html_importer\BatchHandler;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Field\FieldFilteredMarkup;
use Drupal\Core\Logger\LoggerChannelFactory;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Exception;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\StringTranslation\TranslationManager;
use Drupal\Core\Path\AliasManager;
/**
* Class to Process HTML files.
*
* @package Drupal\html_importer.
*/
class ImportBatchManager {
/**
* Logger service object.
*
* @var \Drupal\Core\Logger\LoggerChannelFactory
*/
protected $loggerFactory;
/**
* Message service object.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* Translation service object.
*
* @var \Drupal\Core\StringTranslation\TranslationManager
*/
protected $translation;
/**
* Alias service object.
*
* @var \Drupal\Core\Path\AliasManager
*/
protected $aliasManager;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs ImportBatchManager object.
*
* @param \Drupal\Core\Logger\LoggerChannelFactory $logger_factory
* Drupal Logger Factory service.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* Drupal message services.
* @param \Drupal\Core\StringTranslation\TranslationManager $translation
* Drupal translation services.
* @param \Drupal\Core\Path\AliasManager $alias_manager
* Drupal alias manager services.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
*/
public function __construct(LoggerChannelFactory $logger_factory, MessengerInterface $messenger, TranslationManager $translation, AliasManager $alias_manager, EntityTypeManagerInterface $entity_type_manager) {
$this->loggerFactory = $logger_factory;
$this->messenger = $messenger;
$this->translation = $translation;
$this->aliasManager = $alias_manager;
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public function create(ContainerInterface $container) {
return new static(
$container->get('logger.factory'),
$container->get('messenger'),
$container->get('string_translation'),
$container->get('path.alias_manager'),
$container->get('entity_type.manager')
);
}
/**
* Batch process to process Files.
*
* @param string $files
* The file path.
* @param string $folder_uri
* The file extension.
* @param string $context
* The batch context array.
*
* @throws \Exception
*/
public function bathProcess($files, $folder_uri, $context) {
// Iterate all the directory files.
foreach ($files as $file_uri) {
$node_id = NULL;
$filename = reset(explode('.', $file_uri->filename));
// Set node title.
$node_content['title'] = $filename;
$node_url = '/' . str_replace(' ', '_', strtolower($node_content['title']));
// Set node content.
$node_content['content'] = $this->getFileContent($file_uri->uri);
if (!empty($node_content['content'])) {
try {
// Create and update Node.
$path = $this->aliasManager->getPathByAlias($node_url);
if (preg_match('/node\/(\d+)/', $path, $matches)) {
$node_id = $matches[1];
}
$saved_nid = $this->createNode($node_content, $node_id);
// Success message for node creation.
if (!empty($saved_nid)) {
$context['results'][] = $saved_nid;
$this->loggerFactory->get('html_importer')->info(
'@nid Node ID created successfully with unpublished status.', ['@nid' => $saved_nid]
);
}
}
catch (\Throwable $throwable) {
throw new Exception($throwable);
}
}
else {
$this->loggerFactory->get('html_importer')->error(
'Uploaded HTML file has invalid content.'
);
}
}
}
/**
* Get uploaded file content.
*
* @param int $file_input
* File Fid.
*
* @return string
* HTML file content.
*/
public function getFileContent($file_input) {
$content = file_get_contents($file_input);
$node_content = Html::normalize(Xss::filter($content, FieldFilteredMarkup::allowedTags()));
return $node_content;
}
/**
* Create Node with content type import_pages.
*
* @param array $item
* Node content.
* @param int $nid
* Node nid.
*
* @return int|string|null
* Node NID.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @throws \Drupal\Core\Entity\EntityStorageException
*/
public function createNode(array $item, $nid = NULL) {
$url = '/' . str_replace(' ', '_', strtolower($item['title']));
$node_storage = $this->entityTypeManager->getStorage('node');
if ($nid == NULL) {
// Create New Node.
$node_data['type'] = 'import_pages';
$node_data['body']['value'] = $item['content'];
$node_data['body']['format'] = 'full_html';
$node_data['title'] = $item['title'];
$node_data['path']['alias'] = $url;
$node = $node_storage->create($node_data);
$node->setPublished(FALSE);
}
else {
// Update Node.
$node = $node_storage->load($nid);
$node->set('body', $item['content']);
$node->body->format = 'full_html';
}
$node->save();
return $node->id();
}
/**
* Finish batch to create node from HTML file.
*
* @param bool $success
* Indicate that the batch API tasks were all completed successfully.
* @param array $results
* An array of all the results that were updated in processHtmlFiles().
* @param array $operations
* A list of the operations that had not been completed by the batch API.
*/
public function batchFinished($success, array $results, array $operations) {
// The 'success' parameter means no fatal PHP errors were detected. All
// other error management should be handled using 'results'.
if ($success) {
$message = $this->translation
->formatPlural(count($results), 'One node generated .', '@count nodes generated.');
}
else {
$message = 'Batch process finished with an error.';
}
$this->messenger->addMessage($message);
}
}
