view_mode_crop-1.0.x-dev/src/ViewModeCropComputed.php

src/ViewModeCropComputed.php
<?php

namespace Drupal\view_mode_crop;

use Drupal\Core\TypedData\TypedData;
use Drupal\view_mode_crop\Plugin\Field\FieldType\ViewModeCropEntityReferenceItem;
use Drupal\view_mode_crop\Plugin\Field\FieldType\ViewModeCropImageItem;

/**
 * Gets the crop data for the field.
 */
class ViewModeCropComputed extends TypedData {

  /**
   * {@inheritdoc}
   */
  public function getValue() {
    /** @var \Drupal\Core\Field\FieldItemInterface $item */
    $item = $this->getParent();

    if (!$item instanceof ViewModeCropEntityReferenceItem && !$item instanceof ViewModeCropImageItem) {
      return NULL;
    }

    $entity = $item->getEntity();

    if ($entity->isNew()) {
      return NULL;
    }

    $field_name = $item->getFieldDefinition()->getName();
    $delta = (int) $item->getName();

    $db = \Drupal::database();

    $record = $db->select('view_mode_crop', 'vmc')
      ->fields('vmc', ['data'])
      ->condition('entity_type', $entity->getEntityTypeId())
      ->condition('entity_id', $entity->uuid())
      ->condition('field_name', $field_name)
      ->condition('delta', $delta)
      ->execute()->fetchAssoc();

    if (!$record) {
      return NULL;
    }

    return $record['data'];
  }

  /**
   * {@inheritdoc}
   */
  public function setValue($value, $notify = TRUE) {
    if ($value !== NULL) {
      /** @var \Drupal\Core\Field\FieldItemInterface $item */
      $item = $this->getParent();
      $entity = $item->getEntity();

      if (($item instanceof ViewModeCropEntityReferenceItem || $item instanceof ViewModeCropImageItem)) {
        $field_name = $item->getFieldDefinition()->getName();
        $delta = (int) $item->getName();
        $db = \Drupal::database();

        $db->delete('view_mode_crop')
          ->condition('entity_type', $entity->getEntityTypeId())
          ->condition('entity_id', $entity->uuid())
          ->condition('field_name', $field_name)
          ->condition('delta', $delta)
          ->execute();

        $db->insert('view_mode_crop')
          ->fields([
            'entity_type' => $entity->getEntityTypeId(),
            'entity_id' => $entity->uuid(),
            'field_name' => $field_name,
            'delta' => $delta,
            'data' => $value,
          ])
          ->execute();
      }
    }
    if ($notify && isset($this->parent)) {
      $this->parent->onChange($this->name);
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc