|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Wwwision\SubscriptionEngine\Engine; |
| 6 | + |
| 7 | +use InvalidArgumentException; |
| 8 | + |
| 9 | +/** |
| 10 | + * @implements \IteratorAggregate<Error> |
| 11 | + */ |
| 12 | +final readonly class Errors implements \IteratorAggregate, \Countable |
| 13 | +{ |
| 14 | + private const int CLAMP_ERRORS = 5; |
| 15 | + |
| 16 | + /** |
| 17 | + * @var non-empty-array<Error> |
| 18 | + */ |
| 19 | + private array $errors; |
| 20 | + |
| 21 | + private function __construct(Error ...$errors) |
| 22 | + { |
| 23 | + if ($errors === []) { |
| 24 | + throw new InvalidArgumentException('Errors must not be empty.', 1736159619); |
| 25 | + } |
| 26 | + $this->errors = array_values($errors); |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * @param array<Error> $errors |
| 31 | + */ |
| 32 | + public static function fromArray(array $errors): self |
| 33 | + { |
| 34 | + return new self(...$errors); |
| 35 | + } |
| 36 | + |
| 37 | + public function getIterator(): \Traversable |
| 38 | + { |
| 39 | + yield from $this->errors; |
| 40 | + } |
| 41 | + |
| 42 | + public function count(): int |
| 43 | + { |
| 44 | + return count($this->errors); |
| 45 | + } |
| 46 | + |
| 47 | + public function first(): Error |
| 48 | + { |
| 49 | + return $this->errors[array_key_first($this->errors)]; |
| 50 | + } |
| 51 | + |
| 52 | + public function getClampedMessage(): string |
| 53 | + { |
| 54 | + $additionalMessage = ''; |
| 55 | + $lines = []; |
| 56 | + foreach ($this->errors as $error) { |
| 57 | + $lines[] = sprintf('%s"%s": %s', $error->position ? 'Event ' . $error->position->value . ' in ' : '', $error->subscriptionId->value, $error->message); |
| 58 | + if (count($lines) >= self::CLAMP_ERRORS) { |
| 59 | + $additionalMessage = sprintf('%sAnd %d other exceptions, see log.', ";\n", count($this->errors) - self::CLAMP_ERRORS); |
| 60 | + break; |
| 61 | + } |
| 62 | + } |
| 63 | + return implode(";\n", $lines) . $additionalMessage; |
| 64 | + } |
| 65 | +} |
0 commit comments