-
Notifications
You must be signed in to change notification settings - Fork 48
/
AnonymizeDate.php
71 lines (58 loc) · 1.84 KB
/
AnonymizeDate.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
<?php
declare(strict_types=1);
namespace Smile\GdprDump\Converter\Anonymizer;
use DateTime;
use Smile\GdprDump\Converter\ConverterInterface;
use Smile\GdprDump\Converter\Parameters\Parameter;
use Smile\GdprDump\Converter\Parameters\ParameterProcessor;
use UnexpectedValueException;
class AnonymizeDate implements ConverterInterface
{
protected string $defaultFormat = 'Y-m-d';
private string $format = 'Y-m-d';
/**
* @inheritdoc
*/
public function setParameters(array $parameters): void
{
$input = (new ParameterProcessor())
->addParameter('format', Parameter::TYPE_STRING, true, $this->defaultFormat)
->process($parameters);
$this->format = $input->get('format');
}
/**
* @inheritdoc
*
* @throws UnexpectedValueException
*/
public function convert(mixed $value, array $context = []): string
{
$value = (string) $value;
if ($value === '') {
return $value;
}
$date = DateTime::createFromFormat($this->format, $value);
if ($date === false) {
throw new UnexpectedValueException(sprintf('Failed to convert the value "%s" to a date.', $value));
}
$this->anonymizeDate($date);
return $date->format($this->format);
}
/**
* Anonymize the date.
*/
private function anonymizeDate(DateTime $date): void
{
// Get the year, month and day
$year = (int) $date->format('Y');
$month = (int) $date->format('n');
$day = (int) $date->format('j');
// Randomize the month and day
do {
$randomMonth = mt_rand(1, 12);
$randomDay = mt_rand(1, 31);
} while ($randomMonth === $month && $randomDay === $day);
// Replace the values
$date->setDate($year, $randomMonth, $randomDay);
}
}