You are here

public function LikeDislikeController::handler in Like/Dislike 8

Like or Dislike handler.

Parameters

string $clicked: Status of the click link.

string $data: Data passed from the formatter.

Return value

AjaxResponse|string Response count for the like/dislike.

1 string reference to 'LikeDislikeController::handler'
like_dislike.routing.yml in ./like_dislike.routing.yml
like_dislike.routing.yml

File

src/Controller/LikeDislikeController.php, line 94

Class

LikeDislikeController
Class LikeDislikeController.

Namespace

Drupal\like_dislike\Controller

Code

public function handler($clicked, $data) {
  $return = '';
  $response = new AjaxResponse();

  // Decode the url data
  $decode_data = json_decode(base64_decode($data));

  // Load the entity content.
  $entity_data = $this->entityTypeManager
    ->getStorage($decode_data->entity_type)
    ->load($decode_data->entity_id);
  $field_name = $decode_data->field_name;

  // Get the users who already clicked on this particular content.
  $users = json_decode($entity_data->{$field_name}->clicked_by);
  if ($users == NULL) {
    $users = new \stdClass();
    $users->default = 'default';
  }
  $user = $this->currentUser
    ->id();

  // If user is ananomous, ask him to register/login.
  if ($user == 0) {
    $destination = $this->requestStack
      ->getCurrentRequest()
      ->get('like-dislike-redirect');
    user_cookie_save([
      'destination' => $destination,
    ]);
    $user_login_register = $this
      ->like_dislike_login_register();
    $dialog_library['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $response
      ->setAttachments($dialog_library['#attached']);
    return $response
      ->addCommand(new OpenModalDialogCommand('Like/Dislike', $user_login_register));
  }

  // Update content, based on like/dislike.
  $already_clicked = key_exists($user, array_keys((array) $users));
  if ($clicked == 'like') {
    if (!$already_clicked) {
      $entity_data->{$field_name}->likes++;
      $users->{$user} = 'like';
    }
    else {
      return $this
        ->like_dislike_status($response, $decode_data->entity_id);
    }
    $return = $response
      ->addCommand(new HtmlCommand('#like-' . $decode_data->entity_id, $entity_data->{$field_name}->likes));
  }
  elseif ($clicked == 'dislike') {
    if (!$already_clicked) {
      $entity_data->{$field_name}->dislikes--;
      $users->{$user} = "dislike";
    }
    else {
      return $this
        ->like_dislike_status($response, $decode_data->entity_id);
    }
    $return = $response
      ->addCommand(new HtmlCommand('#dislike-' . $decode_data->entity_id, $entity_data->{$field_name}->dislikes));
  }
  $entity_data->{$field_name}->clicked_by = json_encode($users);
  $entity_data
    ->save();
  return $return;
}