packthub_ebook_integration-1.0.0/src/Plugin/EbookNodeProcessor.php
src/Plugin/EbookNodeProcessor.php
<?php
namespace Drupal\packt\Plugin;
use Drupal\Core\File\FileSystemInterface;
use Drupal\file\Entity\File;
use Drupal\file\FileInterface;
use Drupal\image\Entity\ImageStyle;
use Drupal\node\Entity\Node;
class EbookNodeProcessor {
private array $messages;
public function getMessages(): array {
return $this->messages;
}
private array $mappedDataReady;
public function getMappedDataReady(): array {
return $this->mappedDataReady;
}
public function __construct(private readonly array $product_ids) {
$this->messages = [];
$this->mappedDataReady = [];
}
public function attemptFieldsMapping(): bool|null {
$fields = packt_ebook_maps();
if(empty($fields)) {
return NULL;
}
$contentType = $fields['content_type'];
unset($fields['content_type']);
$mappedProducts = [];
$product = new Products();
foreach ($this->product_ids as $key=>$product_id) {
if(!empty($product_id)) {
$product->setProductID($product_id);
$details = $product->getProducts();
if(!empty($details)) {
foreach ($fields as $k=>$field) {
if(!strpos($field, '.')) {
$mappedProducts[$key][$k] = $details[$field] ?? null;
}
else {
$list = explode('.', $field);
$result = $details;
foreach ($list as $part) {
if($part === 'files') {
$res = $this->findFilesRequired($list, $details['files'], $details['product_id'], $details['product_information']['title'] ?? '');
if(!empty($res)) {
$result = $res;
}else {
$this->messages[] = 'File processing failed';
}
break;
}
elseif($part === 'chapters') {
$result = $this->makeChapters($list, $details['chapters']);
break;
}
elseif(isset($result[$part])) {
$result = $result[$part];
}
}
$mappedProducts[$key][$k] = $result;
}
}
}
}
}
if(!empty($mappedProducts)) {
foreach ($mappedProducts as $key=>$mappedProduct) {
$mappedProduct['type'] = $contentType;
$node = Node::create($mappedProduct);
$node->enforceIsNew();
$this->mappedDataReady[] = $node;
$this->messages[] = $key . ' - Product prepared successfully';
}
return TRUE;
}
return FALSE;
}
private function findFilesRequired(array $list, array $files, string $product, string $productTitle = ''): array {
$type = end($list);
$middle = $list[1];
$found = [];
foreach ($files as $key=>$file) {
if(isset($file[$middle]) && $file[$middle] === $type) {
$found = $file;
break;
}
}
if(!empty($found)) {
// Write file here.
$assets = new ProductsAssets();
$filename = $found['file_name'] ?? null;
if($filename) {
$list = explode('.', $filename);
$assets->setProduct($product);
$assets->setFileName($list[0]);
$data = $assets->getAssets();
if(!empty($data['data']) && !empty($data['mime_type'])) {
$extension = explode('/', $data['mime_type']);
$extension = end($extension);
$public = "public://ebook_covers";
// Get the file system service.
$fileSystem = \Drupal::service('file_system');
if(!is_dir($public)) {
// Ensure the directory exists.
$fileSystem->prepareDirectory($public, FileSystemInterface::CREATE_DIRECTORY);
}
$filename = $productTitle ?? uniqid();
$filename = $this->prepareFilename($filename) . ".$extension";
// Create a new file entity.
$file = File::create([
'uri' => $public . '/' . $filename,
'status' => FileInterface::STATUS_PERMANENT,
]);
// Save the file data.
\Drupal::service('file_system')->saveData($data['data'], $file->getFileUri(), FileSystemInterface::EXISTS_REPLACE);
// Save the file entity.
$fid = $file->save();
if($fid) {
if(str_contains($file->getMimeType() , 'image')) {
// Get all image styles.
$imageStyles = ImageStyle::loadMultiple();
// Generate derivative images for each style.
foreach ($imageStyles as $style) {
// Generate a derivative image for the current style.
$derivativeUri = $style->buildUri($file->getFileUri());
$style->createDerivative($file->getFileUri(), $derivativeUri);
}
}
return ['target_id'=>$file->id()];
}
}
}
}
return [];
}
private function makeChapters(array $list, mixed $chapters): string {
$type = end($list);
$line = '';
foreach ($chapters as $chapter) {
if(!empty($chapter[$type])) {
$line .= $chapter[$type]. '|';
}
}
return substr($line, 0, strlen($line) - 1);
}
private function prepareFilename(string $title): string {
$clean = preg_replace('/[^a-zA-Z0-9]/', '_', $title);
return strtolower(str_replace(' ', '_', $clean));
}
}
