Completed
Push — master ( 6f9e63...511ba3 )
by Radu
02:00
created

DateHelper::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
rs 10
cc 2
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace WebServCo\Framework\Helpers;
6
7
use WebServCo\Framework\Exceptions\DateTimeException;
8
9
class DateHelper
10
{
11
    /**
12
    * Format a date, with validation.
13
    */
14
    public static function format(string $date, string $format = 'Y-m-d'): string
15
    {
16
        $dateTime = \DateTime::createFromFormat($format, $date);
17
        if (false === $dateTime) {
18
            throw new DateTimeException('Invalid date or format.');
19
        }
20
        return $dateTime->format($format);
21
    }
22
23
    /**
24
    * Validate an already formatted date.
25
    */
26
    public static function validate(string $date, string $format = 'Y-m-d'): bool
27
    {
28
        $formattedDate = self::format($date, $format);
29
30
        if ($formattedDate !== $date) {
31
            throw new DateTimeException('Invalid date or format.');
32
        }
33
34
        return true;
35
    }
36
}
37