View source  
  <?php
namespace Drupal\webform_content_creator\Entity;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\NodeInterface;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\node\Entity\Node;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\webform_content_creator\WebformContentCreatorInterface;
use Drupal\webform_content_creator\WebformContentCreatorUtilities;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Field\EntityReferenceFieldItemList;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
use Drupal\Component\Utility\Html;
class WebformContentCreatorEntity extends ConfigEntityBase implements WebformContentCreatorInterface {
  use StringTranslationTrait, MessengerTrait;
  
  protected $id;
  
  protected $title;
  
  protected $field_title;
  
  protected $webform;
  
  protected $content_type;
  
  protected $elements;
  
  protected $use_encrypt;
  
  protected $encryption_profile;
  
  public function getTitle() {
    return $this
      ->get('title');
  }
  
  public function setTitle($title) {
    $this
      ->set('title', $title);
    return $this;
  }
  
  public function getContentType() {
    return $this
      ->get('content_type');
  }
  
  public function setContentType($contentType) {
    $this
      ->set('content_type', $contentType);
    return $this;
  }
  
  public function getWebform() {
    return $this
      ->get('webform');
  }
  
  public function setWebform($webform) {
    $this
      ->set('webform', $webform);
    return $this;
  }
  
  public function getAttributes() {
    return $this
      ->get(WebformContentCreatorInterface::ELEMENTS);
  }
  
  public function getSyncEditContentCheck() {
    return $this
      ->get(WebformContentCreatorInterface::SYNC_CONTENT);
  }
  
  public function getSyncDeleteContentCheck() {
    return $this
      ->get(WebformContentCreatorInterface::SYNC_CONTENT_DELETE);
  }
  
  public function getSyncContentField() {
    return $this
      ->get(WebformContentCreatorInterface::SYNC_CONTENT_FIELD);
  }
  
  public function getEncryptionCheck() {
    return $this
      ->get(WebformContentCreatorInterface::USE_ENCRYPT);
  }
  
  public function getEncryptionProfile() {
    return $this
      ->get(WebformContentCreatorInterface::ENCRYPTION_PROFILE);
  }
  
  private function getNodeTitle() {
    
    if ($this
      ->get(WebformContentCreatorInterface::FIELD_TITLE) !== NULL && $this
      ->get(WebformContentCreatorInterface::FIELD_TITLE) !== '') {
      $nodeTitle = $this
        ->get(WebformContentCreatorInterface::FIELD_TITLE);
    }
    else {
      $nodeTitle = \Drupal::entityTypeManager()
        ->getStorage(WebformContentCreatorInterface::WEBFORM)
        ->load($this
        ->get(WebformContentCreatorInterface::WEBFORM))
        ->label();
    }
    return $nodeTitle;
  }
  
  private function getProfileName() {
    $encryptionProfile = '';
    $useEncrypt = $this
      ->get(WebformContentCreatorInterface::USE_ENCRYPT);
    if ($useEncrypt) {
      $encryptionProfile = \Drupal::service('entity.manager')
        ->getStorage(WebformContentCreatorInterface::ENCRYPTION_PROFILE)
        ->load($this
        ->getEncryptionProfile());
    }
    return $encryptionProfile;
  }
  
  private function getDecryptionFromProfile($value, $encryptionProfile = '') {
    if ($this
      ->getEncryptionCheck()) {
      $decValue = WebformContentCreatorUtilities::getDecryptedValue($value, $encryptionProfile);
    }
    else {
      $decValue = $value;
    }
    return $decValue;
  }
  
