media_library_extend_crowdriff-1.x-dev/src/CrowdriffUninstallValidator.php
src/CrowdriffUninstallValidator.php
<?php
namespace Drupal\media_library_extend_crowdriff;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleUninstallValidatorInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Url;
/**
* Crowdriff module uninstall validator service.
*/
class CrowdriffUninstallValidator implements ModuleUninstallValidatorInterface {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a new CrowdriffUninstallValidator.
*
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(TranslationInterface $string_translation, EntityTypeManagerInterface $entity_type_manager) {
$this->stringTranslation = $string_translation;
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public function validate($module): array {
$reasons = [];
if ($module == 'media_library_extend_crowdriff' && $this->crowdriffMediaExists()) {
$reasons[] = $this->t('Crowdriff media entities found. Please delete before uninstallation. <a href=":link">Delete assets</a>', [
':link' => Url::fromRoute('media_library_extend_crowdriff.delete_assets', [], [
'query' => [
'destination' => Url::fromRoute('system.modules_uninstall')
->toString(),
],
])
->toString(),
]);
}
return $reasons;
}
/**
* Check if content available for Crowdriff media types.
*
* @return bool
* TRUE if there are Crowdriff media entities, FALSE otherwise.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
protected function crowdriffMediaExists(): bool {
// Get query.
$query = $this->entityTypeManager->getStorage('media')->getQuery();
$query = $query
->accessCheck(FALSE)
->condition('bundle', ['crowdriff_image', 'crowdriff_video'], 'IN');
// Get array of entity ids.
$ids = $query->execute();
if (!empty($ids)) {
return TRUE;
}
else {
return FALSE;
}
}
}
