Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
Carbon
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
2 / 2
4
100.00% covered (success)
100.00%
1 / 1
 createFromDatetime
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 formatDuration
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Engelsystem\Helpers;
6
7use Carbon\CarbonInterval;
8
9class Carbon extends \Carbon\Carbon
10{
11    public const DATETIME_LOCAL = '!Y-m-d\TH:i';
12
13    public const DATETIME_FALLBACK = '!Y-m-d H:i';
14
15    public const DATETIME_DATABASE = '!Y-m-d\\TH:i:s.up';
16
17    public const DATETIME_FORMATS = [
18        self::DATETIME_LOCAL,
19        self::DATETIME_FALLBACK,
20        self::DEFAULT_TO_STRING_FORMAT,
21        self::DATETIME_DATABASE,
22    ];
23
24    /**
25     * Parses HTML datetime-local and ISO date/time strings.
26     *
27     * @return self|null Carbon if parseable, else null
28     * @see self::DATETIME_FORMATS
29     */
30    public static function createFromDatetime(string $value): ?\Carbon\Carbon
31    {
32        foreach (self::DATETIME_FORMATS as $datetimeFormat) {
33            if (self::canBeCreatedFromFormat($value, $datetimeFormat)) {
34                return self::createFromFormat($datetimeFormat, $value);
35            }
36        }
37
38        return null;
39    }
40
41    /**
42     * Formats a CarbonInterval into a human-readable duration string consisting of hours and minutes.
43     * Format is defined in the localization files under 'general.duration.format'.
44     *
45     * @param CarbonInterval $interval The interval to format
46     * @param string $format The format string, e.g. '%dh %02dm'
47     * @return string The formatted duration string
48     */
49    public static function formatDuration(CarbonInterval $interval, string $format): string
50    {
51        $interval->cascade();
52        $hours = floor($interval->totalHours);
53        $minutes = $interval->minutes;
54
55        return sprintf($format, $hours, $minutes);
56    }
57}