NodeReadTime.php in Node read time 8
File
src/Plugin/views/field/NodeReadTime.php
View source
<?php
namespace Drupal\node_read_time\Plugin\views\field;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node_read_time\Calculate\ReadingTime;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Symfony\Component\DependencyInjection\ContainerInterface;
class NodeReadTime extends FieldPluginBase {
protected $configManager;
protected $readingTime;
public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config_factory, ReadingTime $reading_time) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->configManager = $config_factory;
$this->readingTime = $reading_time;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('config.factory'), $container
->get('reading_time'));
}
public function query() {
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['message_not_enable'] = [
'default' => '',
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$form['message_not_enable'] = [
'#title' => $this
->t('Message to display in case node read time is not enabled'),
'#description' => $this
->t('This text will be displayed in case the node type
does not have read time enable. Can be empty.'),
'#type' => 'textfield',
'#default_value' => $this->options['message_not_enable'],
];
parent::buildOptionsForm($form, $form_state);
}
public function render(ResultRow $values) {
$node = $this
->getEntity($values);
$config = $this->configManager
->get('node_read_time.settings');
$bundles = $config
->get('reading_time')['container'];
if ($bundles) {
foreach ($bundles as $machine_name => $bundle) {
if ($bundle['is_activated'] && $machine_name === $node
->getType()) {
$words_per_minute = $this->configManager
->get('node_read_time.settings')
->get('reading_time')['words_per_minute'] ?: 225;
$reading_time = $this->readingTime
->setWordsPerMinute($words_per_minute)
->collectWords($node)
->calculateReadingTime()
->getReadingTime();
$this->readingTime
->setWords(0);
return [
'#theme' => 'reading_time',
'#reading_time' => $reading_time,
];
}
}
}
return $this->options['message_not_enable'];
}
}