forked from getgrav/grav-plugin-readingtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreadingtime.php
More file actions
60 lines (49 loc) · 1.68 KB
/
readingtime.php
File metadata and controls
60 lines (49 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
namespace Grav\Plugin;
use Grav\Common\Plugin;
use RocketTheme\Toolbox\Event\Event;
class ReadingTimePlugin extends Plugin
{
public static function getSubscribedEvents()
{
return [
'onPageContentProcessed' => ['onPageContentProcessed', 0]
];
}
public function onPageContentProcessed(Event $event)
{
$page = $event['page'];
$cacheKey = 'readingtime-' . $page->id();
// Ensure synchronous cache access
$readingTime = $this->grav['cache']->fetch($cacheKey);
if ($readingTime === false) {
$content = $page->content();
$readingTime = $this->calculateReadingTime($content);
$this->grav['cache']->save($cacheKey, $readingTime);
}
$this->modifyHeader($page, $readingTime);
}
private function modifyHeader($page, $readingTime)
{
$header = $page->header();
$minutes_short_count = $readingTime;
$minutes_text = ($minutes_short_count == 1) ?
$this->grav['language']->translate('PLUGIN_READINGTIME.MINUTE') :
$this->grav['language']->translate('PLUGIN_READINGTIME.MINUTES');
$readingTimeString = sprintf(
'%s: %s %s',
$this->grav['language']->translate('PLUGIN_READINGTIME.READING_LABEL'),
$minutes_short_count,
$minutes_text
);
$header->readingTime = $readingTimeString;
$page->header($header);
}
private function calculateReadingTime($text)
{
$wordCount = str_word_count(strip_tags($text));
$wordsPerMinute = 200;
$readingTime = ceil($wordCount / $wordsPerMinute);
return $readingTime;
}
}