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

DateHelper   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 4
eloc 9
c 2
b 0
f 0
dl 0
loc 26
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A format() 0 7 2
A validate() 0 9 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