DateTimeCreator::createFromFormat()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace byrokrat\id\Helper;
6
7
use byrokrat\id\Exception\InvalidDateStructureException;
8
9
class DateTimeCreator
10
{
11
    /**
12
     * Returns new DateTime object formatted according to the specified format
13
     *
14
     * @throws InvalidDateStructureException If creation fail
15
     */
16
    public static function createFromFormat(string $format, string $date): \DateTime
17
    {
18
        if ($dateTime = \DateTime::createFromFormat($format, $date)) {
19
            $dateTime->setTime(0, 0, 0);
20
            return $dateTime;
21
        }
22
23
        $errors = \DateTime::getLastErrors();
24
25
        $msg = trim(
26
            implode(
27
                ', ',
28
                // @phpstan-ignore-next-line
29
                array_merge((array)($errors['errors'] ?? []), (array)($errors['warnings'] ?? []))
30
            )
31
        );
32
33
        throw new InvalidDateStructureException($msg);
34
    }
35
}
36