Passed
Push — master ( fe8da9...4bb742 )
by Saulius
02:35
created

ElapsedTime::execute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 13
nc 3
nop 3
dl 0
loc 22
ccs 14
cts 14
cp 1
crap 3
rs 9.2
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the sauls/helpers package.
4
 *
5
 * @author    Saulius Vaičeliūnas <[email protected]>
6
 * @link      http://saulius.vaiceliunas.lt
7
 * @copyright 2018
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
namespace Sauls\Component\Helper\Operation\DateTimeOperation;
14
15
use Sauls\Component\Helper\Operation\ArrayOperation;
16
17
class ElapsedTime extends AbstractOperation implements ElapsedTimeInterface
18
{
19
    private $labels = [
20
        'singular' => [
21
            '{year}' => 'yr',
22
            '{month}' => 'mo',
23
            '{week}' => 'w',
24
            '{day}' => 'd',
25
            '{hour}' => 'h',
26
            '{minute}' => 'm',
27
            '{second}' => 's',
28
        ],
29
        'plural' => [
30
            '{years}' => 'yr',
31
            '{months}' => 'mo',
32
            '{weeks}' => 'w',
33
            '{days}' => 'd',
34
            '{hours}' => 'h',
35
            '{minutes}' => 'm',
36
            '{seconds}' => 's',
37
        ],
38
    ];
39
40
    private $timeOffsets = [
41
        ['{year}', '{years}', 31557600],
42
        ['{month}', '{months}', 2592000],
43
        ['{week}', '{weeks}', 604800],
44
        ['{day}', '{days}', 86400],
45
        ['{hour}', '{hours}', 3600],
46
        ['{minute}', '{minutes}', 60],
47
        ['{second}', '{seconds}', 1],
48
    ];
49
50
51
    /**
52
     * @var ArrayOperation\MergeInterface
53
     */
54
    private $arrayMergeOperation;
55
56
    /**
57
     * @var ArrayOperation\GetValue
58
     */
59
    private $arrayGetValueOperation;
60
61 1
    public function __construct(
62
        ArrayOperation\MergeInterface $arrayMergeOperation,
63
        ArrayOperation\GetValue $arrayGetValueOperation
64
    ) {
65 1
        $this->arrayMergeOperation = $arrayMergeOperation;
66 1
        $this->arrayGetValueOperation = $arrayGetValueOperation;
67 1
    }
68
69
    /**
70
     * @throws \Sauls\Component\Helper\Exception\PropertyNotAccessibleException
71
     */
72 14
    public function execute($date, array $labels, string $format = self::ELAPSED_TIME_FORMAT_FULL): string
73
    {
74 14
        $elapsedTimeLabels = $this->arrayMergeOperation->execute($this->labels, $labels);
75
76 14
        $date = $this->createDateObject($date);
77
78 14
        $time = $date->getTimestamp();
79 14
        $timeDifference = time() - $time;
80 14
        $timeLeftValues = [];
81
82 14
        foreach ($this->timeOffsets as [$timeSingle, $timePlural, $offset]) {
83 14
            if ($timeDifference >= $offset) {
84 14
                $timeLeft = floor($timeDifference / $offset);
85 14
                $timeDifference -= ($timeLeft * $offset);
86 14
                $timeLeftValues[] = $this->formatLabel((int)$timeLeft, $elapsedTimeLabels, [
87 14
                    'singular' => $timeSingle,
88 14
                    'plural' => $timePlural,
89
                ]);
90
            }
91
        }
92
93 14
        return $this->outputElapsedTime($timeLeftValues, $format);
94
    }
95
96
    /**
97
     * @throws \Sauls\Component\Helper\Exception\PropertyNotAccessibleException
98
     */
99 14
    private function formatLabel(int $timeLeft, array $labels, array $timeStrings): string
100
    {
101 14
        return \sprintf(
102 14
            '%s%s', $timeLeft,
103 14
            (1 === $timeLeft
104 10
                ? $this->formatSingularLabel($labels, $timeStrings)
105 14
                : $this->formatPlurarLabel($labels, $timeStrings)
106
            )
107
        );
108
    }
109
110
    /**
111
     * @throws \Sauls\Component\Helper\Exception\PropertyNotAccessibleException
112
     */
113 10
    private function formatSingularLabel(array $labels, array $timeStrings): string
114
    {
115 10
        return \strtr(
116 10
            $this->arrayGetValueOperation->execute($timeStrings, 'singular', ''),
117 10
            $this->arrayGetValueOperation->execute($labels, 'singular', '')
0 ignored issues
show
Bug introduced by
It seems like $this->arrayGetValueOper...labels, 'singular', '') can also be of type string; however, parameter $replace_pairs of strtr() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

117
            /** @scrutinizer ignore-type */ $this->arrayGetValueOperation->execute($labels, 'singular', '')
Loading history...
118
        );
119
    }
120
121
    /**
122
     * @throws \Sauls\Component\Helper\Exception\PropertyNotAccessibleException
123
     */
124 14
    private function formatPlurarLabel(array $labels, array $timeStrings): string
125
    {
126 14
        return \strtr(
127 14
            $this->arrayGetValueOperation->execute($timeStrings, 'plural', ''),
128 14
            $this->arrayGetValueOperation->execute($labels, 'plural', '')
0 ignored issues
show
Bug introduced by
It seems like $this->arrayGetValueOper...($labels, 'plural', '') can also be of type string; however, parameter $replace_pairs of strtr() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

128
            /** @scrutinizer ignore-type */ $this->arrayGetValueOperation->execute($labels, 'plural', '')
Loading history...
129
        );
130
    }
131
132
    /**
133
     * @throws \Sauls\Component\Helper\Exception\PropertyNotAccessibleException
134
     */
135 14
    private function outputElapsedTime(array $timeLeftValues, string $format): string
136
    {
137 14
        if (self::ELAPSED_TIME_FORMAT_SHORT === $format) {
138 10
            return $this->arrayGetValueOperation->execute($timeLeftValues, 0, '');
139
        }
140
141 4
        return \implode(' ', $timeLeftValues);
142
    }
143
}
144