You are here

public function ReadingTime::calculateReadingTime in Node read time 8

Calculate the reading time.

Return value

$this

File

src/Calculate/ReadingTime.php, line 184

Class

ReadingTime
Calculates the reading time of a node.

Namespace

Drupal\node_read_time\Calculate

Code

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;
}