OgDeleteOrphansBase.php in Organic groups 8
File
src/OgDeleteOrphansBase.php
View source
<?php
declare (strict_types=1);
namespace Drupal\og;
use Drupal\Component\Plugin\PluginBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\QueueFactory;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class OgDeleteOrphansBase extends PluginBase implements OgDeleteOrphansInterface, ContainerFactoryPluginInterface {
use StringTranslationTrait;
protected $entityTypeManager;
protected $queueFactory;
protected $membershipManager;
protected $groupAudienceHelper;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, QueueFactory $queue_factory, MembershipManagerInterface $membership_manager, OgGroupAudienceHelperInterface $group_audience_helper) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->queueFactory = $queue_factory;
$this->membershipManager = $membership_manager;
$this->groupAudienceHelper = $group_audience_helper;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'), $container
->get('queue'), $container
->get('og.membership_manager'), $container
->get('og.group_audience_helper'));
}
public function register(EntityInterface $entity) {
foreach ($this
->query($entity) as $entity_type => $orphans) {
foreach ($orphans as $orphan) {
$this
->getQueue()
->createItem([
'type' => $entity_type,
'id' => $orphan,
]);
}
}
}
protected function query(EntityInterface $entity) {
$orphans = $this->membershipManager
->getGroupContentIds($entity);
$membership_ids = $this->entityTypeManager
->getStorage('og_membership')
->getQuery()
->condition('entity_type', $entity
->getEntityTypeId())
->condition('entity_id', $entity
->id())
->execute();
if (!empty($membership_ids)) {
$orphans['og_membership'] = $membership_ids;
}
return $orphans;
}
protected function deleteOrphan($entity_type, $entity_id) {
$entity = $this->entityTypeManager
->getStorage($entity_type)
->load($entity_id);
if (!$entity) {
return;
}
if ($this->groupAudienceHelper
->hasGroupAudienceField($entity
->getEntityTypeId(), $entity
->bundle())) {
$group_count = $this->membershipManager
->getGroupCount($entity);
if ($group_count == 0) {
$entity
->delete();
}
}
else {
$entity
->delete();
}
}
protected function getQueue() {
return $this->queueFactory
->get('og_orphaned_group_content', TRUE);
}
public function configurationForm(array $form, FormStateInterface $form_state) {
return [];
}
}