FlippingBook.php in Flipping Book 8
File
src/FlippingBook.php
View source
<?php
namespace Drupal\flipping_book;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Archiver\ArchiverManager;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\flipping_book\Entity\FlippingBook as FlippingBookEntity;
class FlippingBook implements FlippingBookInterface {
protected $fileSystem;
protected $pluginManagerArchiver;
protected $entityTypeManager;
public function __construct(FileSystemInterface $file_system, ArchiverManager $plugin_manager_archiver, EntityTypeManagerInterface $entity_type_manager) {
$this->fileSystem = $file_system;
$this->pluginManagerArchiver = $plugin_manager_archiver;
$this->entityTypeManager = $entity_type_manager;
}
public function extractUploadLocation(FlippingBookEntity $flippingBook) {
$flipping_book_type = $this
->getBundleEntity($flippingBook);
return $flipping_book_type
->get('location');
}
public function getBundleEntity(FlippingBookEntity $flippingBook) {
$storage = $this->entityTypeManager
->getStorage('flipping_book_type');
return $storage
->load($flippingBook
->bundle());
}
public function prepareExportDirectory(File $file, $export_location) {
$filepath = $this->fileSystem
->realpath($file
->getFileUri());
$dir = pathinfo($this
->cleanFilename($file
->getFilename()), PATHINFO_FILENAME);
$this->fileSystem
->prepareDirectory($export_location, FileSystemInterface::CREATE_DIRECTORY);
$destination = $this->fileSystem
->getDestinationFilename($export_location . '/' . $dir, FileSystemInterface::EXISTS_RENAME);
return [
'filepath' => $filepath,
'destination' => $destination,
];
}
public function deleteArchive(FlippingBookEntity $flippingBook) {
$dir = $flippingBook
->get('directory')->value;
if (empty($dir)) {
return;
}
$location = $this
->extractUploadLocation($flippingBook);
$this->fileSystem
->deleteRecursive($this->fileSystem
->realpath("{$location}/{$dir}"));
}
public function extractArchive($file_path, $destination) {
$archiver = $this->pluginManagerArchiver
->getInstance([
'filepath' => $file_path,
]);
$archiver
->extract($this->fileSystem
->realpath($destination . '/'));
}
public function buildFlippingBookUrl(FlippingBookEntity $flippingBook) {
$location = $this
->extractUploadLocation($flippingBook);
$dir = $flippingBook
->getDirectory();
$uri = file_create_url("{$location}/{$dir}/index.html");
return Url::fromUri($uri);
}
public function cleanFilename($filename) {
$filename = str_replace(' ', '_', $filename);
$filename = preg_replace('![^0-9A-Za-z_.-]!', '', $filename);
$filename = preg_replace('/(_)_+|(\\.)\\.+|(-)-+/', '\\1\\2\\3', $filename);
$filename = strtolower($filename);
return $filename;
}
}