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

CurrentMonth   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 20
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 20
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A evaluate() 0 9 3
A __construct() 0 3 1
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