TcaSettingsManager.php in Token Content Access 8
File
src/TcaSettingsManager.php
View source
<?php
namespace Drupal\tca;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Config\ConfigFactory;
use Drupal\tca\Entity\TcaSettings;
use Drupal\Core\Site\Settings;
use Drupal\Component\Utility\Crypt;
class TcaSettingsManager implements TcaSettingsManagerInterface {
protected $entityTypeManager;
protected $configFactory;
public function __construct(EntityTypeManagerInterface $etm, ConfigFactory $config_factory) {
$this->entityTypeManager = $etm;
$this->configFactory = $config_factory;
}
public function saveSettings(array $settings, $entity_type_id, $entity_id) {
$entity = $this
->getEntity($entity_type_id, $entity_id);
if ($entity) {
foreach ($settings as $key => $value) {
$field = 'tca_' . $key;
if ($entity
->hasField($field)) {
$entity
->set($field, $value);
}
}
$entity
->save();
}
else {
$id = $this
->generateSettingsFullId($entity_type_id, $entity_id);
$entity = TcaSettings::load($id);
if ($entity === NULL) {
$entity_array = [
'id' => $id,
];
$entity_array += $settings;
$entity = TcaSettings::create($entity_array);
}
else {
foreach ($settings as $key => $setting) {
$entity
->set($key, $setting);
}
}
$entity
->set('entity_type_id', $entity_type_id);
$entity
->set('entity_id', $entity_id);
$entity
->save();
}
}
public function loadSettingsAsConfig($entity_type_id, $entity_id) {
$entity = $this
->getEntity($entity_type_id, $entity_id);
if ($entity) {
$config = $this->configFactory
->get('tca.tca_settings.default');
$settings = $config
->getRawData();
foreach ($settings as $key => $value) {
$field = 'tca_' . $key;
if ($entity
->hasField($field)) {
if (isset($entity
->get($field)->value)) {
$settings[$key] = $entity
->get($field)->value;
}
}
}
return $config
->initWithData($settings);
}
else {
$id = $this
->generateSettingsFullId($entity_type_id, $entity_id);
$actual = $this->configFactory
->get('tca.tca_settings.' . $id);
if (!$actual
->isNew()) {
return $actual;
}
else {
return $this->configFactory
->get('tca.tca_settings.default');
}
}
}
private function getEntity($entity_type_id, $entity_id) {
$entity_storage = $this->entityTypeManager
->getStorage($entity_type_id);
if ($entity_storage && $entity_id) {
$entity = $entity_storage
->load($entity_id);
if ($entity && is_subclass_of($entity, 'Drupal\\Core\\Entity\\ContentEntityBase')) {
if ($entity
->hasField('tca_active') && $entity
->hasField('tca_token')) {
return $entity;
}
}
}
return NULL;
}
private function generateSettingsFullId($entity_type_id, $entity_id) {
return $entity_type_id . (!empty($entity_id) ? '_' . $entity_id : '');
}
public function generateToken($entity_type_id, $entity_id) {
$private_key = \Drupal::service('private_key')
->get();
$hash_salt = Settings::getHashSalt();
return Crypt::hashBase64($entity_type_id . $entity_id . microtime(), $private_key . $hash_salt);
}
}