Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Serializing a value that its protobuf type cannot represent now throws `Exception\ValueOutOfRange` instead of
wrapping it or writing a broken varint: `int32`/`sint32`/`sfixed32`/enum outside [-2^31, 2^31-1] (e.g.
`int32Of(2 ** 31)` used to wrap to a negative number), `uint32`/`fixed32` outside [0, 2^32-1], and
`uint64`/`fixed64` that are negative, above 2^64-1 or fractional.
`uint64`/`fixed64` that are negative, above 2^64-1 or fractional. The exception names the field numbers that
lead to the value (`$fields`, e.g. `field 3.1`) and, when encoding an object, the class properties
(`$properties`, e.g. `Order::$items → Item::$quantity`).
- `enumT()`, `enumOf()`, `Type\EnumT` and `Reflection\EnumT` accept only int-backed PHP enums and throw
`Exception\InvalidSchema` for any other class when the type is declared. A string-backed enum used to fail
with `\InvalidArgumentException` only when a value was serialized.
Expand Down
11 changes: 8 additions & 3 deletions src/Encoder/Internal/ReflectionEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Thesis\Protobuf\Encoder\Internal;

use Thesis\Protobuf\Encoder;
use Thesis\Protobuf\Exception\ValueOutOfRange;
use Thesis\Protobuf\Reflection\Reflector;
use Thesis\Protobuf\Serializer;

Expand All @@ -21,8 +22,12 @@ public function __construct(
#[\Override]
public function encode(object $message): string
{
return $this->serializer->serialize(
$this->reflector->message($message),
);
try {
return $this->serializer->serialize(
$this->reflector->message($message),
);
} catch (ValueOutOfRange $e) {
throw $e->withProperties($this->reflector->propertyPath($message::class, $e->fields));
}
}
}
59 changes: 57 additions & 2 deletions src/Exception/ValueOutOfRange.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,70 @@
*/
final class ValueOutOfRange extends ProtobufException
{
/**
* Numbers of the fields that lead to the value, from the outermost message. A map entry adds 1 for its key
* or 2 for its value; a repeated field adds nothing for the element index. Empty when the value was
* serialized outside of a message.
*
* @var list<positive-int>
*/
public private(set) array $fields = [];

/**
* The same path as "Class::$property" names when the message was encoded from an object.
*
* @var list<non-empty-string>
*/
public private(set) array $properties = [];

/**
* @param non-empty-string $type protobuf type name, e.g. "int32"
* @param non-empty-string $range the values the type accepts, e.g. "[0, 4294967295]"
*/
public function __construct(
public readonly string $type,
public readonly int|Number $value,
string $range,
private readonly string $range,
) {
parent::__construct(\sprintf('Value %s is out of range for %s: expected an integer in %s.', $value, $type, $range));
parent::__construct($this->describe());
}

/**
* @internal
* @param positive-int $num the field containing the location known so far
*/
public function inField(int $num): self
{
array_unshift($this->fields, $num);
$this->message = $this->describe();

return $this;
}

/**
* @internal
* @param list<non-empty-string> $properties
*/
public function withProperties(array $properties): self
{
$this->properties = $properties;
$this->message = $this->describe();

return $this;
}

private function describe(): string
{
$location = '';

if ($this->fields !== []) {
$location .= ' in field ' . implode('.', $this->fields);
}

if ($this->properties !== []) {
$location .= ' (' . implode(' → ', $this->properties) . ')';
}

return \sprintf('Value %s is out of range for %s%s: expected an integer in %s.', $this->value, $this->type, $location, $this->range);
}
}
8 changes: 6 additions & 2 deletions src/Internal/Serde/SerializeMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Thesis\Protobuf\Internal\Serde;

use Thesis\Protobuf\Exception\ValueOutOfRange;
use Thesis\Protobuf\FieldDescriptor;
use Thesis\Protobuf\Internal\Buffer;
use Thesis\Protobuf\Internal\Buffer\ByteBuffer;
Expand Down Expand Up @@ -35,8 +36,11 @@ public function serialize(WriteBuffer $buffer, mixed $value): void
$type->accept(DetermineWireType::Visitor),
);

