alert_message-1.0.x-dev/src/Entity/AlertMessage.php

src/Entity/AlertMessage.php
<?php

namespace Drupal\alert_message\Entity;

use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityPublishedTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\alert_message\AlertMessageInterface;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
use Drupal\user\EntityOwnerTrait;

/**
 * Defines the alert message entity class.
 *
 * @ContentEntityType(
 *   id = "alert_message",
 *   label = @Translation("Alert message"),
 *   label_collection = @Translation("Alert messages"),
 *   label_singular = @Translation("alert message"),
 *   label_plural = @Translation("alert messages"),
 *   label_count = @PluralTranslation(
 *     singular = "@count alert messages",
 *     plural = "@count alert messages",
 *   ),
 *   constraints = {
 *     "AlertMessagePublishDates" = {}
 *   },
 *   handlers = {
 *     "list_builder" = "Drupal\alert_message\AlertMessageListBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "access" = "Drupal\entity\EntityAccessControlHandler",
 *     "query_access" = "Drupal\entity\QueryAccess\QueryAccessHandler",
 *     "permission_provider" = "Drupal\entity\EntityPermissionProvider",
 *     "form" = {
 *       "add" = "Drupal\alert_message\Form\AlertMessageForm",
 *       "edit" = "Drupal\alert_message\Form\AlertMessageForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
 *     },
 *     "local_task_provider" = {
 *       "html" = "Drupal\entity\Menu\DefaultEntityLocalTaskProvider",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\entity\Routing\AdminHtmlRouteProvider",
 *       "delete-multiple" = "Drupal\entity\Routing\DeleteMultipleRouteProvider",
 *     },
 *     "translation" = "Drupal\content_translation\ContentTranslationHandler",
 *   },
 *   translatable = TRUE,
 *   base_table = "alert_message",
 *   data_table = "alert_message_field_data",
 *   admin_permission = "administer alert message",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label",
 *     "uuid" = "uuid",
 *     "owner" = "uid",
 *     "langcode" = "langcode",
 *     "published" = "status",
 *   },
 *   links = {
 *     "canonical" = "/alert-message/{alert_message}",
 *     "add-form" = "/alert-message/add",
 *     "edit-form" = "/alert-message/{alert_message}/edit",
 *     "delete-form" = "/alert-message/{alert_message}/delete",
 *     "collection" = "/admin/content/alert-message",
 *   },
 *   field_ui_base_route = "entity.alert_message.settings",
 * )
 */
class AlertMessage extends ContentEntityBase implements AlertMessageInterface {

  use EntityChangedTrait;
  use EntityOwnerTrait;
  use EntityPublishedTrait;

