forked from Setono/CronExpressionBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCronExpressionToStringTransformer.php
More file actions
53 lines (44 loc) · 1.38 KB
/
CronExpressionToStringTransformer.php
File metadata and controls
53 lines (44 loc) · 1.38 KB
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
<?php
declare(strict_types=1);
namespace Setono\CronExpressionBundle\Form\DataTransformer;
use Cron\CronExpression;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
/**
* @template-implements DataTransformerInterface<CronExpression, string>
*/
final class CronExpressionToStringTransformer implements DataTransformerInterface
{
/**
* @param mixed $value
*/
#[\Override]
public function transform($value): ?string
{
if (null === $value) {
return '* * * * *';
}
if (!$value instanceof CronExpression) {
throw new TransformationFailedException('Expected an instance of ' . CronExpression::class);
}
return $value->getExpression();
}
/**
* @param mixed $value
*/
#[\Override]
public function reverseTransform($value): CronExpression
{
if (null === $value || '' === $value) {
return CronExpression::factory('* * * * *');
}
if (!is_string($value)) {
throw new TransformationFailedException('Expected an instance of string');
}
try {
return CronExpression::factory($value);
} catch (\InvalidArgumentException $ex) {
throw new TransformationFailedException('Invalid CronExpression', $ex->getCode(), $ex);
}
}
}