Skip to content

Commit 056ede8

Browse files
committed
Actualize docs
1 parent 9f813b7 commit 056ede8

316 files changed

Lines changed: 11882 additions & 4347 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎libs/component/diagnostics/src/Exception/ViolationException.php‎

Lines changed: 81 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,19 @@
99
use 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
/**
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypeLang\Mapper\Diagnostics\Printer\Name;
6+
7+
/**
8+
* Makes a name that comes from the input data safe to be a part of a message:
9+
* the name is cut to a limited length and the result is valid UTF-8.
10+
*
11+
* A name that is not valid UTF-8 is treated as bytes as a whole.
12+
*
13+
* Use {@see limit()} first, then escape the quotes of the target format, then
14+
* {@see escapeInvalidBytes()}.
15+
*
16+
* @internal this is an internal library class, please do not use it in your code
17+
* @psalm-internal TypeLang\Mapper
18+
*/
19+
final class NameSanitizer
20+
{
21+
private const MAX_LENGTH = 64;
22+
23+
private const CUT_MARK = '...';
24+
25+
/**
26+
* Cuts the name to {@see MAX_LENGTH} characters, or to {@see MAX_LENGTH}
27+
* bytes when the name is not valid UTF-8.
28+
*/
29+
public static function limit(string $name): string
30+
{
31+
if (\strlen($name) <= self::MAX_LENGTH) {
32+
return $name;
33+
}
34+
35+
if (\preg_match('//u', $name) !== 1) {
36+
return \substr($name, 0, self::MAX_LENGTH) . self::CUT_MARK;
37+
}
38+
39+
if (\preg_match('/^.{' . self::MAX_LENGTH . '}(?=.)/us', $name, $matches) !== 1) {
40+
return $name;
41+
}
42+
43+
return $matches[0] . self::CUT_MARK;
44+
}
45+
46+
/**
47+
* Replaces every non-ASCII byte of a name that is not valid UTF-8 with
48+
* its hexadecimal escape: `\xFF`.
49+
*/
50+
public static function escapeInvalidBytes(string $name): string
51+
{
52+
if (\preg_match('//u', $name) === 1) {
53+
return $name;
54+
}
55+
56+
return (string) \preg_replace_callback(
57+
pattern: '/[\x80-\xFF]/',
58+
callback: static fn(array $byte): string => \sprintf('\\x%02X', \ord($byte[0])),
59+
subject: $name,
60+
);
61+
}
62+
}

‎libs/component/diagnostics/src/Printer/Path/JsonPathPrinter.php‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,18 @@
88
use TypeLang\Mapper\Diagnostics\Path\Segment\KeySegment;
99
use TypeLang\Mapper\Diagnostics\Path\Segment\PropertySegment;
1010
use TypeLang\Mapper\Diagnostics\Path\Segment\SegmentInterface;
11+
use TypeLang\Mapper\Diagnostics\Printer\Name\NameSanitizer;
1112

