ReadingTime.php in Node read time 8
File
src/Calculate/ReadingTime.php
View source
<?php
namespace Drupal\node_read_time\Calculate;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
class ReadingTime {
use StringTranslationTrait;
private $wordsPerMinute;
private $readingTime;
private $words;
protected $entityTypeManager;
protected $configFactory;
protected $config;
public function __construct(EntityTypeManagerInterface $entityTypeManager, ConfigFactoryInterface $configFactory) {
$this->entityTypeManager = $entityTypeManager;
$this->configFactory = $configFactory;
$this->config = $configFactory
->get('node_read_time.settings');
}
public function setWords($words) {
$this->words = $words;
}
public function setWordsPerMinute($wordsPerMinute) {
$this->wordsPerMinute = $wordsPerMinute;
return $this;
}
public function getReadingTime() {
return $this->readingTime;
}
public function setReadingTime($readingTime) {
$this->readingTime = $readingTime;
}
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) {
foreach ($entity_fields as $k => $field) {
if (!in_array($field
->getType(), $allowedTypes)) {
unset($entity_fields[$k]);
}
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;
}
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;
}
}