  private function mapNodeField(NodeInterface $initialContent, WebformSubmissionInterface $webform_submission, array $fields = [], array $data = [], $encryptionProfile = '', $fieldId = '', array $mapping = [], array $attributes = []) {
    $content = $initialContent;
    if (!$content
      ->hasField($fieldId) || !is_array($mapping)) {
      return $content;
    }
    if ($attributes[$fieldId][WebformContentCreatorInterface::CUSTOM_CHECK]) {
      $decValue = WebformContentCreatorUtilities::getDecryptedTokenValue($mapping[WebformContentCreatorInterface::CUSTOM_VALUE], $encryptionProfile, $webform_submission);
      if ($decValue === 'true' || $decValue === 'TRUE') {
        $decValue = TRUE;
      }
    }
    else {
      if (!$attributes[$fieldId][WebformContentCreatorInterface::TYPE]) {
        if (!array_key_exists(WebformContentCreatorInterface::WEBFORM_FIELD, $mapping) || !array_key_exists($mapping[WebformContentCreatorInterface::WEBFORM_FIELD], $data)) {
          return $content;
        }
        $decValue = $this
          ->getDecryptionFromProfile($data[$mapping[WebformContentCreatorInterface::WEBFORM_FIELD]], $encryptionProfile);
        if ($fields[$fieldId]
          ->getType() === 'entity_reference' && (!is_array($decValue) && intval($decValue) === 0)) {
          $content
            ->set($fieldId, []);
          return $content;
        }
      }
      else {
        $fieldObject = $webform_submission->{$mapping[WebformContentCreatorInterface::WEBFORM_FIELD]};
        if ($fieldObject instanceof EntityReferenceFieldItemList) {
          $decValue = $webform_submission->{$mapping[WebformContentCreatorInterface::WEBFORM_FIELD]}
            ->getValue()[0]['target_id'];
        }
        else {
          $decValue = $webform_submission->{$mapping[WebformContentCreatorInterface::WEBFORM_FIELD]}->value;
        }
      }
    }
    if ($fields[$fieldId]
      ->getType() == 'datetime') {
      $decValue = $this
        ->convertTimestamp($decValue, $fields, $fieldId);
    }
    
    $maxLength = $this
      ->checkMaxFieldSizeExceeded($fields, $fieldId, $decValue);
    if ($maxLength === 0) {
      $content
        ->set($fieldId, $decValue);
    }
    else {
      $content
        ->set($fieldId, substr($decValue, 0, $maxLength));
    }
    return $content;
  }
  
  public function createNode(WebformSubmissionInterface $webform_submission) {
    $nodeTitle = $this
      ->getNodeTitle();
    
    $data = $webform_submission
      ->getData();
    if (empty($data)) {
      return 0;
    }
    $encryptionProfile = $this
      ->getProfileName();
    
    $decryptedTitle = WebformContentCreatorUtilities::getDecryptedTokenValue($nodeTitle, $encryptionProfile, $webform_submission);
    
    $decodedTitle = Html::decodeEntities($decryptedTitle);
    
    $content = Node::create([
      WebformContentCreatorInterface::TYPE => $this
        ->getContentType(),
      'title' => $decodedTitle,
    ]);
    
    $attributes = $this
      ->get(WebformContentCreatorInterface::ELEMENTS);
    $contentType = \Drupal::entityTypeManager()
      ->getStorage('node_type')
      ->load($this
      ->getContentType());
    if (empty($contentType)) {
      return FALSE;
    }
    $fields = WebformContentCreatorUtilities::contentTypeFields($contentType);
    if (empty($fields)) {
      return FALSE;
    }
    foreach ($attributes as $k2 => $v2) {
      $content = $this
        ->mapNodeField($content, $webform_submission, $fields, $data, $encryptionProfile, $k2, $v2, $attributes);
    }
    $result = FALSE;
    
    try {
      $result = $content
        ->save();
    } catch (\Exception $e) {
      \Drupal::logger(WebformContentCreatorInterface::WEBFORM_CONTENT_CREATOR)
        ->error($this
        ->t('A problem occurred when creating a new node.'));
      \Drupal::logger(WebformContentCreatorInterface::WEBFORM_CONTENT_CREATOR)
        ->error($e
        ->getMessage());
    }
    return $result;
  }
  
