You are here

function disqus_entity_update in Disqus 8

Implements hook_entity_update().

File

./disqus.module, line 168
The Disqus Drupal module.

Code

function disqus_entity_update(EntityInterface $entity) {

  // Only act on content entities.
  if (!$entity instanceof ContentEntityInterface) {
    return;
  }
  $field = \Drupal::service('disqus.manager')
    ->getFields($entity
    ->getEntityTypeId());
  if (!$entity
    ->hasField(key($field))) {
    return;
  }
  $messenger = \Drupal::messenger();
  $config = \Drupal::config('disqus.settings');

  // Update the thread information on disqus if required.
  if ($config
    ->get('advanced.api.disqus_api_update') && ($entity
    ->label() != $entity->original
    ->label() || $entity
    ->toUrl() != $entity->original
    ->url())) {
    $disqus = disqus_api();
    if ($disqus) {
      try {

        // Load the thread data from disqus. Passing thread is required to allow
        // the thread:ident call to work correctly. There is a pull request to
        // fix this issue.
        $thread = $disqus->threads
          ->details([
          'forum' => $config
            ->get('disqus_domain'),
          'thread:ident' => "{$entity->getEntityTypeId()}/{$entity->id()}",
          'thread' => '1',
        ]);
      } catch (Exception $exception) {
        $messenger
          ->addError(t('There was an error loading the thread details from Disqus.'));
        \Drupal::logger('disqus')
          ->error('Error loading thread details for entity : @identifier. Check your API keys.', [
          '@identifier' => "{$entity->getEntityTypeId()}/{$entity->id()}",
        ]);
      }
      if (isset($thread->id)) {
        try {
          $disqus->threads
            ->update([
            'access_token' => $config
              ->get('advanced.disqus_useraccesstoken'),
            'thread' => $thread->id,
            'forum' => $config
              ->get('disqus_domain'),
            'title' => $entity
              ->label(),
            'url' => $entity
              ->toUrl('canonical', [
              'absolute' => TRUE,
            ]),
          ]);
        } catch (Exception $exception) {
          $messenger
            ->addError(t('There was an error updating the thread details on Disqus.'));
          \Drupal::logger('disqus')
            ->error('Error updating thread details for entity : @identifier. Check your user access token.', [
            '@identifier' => "{$entity->getEntityTypeId()}/{$entity->id()}",
          ]);
        }
      }
    }
  }
}