You are here

class ScheduledPublishCron in Scheduled Publish 8.2

Same name and namespace in other branches
  1. 8.3 src/Service/ScheduledPublishCron.php \Drupal\scheduled_publish\Service\ScheduledPublishCron
  2. 8 src/Service/ScheduledPublishCron.php \Drupal\scheduled_publish\Service\ScheduledPublishCron

Class ScheduledPublishCron

@package Drupal\scheduled_publish\Service

Hierarchy

Expanded class hierarchy of ScheduledPublishCron

5 files declare their use of ScheduledPublishCron
FormatterTest.php in tests/src/Kernel/FormatterTest.php
MediaTest.php in tests/src/Kernel/MediaTest.php
NodeTest.php in tests/src/Kernel/NodeTest.php
ScheduledPublishCommands.php in src/Commands/ScheduledPublishCommands.php
scheduled_publish.module in ./scheduled_publish.module
Contains scheduled_publish.module.
1 string reference to 'ScheduledPublishCron'
scheduled_publish.services.yml in ./scheduled_publish.services.yml
scheduled_publish.services.yml
1 service uses ScheduledPublishCron
scheduled_publish.update in ./scheduled_publish.services.yml
Drupal\scheduled_publish\Service\ScheduledPublishCron

File

src/Service/ScheduledPublishCron.php, line 25

Namespace

Drupal\scheduled_publish\Service
View source
class ScheduledPublishCron {

  /**
   * @var array
   */
  public static $supportedTypes = [
    'node',
    'media',
    'block_content',
  ];

  /**
   * @var EntityTypeBundleInfo
   */
  private $entityBundleInfoService;

  /**
   * @var EntityFieldManager
   */
  private $entityFieldManager;

  /**
   * @var EntityTypeManager
   */
  private $entityTypeManager;

  /**
   * @var Time
   */
  private $dateTime;

  /**
   * ScheduledPublishCron constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entityBundleInfo
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entityFieldManager
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   * @param \Drupal\Component\Datetime\TimeInterface $dateTime
   */
  public function __construct(EntityTypeBundleInfoInterface $entityBundleInfo, EntityFieldManagerInterface $entityFieldManager, EntityTypeManagerInterface $entityTypeManager, TimeInterface $dateTime) {
    $this->entityBundleInfoService = $entityBundleInfo;
    $this->entityFieldManager = $entityFieldManager;
    $this->entityTypeManager = $entityTypeManager;
    $this->dateTime = $dateTime;
  }

  /**
   *  Run field updates
   */
  public function doUpdate() : void {
    foreach (self::$supportedTypes as $supportedType) {
      $this
        ->doUpdateFor($supportedType);
    }
  }

  /**
   * Run field update for specific entity type
   *
   * @param $entityType
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Exception
   */
  private function doUpdateFor($entityType) {
    $bundles = $this->entityBundleInfoService
      ->getBundleInfo($entityType);
    foreach ($bundles as $bundleName => $value) {
      $scheduledFields = $this
        ->getScheduledFields($entityType, $bundleName);
      if (\count($scheduledFields) > 0) {
        foreach ($scheduledFields as $scheduledField) {
          $query = $this->entityTypeManager
            ->getStorage($entityType)
            ->getQuery('AND');
          $query
            ->condition($entityType === 'media' ? 'bundle' : 'type', $bundleName);
          $query
            ->condition($scheduledField, NULL, 'IS NOT NULL');
          $query
            ->accessCheck(FALSE);
          $query
            ->latestRevision();
          $entities = $query
            ->execute();
          foreach ($entities as $entityRevision => $entityId) {
            $entity = $this->entityTypeManager
              ->getStorage($entityType)
              ->loadRevision($entityRevision);
            $this
              ->updateEntityField($entity, $scheduledField);
          }
        }
      }
    }
  }

  /**
   * Returns scheduled publish fields
   *
   * @param string $entityTypeName
   * @param string $bundleName
   *
   * @return array
   */
  private function getScheduledFields(string $entityTypeName, string $bundleName) : array {
    $scheduledFields = [];
    $fields = $this->entityFieldManager
      ->getFieldDefinitions($entityTypeName, $bundleName);
    foreach ($fields as $fieldName => $field) {

      /** @var FieldConfig $field */
      if (strpos($fieldName, 'field_') !== FALSE) {
        if ($field
          ->getType() === 'scheduled_publish') {
          $scheduledFields[] = $fieldName;
        }
      }
    }
    return $scheduledFields;
  }

  /**
   * Update scheduled publish fields
   *
   * @param \Drupal\Core\Entity\ContentEntityBase $entity
   * @param string $scheduledField
   *
   * @throws \Exception
   */
  private function updateEntityField(ContentEntityBase $entity, string $scheduledField) : void {

    /** @var FieldItemList $scheduledEntity */
    $scheduledEntity = $entity
      ->get($scheduledField);
    $scheduledValue = $scheduledEntity
      ->getValue();
    if (empty($scheduledValue)) {
      return;
    }
    $currentModerationState = $entity
      ->get('moderation_state')
      ->getValue()[0]['value'];
    foreach ($scheduledValue as $key => $value) {
      if ($currentModerationState === $value['moderation_state'] || $this
        ->getTimestampFromIso8601($value['value']) <= $this->dateTime
        ->getCurrentTime()) {
        unset($scheduledValue[$key]);
        $this
          ->updateEntity($entity, $value['moderation_state'], $scheduledField, $scheduledValue);
      }
    }
  }

  /**
   * Returns timestamp from ISO-8601 datetime
   *
   * @param string $dateIso8601
   *
   * @return int
   * @throws \Exception
   */
  private function getTimestampFromIso8601(string $dateIso8601) : int {
    $datetime = new DateTime($dateIso8601, new DateTimeZone(ScheduledPublish::STORAGE_TIMEZONE));
    $datetime
      ->setTimezone(new \DateTimeZone(drupal_get_user_timezone()));
    return $datetime
      ->getTimestamp();
  }

  /**
   * Updates entity
   *
   * @param \Drupal\Core\Entity\ContentEntityBase $entity
   * @param string $moderationState
   * @param string $scheduledPublishField
   * @param $scheduledValue
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  private function updateEntity(ContentEntityBase $entity, string $moderationState, string $scheduledPublishField, $scheduledValue) : void {
    $entity
      ->set($scheduledPublishField, $scheduledValue);
    $entity
      ->set('moderation_state', $moderationState);
    $entity
      ->save();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ScheduledPublishCron::$dateTime private property
ScheduledPublishCron::$entityBundleInfoService private property
ScheduledPublishCron::$entityFieldManager private property
ScheduledPublishCron::$entityTypeManager private property
ScheduledPublishCron::$supportedTypes public static property
ScheduledPublishCron::doUpdate public function Run field updates
ScheduledPublishCron::doUpdateFor private function Run field update for specific entity type
ScheduledPublishCron::getScheduledFields private function Returns scheduled publish fields
ScheduledPublishCron::getTimestampFromIso8601 private function Returns timestamp from ISO-8601 datetime
ScheduledPublishCron::updateEntity private function Updates entity
ScheduledPublishCron::updateEntityField private function Update scheduled publish fields
ScheduledPublishCron::__construct public function ScheduledPublishCron constructor.