View source
<?php
namespace Drupal\acquia_contenthub;
use Drupal\Core\Entity\EntityInterface;
class AuditTrackEntities {
public function batchProcess(array $entities, bool $reprocess, string $audit_command, &$context) {
$uuids = array_column($entities, 'entity_uuid');
if (!isset($context['sandbox'])) {
$context['results']['not_published'] = 0;
$context['results']['outdated'] = 0;
}
$factory = \Drupal::service('acquia_contenthub.client.factory');
if (!$factory
->getClient()) {
throw new \Exception(dt('The Content Hub client is not connected so no operations could be performed.'));
}
$cdfs = $factory
->getClient()
->getEntities($uuids)
->getEntities();
foreach ($entities as $entity) {
$out_of_sync = FALSE;
$uuid = $entity['entity_uuid'];
$ch_entity = $cdfs[$uuid] ?? FALSE;
if (!$ch_entity) {
self::prepareOutput($entity, 'Entity not published.');
$out_of_sync = TRUE;
$context['results']['not_published']++;
}
elseif ($entity['hash'] !== $ch_entity
->getAttribute('hash')
->getValue()['und']) {
self::prepareOutput($entity, 'Outdated entity.');
$out_of_sync = TRUE;
$context['results']['outdated']++;
}
if ($out_of_sync) {
$drupal_entity = \Drupal::entityTypeManager()
->getStorage($entity['entity_type'])
->load($entity['entity_id']);
if (!$drupal_entity) {
self::prepareOutput($entity, 'This entity exists in the tracking table but could not be loaded in Drupal.');
continue;
}
if ($reprocess) {
self::enqueueTrackedEntities($drupal_entity, $audit_command);
}
}
}
}
public static function prepareOutput(array $entity, string $msg) {
$message = dt("@msg: Entity Type = @type, UUID = @uuid, ID = @id, Modified = @modified", [
'@msg' => $msg,
'@type' => $entity['entity_type'],
'@uuid' => $entity['entity_uuid'],
'@id' => $entity['entity_id'],
'@modified' => $entity['modified'],
]);
\Drupal::messenger()
->addMessage(dt($message));
}
public static function enqueueTrackedEntities(EntityInterface $entity, string $audit_command) {
$checker = \Drupal::service('pub.sub_status.checker');
if ($checker
->isPublisher() && $audit_command === 'publisher_audit') {
_acquia_contenthub_publisher_enqueue_entity($entity, 'update');
}
if ($checker
->isSubscriber() && $audit_command === 'subscriber_audit') {
$item = new \stdClass();
$tracker = \Drupal::service('acquia_contenthub_subscriber.tracker');
$queue = \Drupal::queue('acquia_contenthub_subscriber_import');
$item->uuid = implode(', ', $entity
->uuid());
$queue_id = $queue
->createItem($item);
$tracker
->queue($entity);
$tracker
->setQueueItemByUuid($item->uuid, $queue_id);
}
}
public function batchFinished(bool $success, array $results, array $operations) {
if ($success) {
$msg = dt('Total number of audited entities not found in Content Hub: @total' . PHP_EOL, [
'@total' => $results['not_published'],
]);
$msg .= dt('Total number of audited entities found outdated in Content Hub: @total', [
'@total' => $results['outdated'],
]);
}
else {
$msg = dt('Finished with a PHP fatal error.');
}
\Drupal::messenger()
->addStatus($msg);
}
}