flag_lists-4.0.x-dev/src/Controller/ActionLinkHelper.php
src/Controller/ActionLinkHelper.php
<?php
namespace Drupal\flag_lists\Controller;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\flag_lists\FlagListsServiceInterface;
use Drupal\flag_lists\Entity\FlagListItem;
use Drupal\flag\FlagInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Helper class for ActionLink Controller.
*/
class ActionLinkHelper implements ContainerInjectionInterface {
/**
* The flag lists service.
*
* @var \Drupal\flag\FlagListsServiceInterface
*/
protected $flagListsService;
/**
* Constructor.
*
* @param \Drupal\flag_lists\FlagListsServiceInterface $flag_lists
* The flag lists service.
*/
public function __construct(
FlagListsServiceInterface $flag_lists
) {
$this->flagListsService = $flag_lists;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('flaglists')
);
}
/**
* Helper function for flag ActionLinks.
*
* @param \Drupal\flag\FlagInterface $flag
* The flag to flag.
* @param string $entity_id
* The entity id to add the flag list item to.
* @param string $flag_list
* The flag list to add the flag list item to.
*/
public function flagHelper(FlagInterface $flag, $entity_id, $flag_list) {
// Create the Flag List Item.
$flag_list_name =
$this->flagListsService->getFlaggingCollectionById($flag_list)->getName();
$flag_list_item = FlagListItem::create([
'entity_id' => $entity_id,
'type' => $flag->getFlaggableEntityTypeId(),
'baseflag' => $flag->id(),
'flag_list' => $flag_list,
'name' => $flag_list_name . ' ' . $entity_id,
]);
$flag_list_item->save();
}
/**
* Helper function for unflag ActionLinks.
*
* @param \Drupal\flag\FlagInterface $flag
* The flag to unflag.
* @param string $entity_id
* The entity id to remove the flag list item from.
* @param string $flag_list
* The flag list to remove the flag list item from.
*/
public function unflagHelper(FlagInterface $flag, $entity_id, $flag_list) {
// Remove the corresponding Flag List Items.
$baseflag = $flag->id();
$ids = $this->flagListsService->getFlagListItemIds($baseflag, $flag_list,
$entity_id);
foreach ($ids as $id) {
$flagListItem = \Drupal::entityTypeManager()->getStorage('flag_list_item')->load($id);
$flagListItem->delete();
}
}
}
