sessionless-1.x-dev/src/Element/SessionlessElementTrait.php
src/Element/SessionlessElementTrait.php
<?php
namespace Drupal\sessionless\Element;
use Drupal\Core\Form\FormStateInterface;
use Drupal\sessionless\SessionlessEncryptAndSign;
use Drupal\sessionless\SessionlessInterface;
use Drupal\sessionless\SessionlessOnlySign;
trait SessionlessElementTrait {
public function getInfo() {
$class = static::class;
return [
'#input' => TRUE,
'#pre_render' => [
[$class, 'preRenderSessionless'],
],
];
}
protected static function getCryptoService(bool $mustEncrypt): SessionlessInterface {
if ($mustEncrypt) {
return \Drupal::service(SessionlessEncryptAndSign::class);
}
else {
return \Drupal::service(SessionlessOnlySign::class);
}
}
public static function preRenderSessionless($element) {
$serialized = serialize($element['#value'] ?? NULL);
if (isset($serialized)) {
$jwt = self::getCryptoService(self::mustEncrypt())
->encode($serialized);
$element['hidden'] = [
'#type' => 'hidden',
'#name' => $element['#name'],
'#value' => $jwt,
];
}
return $element;
}
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
$value = NULL;
if ($input) {
$serialized = self::getCryptoService(self::mustEncrypt())
->decode($input);
$value = unserialize($serialized);
}
return $value;
}
abstract protected static function mustEncrypt(): bool;
}
