epub_reader_framework-2.0.0-alpha2/src/Epub/ReaderEpubCompletedCleanup.php
src/Epub/ReaderEpubCompletedCleanup.php
<?php
namespace Drupal\epub_reader_framework\Epub;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\node\NodeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Post epub conversion cleanup of no longer existing chapters.
*/
class ReaderEpubCompletedCleanup {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager')
);
}
/**
* Clean up automated chapters that no longer exist.
*
* @param \Drupal\node\NodeInterface $reader_publication
* The reader publication node.
* @param array $chapter_ids
* An array of chapter IDs from the EPUB spine.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @throws \Drupal\Core\Entity\EntityStorageException
*/
public function cleanupChapters(
NodeInterface $reader_publication,
array $chapter_ids
) {
$node_storage = $this->entityTypeManager->getStorage('node');
// Find the automated chapters that are not longer part of the EPUB and
// delete them.
$orphaned_chapter_ids = $node_storage->getQuery()
->condition('type', 'reader_chapter')
->condition('field_reader_publication', $reader_publication->id())
->condition('field_reader_chapter_automated', TRUE)
->condition('field_reader_chapter_epub_id', $chapter_ids, 'NOT IN')
->accessCheck()
->execute();
if ($orphaned_chapter_ids && $orphaned_chapters = $node_storage->loadMultiple($orphaned_chapter_ids)) {
foreach ($orphaned_chapters as $orphaned_chapter) {
$orphaned_chapter->delete();
}
}
}
}
