-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathComboDateAge.php
113 lines (94 loc) · 3.12 KB
/
ComboDateAge.php
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/**
* JBZoo Toolbox - Csv-Blueprint.
*
* This file is part of the JBZoo Toolbox project.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT
* @copyright Copyright (C) JBZoo.com, All rights reserved.
* @see https://github.com/JBZoo/Csv-Blueprint
*/
declare(strict_types=1);
namespace JBZoo\CsvBlueprint\Rules\Cell;
final class ComboDateAge extends AbstractCellRuleCombo
{
protected const NAME = 'age';
protected const INVALID_DATEINTERVAL_ACTUAL = -1;
protected const INVALID_DATEINTERVAL_EXPECTED = -2;
public function getHelpMeta(): array
{
return [
[
'Check an arbitrary date in a CSV cell for age (years).',
'Actually it calculates the difference between the date and the current date.',
'Convenient to use for age restrictions based on birthday.',
'See the description of `date_*` functions for details on date formats.',
],
[
self::MIN => [1, 'x >= 1'],
self::GREATER => [14, 'x > 14'],
self::NOT => [18, 'x != 18'],
self::EQ => [21, 'x == 21'],
self::LESS => [99, 'x < 99'],
self::MAX => [100, 'x <= 100'],
],
];
}
public static function analyzeColumnValues(array $columnValues): array|bool|float|int|string
{
$min = null;
$max = null;
foreach ($columnValues as $cellValue) {
if (!IsDate::testValue($cellValue)) {
return false;
}
$age = self::calculateAge($cellValue);
if ($min === null || $age < $min) {
$min = $age;
}
if ($max === null || $age > $max) {
$max = $age;
}
}
if ($min === null) {
return false;
}
return $max === $min
? ['' => $max]
: ['min' => $min, 'max' => $max];
}
protected function getActualCell(string $cellValue): float
{
try {
$years = self::calculateAge($cellValue);
} catch (\Exception) {
return self::INVALID_DATEINTERVAL_ACTUAL;
}
return $years;
}
protected function getExpected(): float
{
return $this->getOptionAsInt();
}
protected function getExpectedStr(): string
{
return "{$this->getOptionAsInt()} years";
}
protected function getCurrentStr(string $cellValue): string
{
try {
$years = self::calculateAge($cellValue);
} catch (\Exception $exception) {
return "<red>{$exception->getMessage()}</red>";
}
return "parsed as \"{$years}\" years";
}
private static function calculateAge(string $dateString): int
{
$birthDateTime = new \DateTimeImmutable($dateString);
$currentDateTime = new \DateTimeImmutable('now');
return $birthDateTime->diff($currentDateTime)->y; // Returns the total number of full years
}
}