Skip to content

Commit 77920b2

Browse files
authored
Refactor InlineChecker and MemberAssignChecker for improved type validation and add tests for generic ArrayAccess dimension assignments (#126)
1 parent 879291a commit 77920b2

3 files changed

Lines changed: 314 additions & 7 deletions

File tree

‎src/Internal/Checker/InlineChecker.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ public static function validateCollectionElementMutation(
275275

276276
return $registry->validate($value, $valueType, $context);
277277
}
278-
} elseif (isset(self::ARRAY_TYPES[$base]) || $base === 'non-empty-array') {
278+
} else {
279279
$genericCount = \count($typeNode->genericTypes);
280280

281281
if ($genericCount >= 2 && $key !== null) {

‎src/Internal/Checker/MemberAssignChecker.php‎

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,14 @@ public static function check(
5353
?string $caller = null,
5454
mixed $thisOrClass = null
5555
): mixed {
56-
if (Config::isArrayValidationHybrid() && ! str_contains($typeString, '{') && \count($chain) === 1 && $chain[0][0] === 'dim') {
56+
$isObjectDimAccess = \is_object($root) && ($chain[0][0] ?? null) === 'dim';
57+
58+
if (
59+
(Config::isArrayValidationHybrid() || $isObjectDimAccess)
60+
&& ! str_contains($typeString, '{')
61+
&& \count($chain) === 1
62+
&& $chain[0][0] === 'dim'
63+
) {
5764
$directErr = InlineChecker::validateCollectionElementMutation(
5865
$value,
5966
$chain,
@@ -72,6 +79,10 @@ public static function check(
7279
return $value;
7380
}
7481

82+
if ($isObjectDimAccess) {
83+
return $value;
84+
}
85+
7586
$copy = StructureMutator::mutateCopy($root, $chain, $value);
7687

7788
$res = InlineChecker::checkVariable(
@@ -115,11 +126,13 @@ public static function checkProperty(
115126
}
116127

117128
$currentVal = self::readPropertyValue($objectOrClass, $className, $propName);
129+
$isObjectDimAccess = \is_object($currentVal) && ($chain[0][0] ?? null) === 'dim';
118130

119131
if (
120-
Config::isArrayValidationHybrid()
121-
&& \is_array($currentVal)
122-
&& \count($currentVal) > Config::HYBRID_SAMPLE_THRESHOLD
132+
(
133+
(Config::isArrayValidationHybrid() && \is_array($currentVal) && \count($currentVal) > Config::HYBRID_SAMPLE_THRESHOLD)
134+
|| $isObjectDimAccess
135+
)
123136
&& \count($chain) === 1
124137
&& $chain[0][0] === 'dim'
125138
) {
@@ -140,6 +153,10 @@ public static function checkProperty(
140153
return $value;
141154
}
142155

156+
if ($isObjectDimAccess) {
157+
return $value;
158+
}
159+
143160
$copy = StructureMutator::mutateCopy($currentVal, $chain, $value);
144161

145162
$res = InlineChecker::checkProperty($copy, $objectOrClass, $propName, $file, $registry);
@@ -152,7 +169,7 @@ public static function checkProperty(
152169
}
153170

154171
/**
155-
* Directly validates a single element appended/assigned to a large property array in O(1).
172+
* Directly validates a single element appended/assigned to a large property array or generic ArrayAccess object in O(1).
156173
*
157174
* @param list<array{0: 'dim'|'prop', 1: mixed}> $chain
158175
*/
@@ -199,7 +216,7 @@ private static function validatePropertyElementMutation(
199216

200217
return $registry->validate($value, $valueType, $context);
201218
}
202-
} elseif (\in_array($base, ['array', 'non-empty-array', 'iterable'], true)) {
219+
} else {
203220
$genericCount = \count($typeNode->genericTypes);
204221

205222
if ($genericCount >= 2 && $key !== null) {
Lines changed: 290 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,290 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypePHP\Tests\TypeChecking\Generics;
6+
7+
use ArrayAccess;
8+
use ArrayObject;
9+
use Countable;
10+
use TypePHP\Exception\TypeError;
11+
use TypePHP\Internal\Util\Config;
12+
use TypePHP\Tests\Fixtures\Domain\Car;
13+
use TypePHP\Tests\Fixtures\Domain\Cat;
14+
use TypePHP\Tests\Fixtures\Domain\Dog;
15+
use TypePHP\TypePHP;
16+
17+
/**
18+
* Simulates Ramsey\Collection\Collection<T>
19+
*
20+
* @template T
21+
*
22+
* @implements ArrayAccess<array-key, T>
23+
*/
24+
class ReproGenericCollection implements ArrayAccess, Countable
25+
{
26+
/**
27+
* @var array<array-key, T>
28+
*/
29+
private array $items = [];
30+
31+
/**
32+
* @param string $collectionType
33+
* @param array<array-key, T> $data
34+
*/
35+
public function __construct(
36+
private readonly string $collectionType = 'mixed',
37+
array $data = []
38+
) {
39+
$this->items = $data;
40+
}
41+
42+
/**
43+
* @param T $element
44+
*/
45+
public function add(mixed $element): bool
46+
{
47+
$this[] = $element;
48+
49+
return true;
50+
}
51+
52+
public function offsetExists(mixed $offset): bool
53+
{
54+
return isset($this->items[$offset]);
55+
}
56+
57+
/**
58+
* @return T|null
59+
*/
60+
public function offsetGet(mixed $offset): mixed
61+
{
62+
return $this->items[$offset] ?? null;
63+
}
64+
65+
/**
66+
* @param array-key|null $offset
67+
* @param T $value
68+
*/
69+
public function offsetSet(mixed $offset, mixed $value): void
70+
{
71+
if ($offset === null) {
72+
$this->items[] = $value;
73+
} else {
74+
$this->items[$offset] = $value;
75+
}
76+
}
77+
78+
public function offsetUnset(mixed $offset): void
79+
{
80+
unset($this->items[$offset]);
81+
}
82+
83+
public function count(): int
84+
{
85+
return \count($this->items);
86+
}
87+
}
88+
89+
/**
90+
* Simulates Ramsey\Collection\Map\TypedMap<K, T>
91+
*
92+
* @template K of array-key
93+
* @template T
94+
*
95+
* @implements ArrayAccess<K, T>
96+
*/
97+
class ReproGenericTypedMap implements ArrayAccess, Countable
98+
{
99+
/**
100+
* @var array<K, T>
101+
*/
102+
private array $items = [];
103+
104+
public function __construct(
105+
private readonly string $keyType = 'string',
106+
private readonly string $valueType = 'mixed'
107+
) {
108+
}
109+
110+
/**
111+
* @param K $key
112+
* @param T $value
113+
*/
114+
public function put(mixed $key, mixed $value): void
115+
{
116+
$this[$key] = $value;
117+
}
118+
119+
public function offsetExists(mixed $offset): bool
120+
{
121+
return isset($this->items[$offset]);
122+
}
123+
124+
/**
125+
* @param K $offset
126+
*
127+
* @return T|null
128+
*/
129+
public function offsetGet(mixed $offset): mixed
130+
{
131+
return $this->items[$offset] ?? null;
132+
}
133+
134+
/**
135+
* @param K|null $offset
136+
* @param T $value
137+
*/
138+
public function offsetSet(mixed $offset, mixed $value): void
139+
{
140+
if ($offset === null) {
141+
$this->items[] = $value;
142+
} else {
143+
$this->items[$offset] = $value;
144+
}
145+
}
146+
147+
public function offsetUnset(mixed $offset): void
148+
{
149+
unset($this->items[$offset]);
150+
}
151+
152+
public function count(): int
153+
{
154+
return \count($this->items);
155+
}
156+
}
157+
158+
class ReproPropertyCollectionHolder
159+
{
160+
/**
161+
* @var ReproGenericCollection<Dog>
162+
*/
163+
public ReproGenericCollection $dogs;
164+
165+
/**
166+
* @var ReproGenericTypedMap<non-empty-string, positive-int>
167+
*/
168+
public ReproGenericTypedMap $scores;
169+
170+
public function __construct()
171+
{
172+
$this->dogs = new ReproGenericCollection(Dog::class);
173+
$this->scores = new ReproGenericTypedMap('string', 'int');
174+
}
175+
}
176+
177+
describe('Generic ArrayAccess Dimension Assignment ($collection[] = $val & $map[$k] = $val)', function () {
178+
beforeEach(function () {
179+
Config::set(['array_validation' => 'full']);
180+
});
181+
182+
afterEach(function () {
183+
Config::reset();
184+
});
185+
186+
describe('1. Single-Template Generic Collection<T> (Ramsey Collection Reproduction)', function () {
187+
test('enforces generic type T on add() and array append $dogs[] = ... in full validation mode', function () {
188+
/** @var ReproGenericCollection<Dog> $dogs */
189+
$dogs = new ReproGenericCollection(Dog::class);
190+
191+
$dogs->add(new Dog());
192+
$dogs[] = new Dog();
193+
194+
expect($dogs->count())->toBe(2)
195+
->and(TypePHP::getGenericType($dogs))->toBe(Dog::class)
196+
;
197+
198+
expect(function () use ($dogs) {
199+
$dogs[] = new Car();
200+
})->toThrow(TypeError::class, Dog::class);
201+
});
202+
203+
test('enforces positive-int, array shapes, and unions on Collection<T> with $collection[] = ...', function () {
204+
/** @var ReproGenericCollection<positive-int> $scores */
205+
$scores = new ReproGenericCollection('int');
206+
$scores->add(100);
207+
$scores[] = 200;
208+
209+
expect($scores->count())->toBe(2);
210+
211+
expect(function () use ($scores) {
212+
$scores[] = -50;
213+
})->toThrow(TypeError::class, 'positive-int');
214+
215+
/** @var ReproGenericCollection<Dog|Cat> $pets */
216+
$pets = new ReproGenericCollection('object');
217+
$pets[] = new Dog();
218+
$pets[] = new Cat();
219+
220+
expect($pets->count())->toBe(2);
221+
222+
expect(function () use ($pets) {
223+
$pets[] = new Car();
224+
})->toThrow(TypeError::class);
225+
});
226+
});
227+
228+
describe('2. Two-Template Generic TypedMap<K, T> (Ramsey TypedMap Reproduction)', function () {
229+
test('enforces both Key (K) and Value (T) generics on put() and $map[$k] = ... in full validation mode', function () {
230+
/** @var ReproGenericTypedMap<string, Dog> $map */
231+
$map = new ReproGenericTypedMap('string', Dog::class);
232+
233+
$map->put('primary', new Dog());
234+
$map['secondary'] = new Dog();
235+
236+
expect($map->count())->toBe(2)
237+
->and(TypePHP::getGenericType($map, 'K'))->toBe('string')
238+
->and(TypePHP::getGenericType($map, 'T'))->toBe(Dog::class)
239+
;
240+
241+
expect(function () use ($map) {
242+
$map['tertiary'] = new Car();
243+
})->toThrow(TypeError::class, Dog::class);
244+
245+
expect(function () use ($map) {
246+
$map[123] = new Dog();
247+
})->toThrow(TypeError::class, 'key must be of type string');
248+
});
249+
250+
test('enforces generic key and value on native SPL ArrayObject<K, V> dimension assignments', function () {
251+
/** @var ArrayObject<non-empty-string, positive-int> $ao */
252+
$ao = new ArrayObject();
253+
254+
$ao['alpha'] = 10;
255+
expect($ao['alpha'])->toBe(10);
256+
257+
expect(function () use ($ao) {
258+
$ao[''] = 20;
259+
})->toThrow(TypeError::class, 'key must be of type non-empty-string');
260+
261+
expect(function () use ($ao) {
262+
$ao['beta'] = -5;
263+
})->toThrow(TypeError::class, 'positive-int');
264+
});
265+
});
266+
267+
describe('3. Class Properties Holding Generic ArrayAccess Objects ($this->dogs[] = ...)', function () {
268+
test('validates dimension assignments on object properties without converting property to array', function () {
269+
$holder = new ReproPropertyCollectionHolder();
270+
271+
$holder->dogs[] = new Dog();
272+
expect($holder->dogs->count())->toBe(1);
273+
274+
expect(function () use ($holder) {
275+
$holder->dogs[] = new Car();
276+
})->toThrow(TypeError::class, Dog::class);
277+
278+
$holder->scores['first'] = 100;
279+
expect($holder->scores->count())->toBe(1);
280+
281+
expect(function () use ($holder) {
282+
$holder->scores[''] = 100;
283+
})->toThrow(TypeError::class, 'key must be of type non-empty-string');
284+
285+
expect(function () use ($holder) {
286+
$holder->scores['second'] = -10;
287+
})->toThrow(TypeError::class, 'positive-int');
288+
});
289+
});
290+
});

0 commit comments

Comments
 (0)