1 <?php declare(strict_types=1);
38 if (!is_string($from)) {
39 throw new \InvalidArgumentException(__METHOD__ .
" the argument is not a string.");
42 return $this->calculate($from);
49 private function calculate(
string $text) :
int 51 $text = mb_convert_encoding(
52 '<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body>' . $text .
'</body></html>',
57 $document = new \DOMDocument();
58 if (!@$document->loadHTML($text)) {
59 throw new \InvalidArgumentException(__METHOD__ .
" the argument is not a XHTML string.");
64 $xpath = new \DOMXPath($document);
65 $textNodes = $xpath->query(
'//text()');
66 if ($textNodes->length > 0) {
67 foreach ($textNodes as $textNode) {
69 if ($textNode instanceof \DOMCdataSection) {
73 $wordsInContent = array_filter(preg_split(
'/\s+/', $textNode->textContent));
75 $wordsInContent = array_filter($wordsInContent,
function (
string $word) {
76 return preg_replace(
'/^\pP$/',
'', $word) !==
'';
79 $numberOfWords += count($wordsInContent);
83 if ($this->withImages) {
84 $imageNodes = $document->getElementsByTagName(
'img');
88 $readingTime = ceil($numberOfWords / $this->wordsPerMinute);
90 return (
int) $readingTime;
102 for (
$i = 1;
$i <= $numberOfImages;
$i++) {
104 $time += 3 * ((int) $this->wordsPerMinute / 60);
106 $time += (12 - (
$i - 1)) * ((int) $this->wordsPerMinute / 60);
$firstImageReadingTimeInSeconds
transform($from)
Perform the transformation.Please use this for transformations. It's more performant than calling inv...
__construct(bool $withImages)
ReadingTime constructor.
trait DeriveApplyToFromTransform
trait DeriveInvokeFromTransform
calculateWordsForImages(int $numberOfImages)