Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Подсчет времени чтения статьи (PHP)
/**
* Class readTimeEstimate
* Подсчет времени чтения статьи
*/
class readTimeEstimate
{
/**
* Средняя скорость чтения слов в минуту
*/
const WORDS_PER_MINUTE = 200;
const STR_MINUTE = 'мин.';
const STR_SECOND = 'сек.';
private $minutes;
private $seconds;
/**
* readTimeEstimate constructor.
* @param string $str
*/
function __construct(string $str)
{
$wordCount = $this->wordCount(strip_tags($str));
$this->minutes = floor($wordCount / static::WORDS_PER_MINUTE);
$this->seconds = floor($wordCount % static::WORDS_PER_MINUTE / (static::WORDS_PER_MINUTE / 60));
}
/**
* @return string
*/
public function __toString(): string
{
return ($this->minutes == 0) ? $this->seconds . ' ' . static::STR_MINUTE
: $this->minutes . ' ' .
static::STR_MINUTE . ', ' .
$this->seconds . ' ' .
static::STR_SECOND;
}
/**
* @return float
*/
public function getMinutes(): float
{
return $this->minutes;
}
/**
* @return float
*/
public function getSeconds(): float
{
return $this->seconds;
}
/**
* @param string $str
* @return int
*/
protected function wordCount(string $str): int
{
$v = preg_split('/\W+/u', $str, -1, PREG_SPLIT_NO_EMPTY);
return count($v);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment