FlagController.php in Heartbeat 8
File
src/Controller/FlagController.php
View source
<?php
namespace Drupal\heartbeat\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Entity\Query\QueryFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\flag\FlagService;
use Drupal\flag\Entity\Flag;
use Symfony\Component\HttpFoundation\Response;
class FlagController extends ControllerBase {
protected $flagService;
protected $entityTypeManager;
protected $entityQuery;
public function __construct(FlagService $flag, EntityTypeManager $entity_type_manager, QueryFactory $entity_query) {
$this->flagService = $flag;
$this->entityTypeManager = $entity_type_manager;
$this->entityQuery = $entity_query;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('flag'), $container
->get('entity_type.manager'), $container
->get('entity.query'));
}
public function getUserFlaggings() {
$entity_type = \Drupal::request()->request
->get('entity_type');
$entity_id = \Drupal::request()->request
->get('entity_id');
$flag_id = \Drupal::request()->request
->get('flag_id');
$alt_flag_id = $flag_id === 'heartbeat_like' ? 'jihad_flag' : 'heartbeat_like';
$uid = \Drupal::request()->request
->get('uid');
$response = new Response();
$altResponseData = null;
if ($flag_id !== null) {
$responseData = $this->entityQuery
->get("flagging")
->condition("flag_id", $flag_id, "=")
->condition("entity_type", $entity_type, "=")
->condition("entity_id", $entity_id)
->condition("uid", $uid, "=")
->execute() > 0;
if (!$responseData) {
$altResponseData = $this->entityQuery
->get("flagging")
->condition("flag_id", $alt_flag_id, "=")
->condition("entity_type", $entity_type, "=")
->condition("entity_id", $entity_id)
->condition("uid", $uid, "=")
->execute() > 0;
}
}
else {
$responseData = null;
$altResponseData = null;
}
if (!$responseData && $altResponseData) {
$altFlag = $this->flagService
->getFlagById($alt_flag_id);
$entity = $this->entityTypeManager
->getStorage($entity_type)
->load($entity_id);
$this->flagService
->unflag($altFlag, $entity, \Drupal::currentUser()
->getAccount());
}
$response
->setContent(json_encode(array(
'flagged' => $responseData,
'alt_flagged' => $altResponseData,
)));
$response->headers
->set('Content-Type', 'application/json');
return $response;
}
}