  /**
   * {@inheritdoc}
   */
  public function getMessage() {
    return $this->get('message')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setMessage(string $alert_message) {
    $this->set('message', $alert_message);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setTargetedUsers(array $users) {
    $this->set('users', $users);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getTargetedUsers() {
    return $this->get('users')->referencedEntities();
  }

  /**
   * {@inheritdoc}
   */
  public function setTargetedUserIds(array $user_ids) {
    $this->set('users', $user_ids);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getTargetedUserIds(): array {
    $user_ids = [];
    foreach ($this->get('users') as $field_item) {
      $user_ids[] = $field_item->target_id;
    }
    return $user_ids;
  }

  /**
   * {@inheritdoc}
   */
  public function setTargetedRoles(array $roles) {
    $this->set('roles', $roles);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getTargetedRoles() {
    return $this->get('roles')->referencedEntities();
  }

  /**
   * {@inheritdoc}
   */
  public function getTargetedRoleIds(): array {
    $role_ids = [];
    foreach ($this->get('roles') as $field_item) {
      $role_ids[] = $field_item->target_id;
    }
    return $role_ids;
  }

  /**
   * {@inheritdoc}
   */
  public function setTargetedRoleIds(array $user_ids) {
    $this->set('users', $user_ids);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getPublishDate($timezone = 'UTC'): DrupalDateTime {
    return new DrupalDateTime($this->get('publish_date')->value, $timezone);
  }

  /**
   * {@inheritdoc}
   */
  public function setPublishDate(DrupalDateTime $publish_date) {
    $this->get('publish_date')->value = $publish_date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getUnpublishDate($timezone = 'UTC'): DrupalDateTime {
    return new DrupalDateTime($this->get('unpublish_date')->value, $timezone);
  }

  /**
   * {@inheritdoc}
   */
  public function setUnpublishDate(DrupalDateTime $unpublish_date) {
    $this->get('unpublish_date')->value = $unpublish_date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getToPublish(): bool {
    return (bool) $this->get('to_publish')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setToPublish(bool $to_publish) {
    $this->set('to_publish', $to_publish);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getStatus(): bool {
    return (bool) $this->get('status')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setStatus(bool $status) {
    $this->set('status', $status);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    $fields = parent::baseFieldDefinitions($entity_type);
    $fields += static::publishedBaseFieldDefinitions($entity_type);

    $fields['label'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Label'))
      ->setRequired(TRUE)
      ->setTranslatable(TRUE)
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'string',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Author'))
      ->setSetting('target_type', 'user')
      ->setDefaultValueCallback(static::class . '::getDefaultEntityOwner')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'author',
        'weight' => 15,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['message'] = BaseFieldDefinition::create('text_long')
      ->setLabel(t('Message'))
      ->setRequired(TRUE)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'text_textarea',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'text_default',
        'label' => 'above',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['users'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Users'))
      ->setDescription(t('The list of users to display the message to. Leave empty for all. Enter a comma-separated list. For example: Amsterdam, Mexico City, "Cleveland, Ohio"'))
      ->setSetting('target_type', 'user')
      ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete_tags',
        'weight' => 15,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'visible',
        'type' => 'label',
        'weight' => 1,
      ]);

    $fields['roles'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Roles'))
      ->setDescription(t('The user roles to display the message to. Leave empty for all.'))
      ->setSetting('target_type', 'user_role')
      ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => 20,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'visible',
        'type' => 'label',
        'weight' => 1,
      ]);

    $fields['publish_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('Publish Date'))
      ->setDescription(t('The date the alert message should be published.'))
      ->setRequired(TRUE)
      ->setSettings([
        'datetime_type' => 'datetime',
      ])
      ->setDefaultValue([
        'default_date' => 'now',
        'default_date_type' => 'now',
      ])
      ->setDisplayOptions('form', [
        'type' => 'datetime_default',
        'weight' => 25,
      ])
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'datetime_default',
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['unpublish_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('Unpublish date'))
      ->setDescription(t('The date the alert message should be unpublished.'))
      ->setRequired(TRUE)
      ->setSettings([
        'datetime_type' => 'datetime',
      ])
      ->setDefaultValue([
        'default_date' => '+2 day',
        'default_date_type' => 'relative',
      ])
      ->setDisplayOptions('form', [
        'type' => 'datetime_default',
        'weight' => 30,
      ])
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'datetime_default',
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['to_publish'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('To be published'))
      ->setDefaultValue(FALSE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Authored on'))
      ->setDescription(t('The time that the alert message was created.'))
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'timestamp',
        'weight' => 35,
        'settings' => [
          'tooltip' => [
            'date_format' => 'long',
            'custom_date_format' => '',
          ],
          'time_diff' => [
            'enabled' => FALSE,
            'future_format' => '@interval hence',
            'past_format' => '@interval ago',
            'granularity' => 2,
            'refresh' => 60,
          ],
        ],
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the alert message was last edited.'));

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Status'))
      ->setDefaultValue(FALSE)
      ->setSetting('on_label', 'Enabled')
      ->setDisplayOptions('view', [
        'type' => 'boolean',
        'label' => 'above',
        'weight' => 0,
        'settings' => [
          'format' => 'enabled-disabled',
        ],
      ])
      ->setDisplayConfigurable('view', TRUE);

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);
    if (!$this->getOwnerId()) {
      // If no owner has been set explicitly, make the anonymous user the owner.
      $this->setOwnerId(0);
    }
    // Reset publishing values to default.
    $this->setStatus(FALSE);
    $this->setToPublish(FALSE);

    $publish_date = $this->getPublishDate()->getTimestamp();
    $unpublish_date = $this->getUnpublishDate()->getTimestamp();
    $current_time = \Drupal::time()->getRequestTime();
    // Set to publish.
    if ($publish_date > $current_time) {
      $this->setToPublish(TRUE);
      return;
    }
    // Set publish.
    if ($publish_date <= $current_time && $unpublish_date >= $current_time) {
      $this->setStatus(TRUE);
      return;
    }
  }

}

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

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