$serializer = $type->accept(new TypeSerializerVisitor($tag));
$serializer->serialize($tmp, $field->value->value);
try {
$type->accept(new TypeSerializerVisitor($tag))->serialize($tmp, $field->value->value);
} catch (ValueOutOfRange $e) {
throw $e->inField($field->num);
}
}

Buffer\copy($tmp, $buffer);
Expand Down
76 changes: 76 additions & 0 deletions src/Reflection/Reflector.php
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,82 @@ public function map(Message $message, string $class): object
return $object;
}

/**
* Translates a path of field numbers (see Exception\ValueOutOfRange::$fields) into "Class::$property"
* names, starting from the class of the encoded object. Stops where the path leaves the known classes.
*
* @internal
* @param class-string $class
* @param list<positive-int> $fields
* @return list<non-empty-string>
*/
public function propertyPath(string $class, array $fields): array
{
$path = [];
$i = 0;

while (($num = $fields[$i] ?? null) !== null) {
$field = null;

foreach ($this->classReflector->reflect($class)->properties as $property) {
$name = $property->reflection->getName();

if ($property->attributes->has(Field::class)) {
if ($property->attributes->get(Field::class)->num === $num) {
$field = $property->attributes->get(Field::class);

break;
}
} elseif ($property->attributes->has(OneOf::class)) {
foreach ($property->attributes->get(OneOf::class)->variants as $variant) {
if (isset($this->type($variant)->fields[$num])) {
// The variant's own properties carry the field: look it up there.
$path[] = "{$class}::\${$name}";
$class = $variant;

continue 3;
}
}
}
}

if ($field === null) {
break;
}

$segment = "{$class}::\${$name}";
++$i;

$type = $field->type;

while ($type instanceof ListT) {
$type = $type->element;
}

if ($type instanceof MapT) {
$entry = $fields[$i++] ?? null;

if ($entry === 1) {
$segment .= '[key]';
$type = $type->keyT;
} elseif ($entry === 2) {
$segment .= '[value]';
$type = $type->valueT;
}
}

$path[] = $segment;

if (!$type instanceof ObjectT) {
break;
}

$class = $type->class;
}

return $path;
}

/**
* @param ?\Closure(Field, mixed): bool $presence
*/
Expand Down
18 changes: 11 additions & 7 deletions src/Serializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,17 @@ public function serialize(Message $message): string
foreach ($message->fields as $field) {
$type = $field->value->type;

$type
->accept(
new TypeSerializerVisitor(
new Tag($field->num, $type->accept(DetermineWireType::Visitor)),
),
)
->serialize($buffer, $field->value->value);
try {
$type
->accept(
new TypeSerializerVisitor(
new Tag($field->num, $type->accept(DetermineWireType::Visitor)),
),
)
->serialize($buffer, $field->value->value);
} catch (Exception\ValueOutOfRange $e) {
throw $e->inField($field->num);
}
}

return $buffer->flush();
Expand Down
135 changes: 135 additions & 0 deletions tests/ValueOutOfRangeLocationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
<?php

declare(strict_types=1);

namespace Thesis\Protobuf;

use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Thesis\Protobuf\Encoder\Internal\ReflectionEncoder;
use Thesis\Protobuf\Exception\ValueOutOfRange;
use Thesis\Protobuf\Internal\Serde\SerializeMessage;
use Thesis\Protobuf\Reflection\Reflector;