1213
/**
1314
* Prints a path as JSONPath: `$.items[3].name`, `$['a b']`.
1415
*
16+
* A name of a segment is cut to 64 characters and ends with `...` inside the
17+
* quotes: `$['aaaa...']`, such a path is not exact. Bytes that are not valid
18+
* UTF-8 are printed as `\xFF`, the result is always valid UTF-8.
19+
*
20+
* The path follows JSONPath except for the escapes of invalid bytes and the
21+
* cut names.
22+
*
1523
* @link https://www.rfc-editor.org/rfc/rfc9535
1624
*/
1725
final class JsonPathPrinter implements PathPrinterInterface
@@ -68,6 +76,8 @@ private static function printKey(int|string $key): string
6876
*/
6977
private static function printName(string $name): string
7078
{
79+
$name = NameSanitizer::limit($name);
80+
7181
if (\preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/D', $name) === 1) {
7282
return '.' . $name;
7383
}
@@ -79,10 +89,12 @@ private static function escape(string $name): string
7989
{
8090
$escaped = \strtr($name, self::ESCAPES);
8191

82-
return (string) \preg_replace_callback(
92+
$escaped = (string) \preg_replace_callback(
8393
pattern: '/[\x00-\x1f]/',
8494
callback: static fn(array $char): string => \sprintf('\u%04x', \ord($char[0])),
8595
subject: $escaped,
8696
);
97+
98+
return NameSanitizer::escapeInvalidBytes($escaped);
8799
}
88100
}

‎libs/component/diagnostics/src/Violation.php‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,13 @@
1212
*/
1313
final class Violation
1414
{
15+
/**
16+
* Whether the cause is an {@see \Error}: a defect of the code or of its
17+
* declarations, such as a call of a method that does not exist in a
18+
* setter, rather than of the input
19+
*/
20+
public readonly bool $isFatal;
21+
1522
public function __construct(
1623
public readonly ViolationCodeInterface $code,
1724
/**
@@ -50,7 +57,9 @@ public function __construct(
5057
* of a hook of a class. Its message is not a part of the violation.
5158
*/
5259
public readonly ?\Throwable $cause = null,
53-
) {}
60+
) {
61+
$this->isFatal = $cause instanceof \Error;
62+
}
5463

5564
/**
5665
* @param non-empty-string $template

‎libs/component/diagnostics/src/ViolationCode.php‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,26 @@ enum ViolationCode: string implements TypedViolationCodeInterface
4949
*/
5050
case InvalidValue = 'invalid_value';
5151

52+
/**
53+
* Value of an object cannot be read on normalization, such as an
54+
* uninitialized property or a getter that throws. The error is the cause
55+
* of the violation, the violation has no value.
56+
*/
57+
case UnreadableValue = 'unreadable_value';
58+
59+
/**
60+
* Value is nested deeper than the limit of the configuration, such as
61+
* an object that refers to itself. The path points to the object.
62+
*/
63+
case DepthExceeded = 'depth_exceeded';
64+
65+
/**
66+
* Object of a class of a discriminated hierarchy has no tag: neither
67+
* its class nor a parent of it is in the map. The path points to the
68+
* object.
69+
*/
70+
case UntaggedObject = 'untagged_object';
71+
5272
public function getCode(): string
5373
{
5474
return $this->value;
@@ -64,6 +84,9 @@ public function getTemplate(): string
6484
self::DuplicateField => 'Field "{{field}}" duplicates the field "{{other}}"',
6585
self::FailedCheck => 'Value must be of type {{expected}} ({{check}})',
6686
self::InvalidValue => 'Value {{value}} is rejected',
87+
self::UnreadableValue => 'Value cannot be read',
88+
self::DepthExceeded => 'Nesting depth exceeds the limit of {{limit}}',
89+
self::UntaggedObject => 'Class "{{class}}" has no tag in the discriminator map of "{{base}}"',
6790
};
6891
}
6992

‎libs/component/diagnostics/tests/Exception/ViolationExceptionTest.php‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,4 +84,62 @@ public function print(Path $path): string
8484

8585
self::assertSame('custom: Value "a" is rejected', $exception->getMessage());
8686
}
87+
88+
public function testViolationsAreIteratedAndCounted(): void
89+
{
90+
$violations = [
91+
new Violation(ViolationCode::MissingField, ['field' => 'id'], new Path([new KeySegment('id')])),
92+
new Violation(ViolationCode::InvalidValue, [], new Path([new KeySegment('age')]), 'x'),
93+
];
94+
95+
$exception = self::createException($violations);
96+
97+
self::assertCount(2, $exception);
98+
self::assertSame($violations, \iterator_to_array($exception));
99+
}
100+
101+
public function testViolationsCausedByErrorsAreFatal(): void
102+
{
103+
$error = new \DivisionByZeroError('Division by zero');
104+
$exception = new \InvalidArgumentException('rejected');
105+
$fatal = new Violation(ViolationCode::InvalidValue, [], new Path([new KeySegment('a')]), 1, cause: $error);
106+
$rejected = new Violation(
107+
ViolationCode::InvalidValue,
108+
[],
109+
new Path([new KeySegment('b')]),
110+
2,
111+
cause: $exception,
112+
);
113+
$missing = new Violation(ViolationCode::MissingField, ['field' => 'c'], new Path([new KeySegment('c')]));
114+
115+
$all = self::createException([$missing, $rejected, $fatal]);
116+
117+
self::assertTrue($fatal->isFatal);
118+
self::assertFalse($rejected->isFatal);
119+
self::assertTrue($all->hasFatalViolations);
120+
self::assertSame([$fatal], $all->getFatalViolations());
121+
self::assertSame([$exception, $error], $all->getCauses());
122+
123+
$errors = [];
124+
125+
foreach ($all->getFatalErrors() as $violation => $cause) {
126+
$errors[] = [$violation, $cause];
127+
}
128+
129+
self::assertSame([[$fatal, $error]], $errors);
130+
131+
self::assertFalse(self::createException([$missing, $rejected])->hasFatalViolations);
132+
}
133+
134+
/**
135+
* @param non-empty-list<Violation> $violations
136+
*/
137+
private static function createException(array $violations): InvalidInputStubException
138+
{
139+
return InvalidInputStubException::becauseInputIsInvalid(
140+
$violations,
141+
self::createFormatter(),
142+
new JsonPathPrinter(),
143+
);
144+
}
87145
}

0 commit comments

Comments
 (0)