TimeToRead   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 1
dl 0
loc 54
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A get() 0 4 1
A calculate() 0 24 5
1
<?php
2
3
namespace GinoPane\BlogTimeToRead\Helpers;
4
5
use GinoPane\BlogTimeToRead\Models\Settings;
6
7
class TimeToRead
8
{
9
    /** @var Settings */
10
    private $settings = null;
11
12
    /**
13
     * TimeToRead constructor
14
     *
15
     * @param Settings $settings
16
     */
17
    public function __construct(Settings $settings)
18
    {
19
        $this->settings = $settings;
20
    }
21
22
    /**
23
     * @return TimeToRead
24
     */
25
    public static function get()
26
    {
27
        return new self(Settings::instance());
28
    }
29
30
    /**
31
     * @param string $text
32
     * @param array  $options
33
     *
34
     * @return int
35
     */
36
    public function calculate(string $text, array $options = []): int
37
    {
38
        $readingSpeed = abs(
39
            isset($options[Settings::READING_SPEED_KEY])
40
            ? (int)$options[Settings::READING_SPEED_KEY]
41
            : $this->settings->readingSpeed()
42
        );
43
44
        $isRoundingUpEnabled = isset($options[Settings::ROUNDING_UP_ENABLED_KEY])
45
            ? (bool)$options[Settings::ROUNDING_UP_ENABLED_KEY]
46
            : $this->settings->isRoundingUpEnabled();
47
48
        if (!$readingSpeed) {
49
            return 0;
50
        } else {
51
            $rawTimeToRead = str_word_count(strip_tags($text)) / $readingSpeed;
52
53
            if ($isRoundingUpEnabled) {
54
                return ceil($rawTimeToRead);
55
            } else {
56
                return (int)round($rawTimeToRead);
57
            }
58
        }
59
    }
60
}