diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index 62437a3..ae67929 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -275,7 +275,7 @@ public static function validateCollectionElementMutation( return $registry->validate($value, $valueType, $context); } - } elseif (isset(self::ARRAY_TYPES[$base]) || $base === 'non-empty-array') { + } else { $genericCount = \count($typeNode->genericTypes); if ($genericCount >= 2 && $key !== null) { diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index 25a9b5c..cd017b3 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -53,7 +53,14 @@ public static function check( ?string $caller = null, mixed $thisOrClass = null ): mixed { - if (Config::isArrayValidationHybrid() && ! str_contains($typeString, '{') && \count($chain) === 1 && $chain[0][0] === 'dim') { + $isObjectDimAccess = \is_object($root) && ($chain[0][0] ?? null) === 'dim'; + + if ( + (Config::isArrayValidationHybrid() || $isObjectDimAccess) + && ! str_contains($typeString, '{') + && \count($chain) === 1 + && $chain[0][0] === 'dim' + ) { $directErr = InlineChecker::validateCollectionElementMutation( $value, $chain, @@ -72,6 +79,10 @@ public static function check( return $value; } + if ($isObjectDimAccess) { + return $value; + } + $copy = StructureMutator::mutateCopy($root, $chain, $value); $res = InlineChecker::checkVariable( @@ -115,11 +126,13 @@ public static function checkProperty( } $currentVal = self::readPropertyValue($objectOrClass, $className, $propName); + $isObjectDimAccess = \is_object($currentVal) && ($chain[0][0] ?? null) === 'dim'; if ( - Config::isArrayValidationHybrid() - && \is_array($currentVal) - && \count($currentVal) > Config::HYBRID_SAMPLE_THRESHOLD + ( + (Config::isArrayValidationHybrid() && \is_array($currentVal) && \count($currentVal) > Config::HYBRID_SAMPLE_THRESHOLD) + || $isObjectDimAccess + ) && \count($chain) === 1 && $chain[0][0] === 'dim' ) { @@ -140,6 +153,10 @@ public static function checkProperty( return $value; } + if ($isObjectDimAccess) { + return $value; + } + $copy = StructureMutator::mutateCopy($currentVal, $chain, $value); $res = InlineChecker::checkProperty($copy, $objectOrClass, $propName, $file, $registry); @@ -152,7 +169,7 @@ public static function checkProperty( } /** - * Directly validates a single element appended/assigned to a large property array in O(1). + * Directly validates a single element appended/assigned to a large property array or generic ArrayAccess object in O(1). * * @param list $chain */ @@ -199,7 +216,7 @@ private static function validatePropertyElementMutation( return $registry->validate($value, $valueType, $context); } - } elseif (\in_array($base, ['array', 'non-empty-array', 'iterable'], true)) { + } else { $genericCount = \count($typeNode->genericTypes); if ($genericCount >= 2 && $key !== null) { diff --git a/tests/TypeChecking/Generics/ArrayAccessGenericDimensionAssignmentTest.php b/tests/TypeChecking/Generics/ArrayAccessGenericDimensionAssignmentTest.php new file mode 100644 index 0000000..ba2328b --- /dev/null +++ b/tests/TypeChecking/Generics/ArrayAccessGenericDimensionAssignmentTest.php @@ -0,0 +1,290 @@ + + * + * @template T + * + * @implements ArrayAccess + */ +class ReproGenericCollection implements ArrayAccess, Countable +{ + /** + * @var array + */ + private array $items = []; + + /** + * @param string $collectionType + * @param array $data + */ + public function __construct( + private readonly string $collectionType = 'mixed', + array $data = [] + ) { + $this->items = $data; + } + + /** + * @param T $element + */ + public function add(mixed $element): bool + { + $this[] = $element; + + return true; + } + + public function offsetExists(mixed $offset): bool + { + return isset($this->items[$offset]); + } + + /** + * @return T|null + */ + public function offsetGet(mixed $offset): mixed + { + return $this->items[$offset] ?? null; + } + + /** + * @param array-key|null $offset + * @param T $value + */ + public function offsetSet(mixed $offset, mixed $value): void + { + if ($offset === null) { + $this->items[] = $value; + } else { + $this->items[$offset] = $value; + } + } + + public function offsetUnset(mixed $offset): void + { + unset($this->items[$offset]); + } + + public function count(): int + { + return \count($this->items); + } +} + +/** + * Simulates Ramsey\Collection\Map\TypedMap + * + * @template K of array-key + * @template T + * + * @implements ArrayAccess + */ +class ReproGenericTypedMap implements ArrayAccess, Countable +{ + /** + * @var array + */ + private array $items = []; + + public function __construct( + private readonly string $keyType = 'string', + private readonly string $valueType = 'mixed' + ) { + } + + /** + * @param K $key + * @param T $value + */ + public function put(mixed $key, mixed $value): void + { + $this[$key] = $value; + } + + public function offsetExists(mixed $offset): bool + { + return isset($this->items[$offset]); + } + + /** + * @param K $offset + * + * @return T|null + */ + public function offsetGet(mixed $offset): mixed + { + return $this->items[$offset] ?? null; + } + + /** + * @param K|null $offset + * @param T $value + */ + public function offsetSet(mixed $offset, mixed $value): void + { + if ($offset === null) { + $this->items[] = $value; + } else { + $this->items[$offset] = $value; + } + } + + public function offsetUnset(mixed $offset): void + { + unset($this->items[$offset]); + } + + public function count(): int + { + return \count($this->items); + } +} + +class ReproPropertyCollectionHolder +{ + /** + * @var ReproGenericCollection + */ + public ReproGenericCollection $dogs; + + /** + * @var ReproGenericTypedMap + */ + public ReproGenericTypedMap $scores; + + public function __construct() + { + $this->dogs = new ReproGenericCollection(Dog::class); + $this->scores = new ReproGenericTypedMap('string', 'int'); + } +} + +describe('Generic ArrayAccess Dimension Assignment ($collection[] = $val & $map[$k] = $val)', function () { + beforeEach(function () { + Config::set(['array_validation' => 'full']); + }); + + afterEach(function () { + Config::reset(); + }); + + describe('1. Single-Template Generic Collection (Ramsey Collection Reproduction)', function () { + test('enforces generic type T on add() and array append $dogs[] = ... in full validation mode', function () { + /** @var ReproGenericCollection $dogs */ + $dogs = new ReproGenericCollection(Dog::class); + + $dogs->add(new Dog()); + $dogs[] = new Dog(); + + expect($dogs->count())->toBe(2) + ->and(TypePHP::getGenericType($dogs))->toBe(Dog::class) + ; + + expect(function () use ($dogs) { + $dogs[] = new Car(); + })->toThrow(TypeError::class, Dog::class); + }); + + test('enforces positive-int, array shapes, and unions on Collection with $collection[] = ...', function () { + /** @var ReproGenericCollection $scores */ + $scores = new ReproGenericCollection('int'); + $scores->add(100); + $scores[] = 200; + + expect($scores->count())->toBe(2); + + expect(function () use ($scores) { + $scores[] = -50; + })->toThrow(TypeError::class, 'positive-int'); + + /** @var ReproGenericCollection $pets */ + $pets = new ReproGenericCollection('object'); + $pets[] = new Dog(); + $pets[] = new Cat(); + + expect($pets->count())->toBe(2); + + expect(function () use ($pets) { + $pets[] = new Car(); + })->toThrow(TypeError::class); + }); + }); + + describe('2. Two-Template Generic TypedMap (Ramsey TypedMap Reproduction)', function () { + test('enforces both Key (K) and Value (T) generics on put() and $map[$k] = ... in full validation mode', function () { + /** @var ReproGenericTypedMap $map */ + $map = new ReproGenericTypedMap('string', Dog::class); + + $map->put('primary', new Dog()); + $map['secondary'] = new Dog(); + + expect($map->count())->toBe(2) + ->and(TypePHP::getGenericType($map, 'K'))->toBe('string') + ->and(TypePHP::getGenericType($map, 'T'))->toBe(Dog::class) + ; + + expect(function () use ($map) { + $map['tertiary'] = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect(function () use ($map) { + $map[123] = new Dog(); + })->toThrow(TypeError::class, 'key must be of type string'); + }); + + test('enforces generic key and value on native SPL ArrayObject dimension assignments', function () { + /** @var ArrayObject $ao */ + $ao = new ArrayObject(); + + $ao['alpha'] = 10; + expect($ao['alpha'])->toBe(10); + + expect(function () use ($ao) { + $ao[''] = 20; + })->toThrow(TypeError::class, 'key must be of type non-empty-string'); + + expect(function () use ($ao) { + $ao['beta'] = -5; + })->toThrow(TypeError::class, 'positive-int'); + }); + }); + + describe('3. Class Properties Holding Generic ArrayAccess Objects ($this->dogs[] = ...)', function () { + test('validates dimension assignments on object properties without converting property to array', function () { + $holder = new ReproPropertyCollectionHolder(); + + $holder->dogs[] = new Dog(); + expect($holder->dogs->count())->toBe(1); + + expect(function () use ($holder) { + $holder->dogs[] = new Car(); + })->toThrow(TypeError::class, Dog::class); + + $holder->scores['first'] = 100; + expect($holder->scores->count())->toBe(1); + + expect(function () use ($holder) { + $holder->scores[''] = 100; + })->toThrow(TypeError::class, 'key must be of type non-empty-string'); + + expect(function () use ($holder) { + $holder->scores['second'] = -10; + })->toThrow(TypeError::class, 'positive-int'); + }); + }); +});