Completed
Push — master ( 3cf61a...455b58 )
by Saulius
01:58
created

countdown()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 8
nop 3
dl 0
loc 18
ccs 10
cts 10
cp 1
crap 5
rs 8.8571
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 15 and the first side effect is on line 15.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
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;
14
15
\define('ELAPSED_TIME_LABEL_SINGLE', 'single');
16
\define('ELAPSED_TIME_LABEL_PLURAL', 'plural');
17
\define('DEFAULT_ELAPSED_TIME_LABELS', [
18
    ELAPSED_TIME_LABEL_SINGLE => [
19
        '{year}' => 'yr',
20
        '{month}' => 'mo',
21
        '{week}' => 'w',
22
        '{day}' => 'd',
23
        '{hour}' => 'h',
24
        '{minute}' => 'm',
25
        '{second}' => 's',
26
    ],
27
    ELAPSED_TIME_LABEL_PLURAL => [
28
        '{years}' => 'yr',
29
        '{months}' => 'mo',
30
        '{weeks}' => 'w',
31
        '{days}' => 'd',
32
        '{hours}' => 'h',
33
        '{minutes}' => 'm',
34
        '{seconds}' => 's',
35
    ],
36
]);
37
\define('DEFAULT_ELAPSED_TIME_OFFSETS', [
38
    ['{year}', '{years}', 31557600],
39
    ['{month}', '{months}', 2592000],
40
    ['{week}', '{weeks}', 604800],
41
    ['{day}', '{days}', 86400],
42
    ['{hour}', '{hours}', 3600],
43
    ['{minute}', '{minutes}', 60],
44
    ['{second}', '{seconds}', 1],
45
]);
46
47
/**
48
 * @param string|\DateTime $date
49
 */
50
function print_elapsed_time_short($date, array $elapsedTimeLabels = []): string
51
{
52 10
    return elapsed_time($date, $elapsedTimeLabels)[0];
53
}
54
55
/**
56
 * @param string|\DateTime $date
57
 */
58
function print_elapsed_time_long($date, array $elapsedTimeLabels = []): string
59
{
60 4
    return implode(' ', elapsed_time($date, $elapsedTimeLabels));
61
}
62
63
/**
64
 * @param string|\DateTime $date
65
 */
66
function elapsed_time($date, array $elapsedTimeLabels = []): array
67
{
68 14
    $elapsedTimeLabels = array_merge(DEFAULT_ELAPSED_TIME_LABELS, $elapsedTimeLabels);
69
70 14
    if (\is_string($date)) {
71 2
        $date = new \DateTime($date);
72
    }
73
74 14
    $time = $date->getTimestamp();
75 14
    $diff = time() - $time;
76 14
    $timeLeft = [];
77
78 14
    foreach (DEFAULT_ELAPSED_TIME_OFFSETS as list($timeSingle, $timePlural, $offset)) {
79 14
        if ($diff >= $offset) {
80 14
            $left = floor($diff / $offset);
81 14
            $diff -= ($left * $offset);
82 14
            $timeLeft[] = format_elapsed_time_string($left, $elapsedTimeLabels, [
0 ignored issues
show
Bug introduced by
$left of type double is incompatible with the type integer expected by parameter $timeLeft of Sauls\Component\Helper\f...t_elapsed_time_string(). ( Ignorable by Annotation )

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

82
            $timeLeft[] = format_elapsed_time_string(/** @scrutinizer ignore-type */ $left, $elapsedTimeLabels, [
Loading history...
83 14
                ELAPSED_TIME_LABEL_SINGLE => $timeSingle,
84 14
                ELAPSED_TIME_LABEL_PLURAL => $timePlural,
85
            ]);
86
        }
87
    }
88
89 14
    return $timeLeft;
90
}
91
92
function format_elapsed_time_string(int $timeLeft, array $elapsedTimeLabels, array $timeStrings): string
93
{
94 18
    return sprintf('%s%s', $timeLeft, (1 === $timeLeft ? strtr(
0 ignored issues
show
Bug introduced by
The call to strtr() has too few arguments starting with to. ( Ignorable by Annotation )

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

94
    return sprintf('%s%s', $timeLeft, (1 === $timeLeft ? /** @scrutinizer ignore-call */ strtr(

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
95 12
            array_get_value($timeStrings, ELAPSED_TIME_LABEL_SINGLE, ''),
96 12
            array_get_value($elapsedTimeLabels, ELAPSED_TIME_LABEL_SINGLE)
97 16
        ) : strtr(
98 16
            array_get_value($timeStrings, ELAPSED_TIME_LABEL_PLURAL, ''),
99 18
            array_get_value($elapsedTimeLabels, ELAPSED_TIME_LABEL_PLURAL)
100
        )
101
    ));
102
}
103
104
/**
105
 * @param string|\DateTime $dateFrom
106
 * @param string|\DateTime $dateTo
107
 */
108
function countdown($dateFrom = 'now', $dateTo, string $outputFormat = '%s%02d:%02d:%02d'): string
109
{
110 7
    $dateFrom = $dateFrom instanceof \DateTime ? $dateFrom : new \DateTime($dateFrom);
111 7
    $dateTo = $dateTo instanceof \DateTime ? $dateTo : new \DateTime($dateTo);
112
113 7
    $dateDifference = $dateFrom->diff($dateTo);
114
115 7
    $dateFromHigherThanDateTo = $dateFrom > $dateTo;
116
117 7
    $hours = $dateDifference->h;
118 7
    $minutes = $dateDifference->i;
119 7
    $seconds = $dateDifference->s;
120
121 7
    if ($dateDifference->days > 0) {
122 5
        $hours += $dateDifference->days * 24;
123
    }
124
125 7
    return sprintf($outputFormat, $dateFromHigherThanDateTo ? '-' : '', $hours, $minutes, $seconds);
126
}
127