AllowedLanguagesManager.php in Allowed Languages 2.x
File
src/AllowedLanguagesManager.php
View source
<?php
namespace Drupal\allowed_languages;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Entity\ContentEntityInterface;
class AllowedLanguagesManager implements AllowedLanguagesManagerInterface {
protected $currentUser;
protected $entityTypeManager;
public function __construct(AccountProxyInterface $current_user, EntityTypeManagerInterface $entity_type_manager) {
$this->currentUser = $current_user;
$this->entityTypeManager = $entity_type_manager;
}
public function accountFromProxy(AccountInterface $account = NULL) {
if ($account === NULL) {
$account = $this->currentUser;
}
if ($account instanceof AccountProxyInterface) {
$account = $this->entityTypeManager
->getStorage('user')
->load($account
->id());
}
return $account;
}
public function assignedLanguages(AccountInterface $account = NULL) {
$account = $this
->accountFromProxy($this->currentUser);
$language_values = [];
if (!$account
->hasField('allowed_languages')) {
return $language_values;
}
foreach ($account
->get('allowed_languages')
->getValue() as $item) {
$language_values[] = $item['target_id'];
}
return $language_values;
}
public function hasPermissionForLanguage(LanguageInterface $language, AccountInterface $account = NULL) {
$account = $this
->accountFromProxy($this->currentUser);
if ($account
->hasPermission('translate all languages')) {
return TRUE;
}
$allowed_languages = $this
->assignedLanguages($account);
return in_array($language
->getId(), $allowed_languages);
}
public function isEntityLanguageControlled(EntityInterface $entity) {
if ($entity instanceof ContentEntityInterface && $entity
->isTranslatable()) {
return TRUE;
}
return FALSE;
}
}