summaryrefslogtreecommitdiff
path: root/src/Validators/DateFormatValidator.php
blob: fedbb7dde8f42f10b64310c98681b72a93f4e8eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php

namespace Askonomm\Hird\Validators;

/**
 * Implements a DateFormat validator that has a job 
 * of validating that a given date is in the correct
 * format.
 * 
 * @author Asko Nomm <asko@bien.ee>
 */
class DateFormatValidator implements Validator
{
    /**
     * Returns a boolean `true` when given `$value` is a valid e-mail
     * address. Returns `false` otherwise.
     *
     * @param string $field
     * @param mixed $value
     * @param mixed $modifier
     * @return boolean
     */
    public static function validate(string $field, mixed $value, mixed $modifier = null): bool
    {
        if ($value) {
            $datetime = \DateTime::createFromFormat($modifier, $value);

            return $datetime !== false && !array_sum($datetime::getLastErrors());
        }

        return true;
    }

    /**
     * Composes the error message in case the validation fails.
     *
     * @param string $field
     * @param mixed $modifier
     * @return string
     */
    public static function composeError(string $field, mixed $modifier = null): string
    {
        return "${field} does not match the required date format ${modifier}.";
    }
}