You are here

class ReadingTime in Node read time 8

Calculates the reading time of a node.

Hierarchy

Expanded class hierarchy of ReadingTime

1 file declares its use of ReadingTime
NodeReadTime.php in src/Plugin/views/field/NodeReadTime.php
1 string reference to 'ReadingTime'
node_read_time.services.yml in ./node_read_time.services.yml
node_read_time.services.yml
1 service uses ReadingTime
reading_time in ./node_read_time.services.yml
Drupal\node_read_time\Calculate\ReadingTime

File

src/Calculate/ReadingTime.php, line 12

Namespace

Drupal\node_read_time\Calculate
View source
class ReadingTime {
  use StringTranslationTrait;

  /**
   * Number of words per minute.
   *
   * @var int
   */
  private $wordsPerMinute;

  /**
   * The reading time value.
   *
   * @var int
   */
  private $readingTime;

  /**
   * The words from all the fields.
   *
   * @var string
   */
  private $words;

  /**
   * EntityTypeManager object.
   *
   * @var Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Stores the configuration factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Stores the configuration.
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $config;

  /**
   * Class constructor.
   *
   * @param Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   EntityTypeManager object.
   * @param Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   ConfigFactory object.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager, ConfigFactoryInterface $configFactory) {
    $this->entityTypeManager = $entityTypeManager;
    $this->configFactory = $configFactory;
    $this->config = $configFactory
      ->get('node_read_time.settings');
  }

  /**
   * Sets the number of words.
   *
   * @param int $words
   *   The number of collected words.
   */
  public function setWords($words) {
    $this->words = $words;
  }

  /**
   * Sets words per minute.
   *
   * @param int $wordsPerMinute
   *   Set the number of words per minute.
   *
   * @return \Drupal\node_read_time\Calculate\ReadingTime
   *   Returns this class object.
   */
  public function setWordsPerMinute($wordsPerMinute) {
    $this->wordsPerMinute = $wordsPerMinute;
    return $this;
  }

  /**
   * Gets the reading time value.
   *
   * @return int|null
   *   Returns the reading time value.
   */
  public function getReadingTime() {
    return $this->readingTime;
  }

  /**
   * Sets the reading time value.
   *
   * @@param int
   *   Sets the reading time value.
   */
  public function setReadingTime($readingTime) {
    $this->readingTime = $readingTime;
  }

  /**
   * Gets the fields from allowed types.
   *
   * @param object $entity
   *   The Entity that should be checked for textfields.
   *
   * @return \Drupal\node_read_time\Calculate\ReadingTime
   *   Returns this class object.
   */
  public function collectWords($entity) {
    $entity_fields = !empty($entity) ? $entity
      ->getFieldDefinitions() : NULL;
    $allowedTypes = [
      'text',
      'text_long',
      'text_with_summary',
      'string_long',
      'entity_reference_revisions',
    ];
    if ($entity_fields) {

      // Clean the unnecessary fields.
      foreach ($entity_fields as $k => $field) {
        if (!in_array($field
          ->getType(), $allowedTypes)) {
          unset($entity_fields[$k]);
        }

        // Remove revision fields.
        if (strpos($k, 'revision') !== FALSE) {
          unset($entity_fields[$k]);
        }
      }
      foreach ($entity_fields as $k => $field) {
        if (!empty($entity
          ->get($k)
          ->getValue()[0]['value'])) {
          $this->words .= $entity
            ->get($k)
            ->getValue()[0]['value'];
        }
        elseif ($field
          ->getType() == 'entity_reference_revisions') {
          $fieldStorage = $entity_fields[$k]
            ->get('fieldStorage');
          if ($fieldStorage) {
            $entityType = $fieldStorage
              ->get('settings')['target_type'];
            $list = $entity
              ->get($k)
              ->getValue();
            foreach ($list as $item) {
              $referenceRevisionEntity = $this->entityTypeManager
                ->getStorage($entityType)
                ->load($item['target_id']);
              $this
                ->collectWords($referenceRevisionEntity);
            }
          }
        }
      }
    }
    return $this;
  }

  /**
   * Calculate the reading time.
   *
   * @return $this
   */
  public function calculateReadingTime() {
    $unit = $this->config
      ->get('reading_time.unit_of_time');
    $words_count = count(preg_split('/\\s+/', strip_tags($this->words)));
    $reading_time = 0;
    if ($words_count > 1) {
      $minute = floor($words_count / $this->wordsPerMinute);
      $second = floor($words_count % $this->wordsPerMinute / ($this->wordsPerMinute / 60));
      switch ($unit) {
        case 'minute':
          $reading_time = $this
            ->formatPlural(ceil($words_count / $this->wordsPerMinute), '1 minute', '@count minutes');
          break;
        case 'second':
          $reading_time = $this
            ->formatPlural($minute, '1 minute', '@count minutes') . ', ' . $this
            ->formatPlural($second, '1 second', '@count seconds');
          break;
        default:
          $reading_time = ceil($words_count / $this->wordsPerMinute);
      }
    }
    $this->readingTime = $reading_time;
    return $this;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ReadingTime::$config protected property Stores the configuration.
ReadingTime::$configFactory protected property Stores the configuration factory.
ReadingTime::$entityTypeManager protected property EntityTypeManager object.
ReadingTime::$readingTime private property The reading time value.
ReadingTime::$words private property The words from all the fields.
ReadingTime::$wordsPerMinute private property Number of words per minute.
ReadingTime::calculateReadingTime public function Calculate the reading time.
ReadingTime::collectWords public function Gets the fields from allowed types.
ReadingTime::getReadingTime public function Gets the reading time value.
ReadingTime::setReadingTime public function Sets the reading time value.
ReadingTime::setWords public function Sets the number of words.
ReadingTime::setWordsPerMinute public function Sets words per minute.
ReadingTime::__construct public function Class constructor.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.