Completed
Pull Request — master (#21)
by Hannes
09:11
created

DateTimeCreator::createFromFormat()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
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
                array_merge($errors['errors'], $errors['warnings'])
29
            )
30
        );
31
32
        throw new InvalidDateStructureException($msg);
33
    }
34
}
35