#[CoversClass(ValueOutOfRange::class)]
#[CoversClass(Serializer::class)]
#[CoversClass(SerializeMessage::class)]
#[CoversClass(ReflectionEncoder::class)]
#[CoversClass(Reflector::class)]
final class ValueOutOfRangeLocationTest extends TestCase
{
/**
* @param list<positive-int> $fields
*/
#[DataProvider('provideSerializerNamesTheFieldCases')]
public function testSerializerNamesTheField(Message $message, array $fields, string $location): void
{
try {
new Serializer()->serialize($message);
self::fail('Serialization must fail.');
} catch (ValueOutOfRange $e) {
self::assertSame($fields, $e->fields);
self::assertSame([], $e->properties);
self::assertStringContainsString("for uint32 in field {$location}: expected", $e->getMessage());
}
}

/**
* @return iterable<string, array{Message, list<positive-int>, string}>
*/
public static function provideSerializerNamesTheFieldCases(): iterable
{
yield 'top-level field' => [message(fieldOf(3, uint32Of(-5))), [3], '3'];
yield 'nested message' => [message(fieldOf(3, messageOf(fieldOf(1, uint32Of(-5))))), [3, 1], '3.1'];
yield 'list element' => [message(fieldOf(4, listOf(uint32T, [1, -5]))), [4], '4'];
yield 'map key' => [message(fieldOf(5, mapOf(uint32T, stringT, Map::fromArray([-5 => 'a'])))), [5, 1], '5.1'];
yield 'map value' => [message(fieldOf(5, mapOf(stringT, uint32T, Map::fromArray(['a' => -5])))), [5, 2], '5.2'];
}

/**
* @param list<positive-int> $fields
* @param list<non-empty-string> $properties
*/
#[DataProvider('provideEncoderNamesTheClassAndPropertyCases')]
public function testEncoderNamesTheClassAndProperty(object $message, array $fields, array $properties): void
{
try {
Encoder\Builder::buildDefault()->encode($message);
self::fail('Encoding must fail.');
} catch (ValueOutOfRange $e) {
self::assertSame($fields, $e->fields);
self::assertSame($properties, $e->properties);
self::assertStringContainsString(\sprintf('(%s)', implode(' → ', $properties)), $e->getMessage());
}
}

/**
* @return iterable<string, array{object, list<positive-int>, list<non-empty-string>}>
*/
public static function provideEncoderNamesTheClassAndPropertyCases(): iterable
{
$outer = LocationTestOuter::class;
$inner = LocationTestInner::class;

yield 'scalar' => [new LocationTestInner(-5), [1], ["{$inner}::\$id"]];
yield 'nested object' => [new LocationTestOuter(inner: new LocationTestInner(-5)), [3, 1], ["{$outer}::\$inner", "{$inner}::\$id"]];
yield 'list of objects' => [
new LocationTestOuter(items: [new LocationTestInner(1), new LocationTestInner(-5)]),
[4, 1],
["{$outer}::\$items", "{$inner}::\$id"],
];
yield 'map value object' => [
new LocationTestOuter(byName: Map::fromArray(['a' => new LocationTestInner(-5)])),
[5, 2, 1],
["{$outer}::\$byName[value]", "{$inner}::\$id"],
];
yield 'map key' => [
new LocationTestOuter(byId: Map::fromArray([-5 => 'a'])),
[6, 1],
["{$outer}::\$byId[key]"],
];
yield 'oneof variant' => [
new LocationTestOuter(choice: new LocationTestVariant(-5)),
[7],
["{$outer}::\$choice", LocationTestVariant::class . '::$count'],
];
}
}

final readonly class LocationTestInner
{
public function __construct(
#[Reflection\Field(1, Reflection\Uint32T::T)]
public int $id = 0,
) {}
}

final readonly class LocationTestVariant
{
public function __construct(
#[Reflection\Field(7, Reflection\Uint32T::T)]
public int $count = 0,
) {}
}

final readonly class LocationTestOuter
{
/**
* @param list<LocationTestInner> $items
* @param Map<string, LocationTestInner> $byName
* @param Map<int, string> $byId
*/
public function __construct(
#[Reflection\Field(3, new Reflection\ObjectT(LocationTestInner::class))]
public ?LocationTestInner $inner = null,
#[Reflection\Field(4, new Reflection\ListT(new Reflection\ObjectT(LocationTestInner::class)))]
public array $items = [],
#[Reflection\Field(5, new Reflection\MapT(Reflection\StringT::T, new Reflection\ObjectT(LocationTestInner::class)))]
public Map $byName = new Map(),
#[Reflection\Field(6, new Reflection\MapT(Reflection\Uint32T::T, Reflection\StringT::T))]
public Map $byId = new Map(),
#[Reflection\OneOf([LocationTestVariant::class])]
public ?LocationTestVariant $choice = null,
) {}
}
Loading