LikeDislikePermissions.php in Like & Dislike 8
File
src/LikeDislikePermissions.php
View source
<?php
namespace Drupal\like_and_dislike;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\votingapi\Entity\VoteType;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LikeDislikePermissions implements ContainerInjectionInterface {
use StringTranslationTrait;
protected $entityTypeManager;
protected $configFactory;
protected $bundleInfoService;
public function __construct(EntityTypeManagerInterface $entity_type_manager, ConfigFactoryInterface $config_factory, EntityTypeBundleInfoInterface $bundle_info_service) {
$this->entityTypeManager = $entity_type_manager;
$this->configFactory = $config_factory;
$this->bundleInfoService = $bundle_info_service;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager'), $container
->get('config.factory'), $container
->get('entity_type.bundle.info'));
}
public function buildPermissions() {
$permissions = [];
$enabled_entity_types = $this->configFactory
->get('like_and_dislike.settings')
->get('enabled_types');
$vote_types = VoteType::loadMultiple();
foreach ($enabled_entity_types as $entity_type_id => $bundles) {
$this
->addLikeAndDislikePermission($permissions, $vote_types, $entity_type_id, $bundles);
}
return $permissions;
}
protected function addLikeAndDislikePermission(array &$permissions, array $vote_types, $entity_type_id, array $bundles) {
$entity_type = $this->entityTypeManager
->getDefinition($entity_type_id, FALSE);
if (empty($bundles)) {
foreach ($vote_types as $vote_type) {
$permissions["add or remove {$vote_type->id()} votes on {$entity_type_id}"] = [
'title' => $this
->t('%entity_type_name: add/remove %vote_type_name', [
'%entity_type_name' => $entity_type
->getLabel(),
'%vote_type_name' => $vote_type
->label(),
]),
];
}
}
else {
foreach ($bundles as $bundle) {
$bundle_info = $this->bundleInfoService
->getBundleInfo($entity_type_id)[$bundle];
foreach ($vote_types as $vote_type) {
$permissions["add or remove {$vote_type->id()} votes on {$bundle} of {$entity_type_id}"] = [
'title' => $this
->t('%entity_type (%bundle): add/remove %vote_type', [
'%entity_type' => $entity_type
->getLabel(),
'%vote_type' => $vote_type
->label(),
'%bundle' => $bundle_info['label'],
]),
];
}
}
}
}
}