  public function updateNode(WebformSubmissionInterface $webform_submission, $op = 'edit') {
    if (empty($this
      ->getSyncContentField())) {
      return FALSE;
    }
    $contentType = \Drupal::entityTypeManager()
      ->getStorage('node_type')
      ->load($this
      ->getContentType());
    if (empty($contentType)) {
      return FALSE;
    }
    $fields = WebformContentCreatorUtilities::contentTypeFields($contentType);
    if (empty($fields)) {
      return FALSE;
    }
    if (!array_key_exists($this
      ->getSyncContentField(), $fields)) {
      return FALSE;
    }
    $nodeTitle = $this
      ->getNodeTitle();
    
    $data = $webform_submission
      ->getData();
    if (empty($data)) {
      return FALSE;
    }
    $encryptionProfile = $this
      ->getProfileName();
    
    $decryptedTitle = WebformContentCreatorUtilities::getDecryptedTokenValue($nodeTitle, $encryptionProfile, $webform_submission);
    
    $decodedTitle = Html::decodeEntities($decryptedTitle);
    
    $nodes = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties([
      $this
        ->getSyncContentField() => $webform_submission
        ->id(),
    ]);
    
    if (!($content = reset($nodes))) {
      return FALSE;
    }
    if ($op === 'delete' && !empty($this
      ->getSyncDeleteContentCheck())) {
      $result = $content
        ->delete();
      return $result;
    }
    if (empty($this
      ->getSyncEditContentCheck())) {
      return FALSE;
    }
    
    $content
      ->setTitle($decodedTitle);
    
    $attributes = $this
      ->get(WebformContentCreatorInterface::ELEMENTS);
    foreach ($attributes as $k2 => $v2) {
      $content = $this
        ->mapNodeField($content, $webform_submission, $fields, $data, $encryptionProfile, $k2, $v2, $attributes);
    }
    $result = FALSE;
    
    try {
      $result = $content
        ->save();
    } catch (\Exception $e) {
      \Drupal::logger(WebformContentCreatorInterface::WEBFORM_CONTENT_CREATOR)
        ->error($this
        ->t('A problem occurred while updating node.'));
      \Drupal::logger(WebformContentCreatorInterface::WEBFORM_CONTENT_CREATOR)
        ->error($e
        ->getMessage());
    }
    return $result;
  }
  
  public function existsContentType() {
    
    $content_type_id = $this
      ->getContentType();
    
    $content_type_entity = \Drupal::entityTypeManager()
      ->getStorage('node_type')
      ->load($content_type_id);
    return !empty($content_type_entity);
  }
  
  public function equalsContentType($ct) {
    return $ct === $this
      ->getContentType();
  }
  
  public function equalsWebform($webform) {
    return $webform === $this
      ->getWebform();
  }
  
  public function statusMessage($status) {
    if ($status) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('Saved the %label entity.', [
        '%label' => $this
          ->getTitle(),
      ]));
    }
    else {
      $this
        ->messenger()
        ->addMessage($this
        ->t('The %label entity was not saved.', [
        '%label' => $this
          ->getTitle(),
      ]));
    }
  }
  
  public function checkMaxFieldSizeExceeded(array $fields, $k, $decValue = "") {
    if (!array_key_exists($k, $fields) || empty($fields[$k])) {
      return 0;
    }
    $fieldSettings = $fields[$k]
      ->getSettings();
    if (empty($fieldSettings) || !array_key_exists('max_length', $fieldSettings)) {
      return 0;
    }
    $maxLength = $fieldSettings['max_length'];
    if (empty($maxLength)) {
      return 0;
    }
    if ($maxLength < strlen($decValue)) {
      \Drupal::logger(WebformContentCreatorInterface::WEBFORM_CONTENT_CREATOR)
        ->notice($this
        ->t('Problem: Field max length exceeded (truncated).'));
      return $maxLength;
    }
    return strlen($decValue);
  }
  
  public function convertTimestamp($datefield, array $fields, $fieldId) {
    $dateTime = new DrupalDateTime($datefield, 'UTC');
    $dateType = $fields[$fieldId]
      ->getSettings()['datetime_type'];
    if ($dateType === 'datetime') {
      $formatted = \Drupal::service('date.formatter')
        ->format($dateTime
        ->getTimestamp(), 'custom', DateTimeItemInterface::DATETIME_STORAGE_FORMAT, 'UTC');
    }
    else {
      $formatted = \Drupal::service('date.formatter')
        ->format($dateTime
        ->getTimestamp(), 'custom', DateTimeItemInterface::DATE_STORAGE_FORMAT, 'UTC');
    }
    return $formatted;
  }
}