99use TypeLang \Mapper \Diagnostics \ViolationFormatterInterface ;
1010
1111/**
12- * Mapping failure caused by invalid input.
12+ * Mapping failure caused by invalid input. Iterates over the violations in
13+ * order of appearance, a fatal one tells a defect of the code behind the
14+ * input, see {@see Violation::$isFatal}.
15+ *
16+ * @template-implements \IteratorAggregate<int, Violation>
1317 */
14- abstract class ViolationException extends \RuntimeException
18+ abstract class ViolationException extends \RuntimeException implements \IteratorAggregate, \Countable
1519{
20+ /**
21+ * Whether a violation is caused by an {@see \Error}
22+ */
23+ public readonly bool $ hasFatalViolations ;
24+
1625 protected function __construct (
1726 /**
1827 * Violations in order of appearance
@@ -24,6 +33,76 @@ protected function __construct(
2433 ?\Throwable $ previous = null ,
2534 ) {
2635 parent ::__construct ($ message , 0 , $ previous );
36+
37+ $ this ->hasFatalViolations = $ this ->getFatalViolations () !== [];
38+ }
39+
40+ /**
41+ * @return \ArrayIterator<int, Violation>
42+ */
43+ public function getIterator (): \ArrayIterator
44+ {
45+ return new \ArrayIterator ($ this ->violations );
46+ }
47+
48+ /**
49+ * @return int<1, max>
50+ */
51+ public function count (): int
52+ {
53+ return \count ($ this ->violations );
54+ }
55+
56+ /**
57+ * Returns the violations caused by an {@see \Error}, in order of
58+ * appearance.
59+ *
60+ * @return list<Violation>
61+ */
62+ public function getFatalViolations (): array
63+ {
64+ $ result = [];
65+
66+ foreach ($ this ->violations as $ violation ) {
67+ if ($ violation ->isFatal ) {
68+ $ result [] = $ violation ;
69+ }
70+ }
71+
72+ return $ result ;
73+ }
74+
75+ /**
76+ * Returns the errors of the fatal violations by their violations.
77+ *
78+ * @return iterable<Violation, \Error>
79+ */
80+ public function getFatalErrors (): iterable
81+ {
82+ foreach ($ this ->violations as $ violation ) {
83+ if ($ violation ->cause instanceof \Error) {
84+ yield $ violation => $ violation ->cause ;
85+ }
86+ }
87+ }
88+
89+ /**
90+ * Returns the causes of the violations that have one, in order of
91+ * appearance.
92+ *
93+ * @return list<\Throwable>
94+ */
95+ public function getCauses (): array
96+ {
97+ $ result = [];
98+
99+ foreach ($ this ->violations as $ violation ) {
100+ if ($ violation ->cause !== null ) {
101+ $ result [] = $ violation ->cause ;
102+ }
103+ }
104+
105+ return $ result ;
27106 }
28107
29108 /**
0 commit comments