TextHelpers::estimateReadingTime()   B
last analyzed

Complexity

Conditions 7
Paths 20

Size

Total Lines 31
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 16
c 1
b 0
f 0
nc 20
nop 3
dl 0
loc 31
ccs 0
cts 15
cp 0
crap 56
rs 8.8333
1
<?php
2
3
namespace App\Helpers;
4
5
class TextHelpers
6
{
7
8
    /**
9
     * Return the estimated reading time for a given piece of $content in minutes.
10
     *
11
     * Average reading speed is between 230-280 words per minute,
12
     * so he using 200 here is keeping some limit to provide pessimistic reading time.
13
     * Most of people should read it faster.
14
     *
15
     * @param string $content Content to calculate read time for.
16
     * @param int $wpm Estimated words per minute of reader.
17
     *
18
     * @return string estimated read time eg. 1 minute, 30 seconds
19
     */
20
    public static function estimateReadingTime(
21
        string $content = '',
22
        int $wpm = 200,
23
        string $format = null
24
    ): string {
25
26
        $word_count = str_word_count(strip_tags($content));
27
28
        $minutes = floor($word_count / $wpm);
29
        $seconds = floor($word_count % $wpm / ($wpm / 60));
30
31
        $str_minutes = ($minutes == 1) ? "minute" : "minutes";
32
        $str_seconds = ($seconds == 1) ? "second" : "seconds";
33
34
        if ($format == 'minutes') {
35
            if ($minutes == 0) {
36
                return 'Less then one minute';
37
            } else {
38
                return "{$minutes}";
39
            }
40
        }
41
42
        if ($format == 'minutesAndSeconds') {
43
            if ($minutes == 0) {
44
                return "{$seconds} {$str_seconds}";
45
            } else {
46
                return "{$minutes} {$str_minutes}, {$seconds} {$str_seconds}";
47
            }
48
        }
49
50
        return "Please specify the time format";
51
    }
52
}
53