-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.php
executable file
·55 lines (45 loc) · 1.82 KB
/
plugin.php
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
<?php
declare(strict_types=1);
namespace Flextype\Plugin\ReadingTime {
use Twig\TwigFunction;
/**
* Get reading time
*
* @return string
*/
function readingTime(string $content, array $options = []): string
{
$defaults = [
'minute' => 'minute',
'minutes' => 'minutes',
'second' => 'second',
'seconds' => 'seconds',
'format' => '{minutes_count} {minutes_label}, {seconds_count} {seconds_label}',
'format.alt' => '{seconds_count} {seconds_label}',
'format.alt.enable' => false
];
$options = array_merge($defaults, $options);
$words = str_word_count(strip_tags($content));
$minutesCount = floor($words / 200);
$secondsCount = floor($words % 200 / (200 / 60));
$minutesLabel = ($minutesCount <= 1) ? $options['minute'] : $options['minutes'];
$secondsLabel = ($secondsCount <= 1) ? $options['second'] : $options['seconds'];
$replace = [
'minutes_count' => $minutesCount,
'minutes_label' => $minutesLabel,
'seconds_count' => $secondsCount,
'seconds_label' => $secondsLabel,
];
if ($minutesCount < 1 and $options['format.alt.enable'] === true) {
$result = $options['format.alt'];
} else {
$result = $options['format'];
}
foreach ($replace as $key => $value) {
$result = str_replace('{' . $key . '}', $value, $result);
}
return $result;
}
// Twig: {{ readingTime() }}
flextype('twig')->addFunction(new TwigFunction('readingTime', fn (string $content, array $options = []) => readingTime($content, $options)));
}