mmk2410.org/site/models/article.php

45 lines
1.1 KiB
PHP
Raw Normal View History

2024-03-17 22:34:51 +01:00
<?php
2025-01-30 19:52:03 +01:00
use Kirby\Cms\Page;
/**
* @method object categories()
* @method object tags()
* @method object date()
* @method object text()
*/
2024-03-17 22:34:51 +01:00
class ArticlePage extends Page
{
2025-01-30 19:52:03 +01:00
private const READING_TIME_FORMAT = '%d words, ~%d min reading time';
/**
* @param array|string|null $options
*/
2024-03-17 22:34:51 +01:00
public function url($options = null): string
{
$date = $this->date()->toDate('Y/m/d');
return '/' . $date .'/' . $this->slug();
}
2025-01-30 19:52:03 +01:00
public function readingTime(): string
{
2024-03-17 22:34:51 +01:00
$doc = new DOMDocument();
2025-01-30 19:52:03 +01:00
$doc->loadHTML(
'<html><head><meta charset="UTF-8"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body>'
. $this->text()->kirbytext()
. '</body></html>'
2024-03-17 22:34:51 +01:00
);
$pElems = $doc->getElementsByTagName('p');
$text = '';
foreach ($pElems as $pElem) {
$text .= $pElem->nodeValue . ' ';
}
$wordCount = count(explode(' ', $text));
$readingTime = (int)ceil($wordCount / 150);
2025-01-30 19:52:03 +01:00
return sprintf(self::READING_TIME_FORMAT, $wordCount, $readingTime);
2024-03-17 22:34:51 +01:00
}
}