Passed
Push — main ( ea004a...3eacfa )
by Breno
02:30
created

CurrentMonth::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Rules\DateTime;
5
6
use Attribute;
7
use BrenoRoosevelt\Validation\AbstractValidation;
8
use DateTimeImmutable;
9
use Throwable;
10
11
#[Attribute(Attribute::TARGET_PROPERTY)]
12
class CurrentMonth extends AbstractValidation
13
{
14
    const CURRENT_MONTH = 'm';
15
    const CURRENT_MONTH_SAME_YEAR = 'Y-m';
16
17
    public function __construct(private bool $sameYear = true, ?string $message = 'The date/time should be today')
18
    {
19
        parent::__construct($message);
20
    }
21
22
    protected function evaluate($input, array $context = []): bool
23
    {
24
        try {
25
            $now = new DateTimeImmutable();
26
            $datetime = new DateTimeImmutable($input);
27
            $format = $this->sameYear ? self::CURRENT_MONTH_SAME_YEAR : self::CURRENT_MONTH;
28
            return $datetime->format($format) === $now->format($format);
29
        } catch (Throwable) {
30
            return false;
31
        }
32
    }
33
}
34