|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Yokai\Batch\Bridge\Symfony\Validator; |
| 6 | + |
| 7 | +use DateTimeInterface; |
| 8 | +use Symfony\Component\Validator\ConstraintViolationInterface; |
| 9 | +use Symfony\Component\Validator\Validator\ValidatorInterface; |
| 10 | +use Yokai\Batch\Job\Item\InvalidItemException; |
| 11 | +use Yokai\Batch\Job\Item\ItemProcessorInterface; |
| 12 | + |
| 13 | +final class SkipInvalidItemProcessor implements ItemProcessorInterface |
| 14 | +{ |
| 15 | + /** |
| 16 | + * @var ValidatorInterface |
| 17 | + */ |
| 18 | + private $validator; |
| 19 | + |
| 20 | + /** |
| 21 | + * @var array|null |
| 22 | + */ |
| 23 | + private $groups; |
| 24 | + |
| 25 | + public function __construct(ValidatorInterface $validator, array $groups = null) |
| 26 | + { |
| 27 | + $this->validator = $validator; |
| 28 | + $this->groups = $groups; |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * @inheritDoc |
| 33 | + */ |
| 34 | + public function process($item) |
| 35 | + { |
| 36 | + $violations = $this->validator->validate($item, null, $this->groups); |
| 37 | + if (count($violations) === 0) { |
| 38 | + return $item; |
| 39 | + } |
| 40 | + |
| 41 | + $issues = []; |
| 42 | + /** @var ConstraintViolationInterface $violation */ |
| 43 | + foreach ($violations as $violation) { |
| 44 | + $issues[] = sprintf( |
| 45 | + '%s: %s: %s', |
| 46 | + $violation->getPropertyPath(), |
| 47 | + $violation->getMessage(), |
| 48 | + $this->normalizeInvalidValue($violation->getInvalidValue()) |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + throw new InvalidItemException(implode(PHP_EOL, $issues)); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * @param mixed $invalidValue |
| 57 | + * |
| 58 | + * @return integer|float|string|boolean |
| 59 | + */ |
| 60 | + private function normalizeInvalidValue($invalidValue) |
| 61 | + { |
| 62 | + if ($invalidValue === '') { |
| 63 | + return '""'; |
| 64 | + } |
| 65 | + if ($invalidValue === null) { |
| 66 | + return 'NULL'; |
| 67 | + } |
| 68 | + if (is_scalar($invalidValue)) { |
| 69 | + return $invalidValue; |
| 70 | + } |
| 71 | + |
| 72 | + if (is_iterable($invalidValue)) { |
| 73 | + $invalidValues = []; |
| 74 | + foreach ($invalidValue as $value) { |
| 75 | + $invalidValues[] = $this->normalizeInvalidValue($value); |
| 76 | + } |
| 77 | + |
| 78 | + return implode(', ', $invalidValues); |
| 79 | + } |
| 80 | + |
| 81 | + if (is_object($invalidValue)) { |
| 82 | + if ($invalidValue instanceof DateTimeInterface) { |
| 83 | + return $invalidValue->format(DateTimeInterface::ISO8601); |
| 84 | + } |
| 85 | + |
| 86 | + if (method_exists($invalidValue, '__toString')) { |
| 87 | + return (string)$invalidValue; |
| 88 | + } |
| 89 | + |
| 90 | + return sprintf('%s:%s', get_class($invalidValue), spl_object_hash($invalidValue)); |
| 91 | + } |
| 92 | + |
| 93 | + return gettype($invalidValue); |
| 94 | + } |
| 95 | +} |
0 commit comments