-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray-shapes.patch
More file actions
8092 lines (7948 loc) · 246 KB
/
Copy patharray-shapes.patch
File metadata and controls
8092 lines (7948 loc) · 246 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git a/README.md b/README.md
index fabe5902..186473f3 100644
--- a/README.md
+++ b/README.md
@@ -16,73 +16,301 @@ blog to the most popular websites in the world. PHP is distributed under the
---
-## Array Shape Return Types (RFC Implementation)
+## Typed Arrays & Array Shapes RFC Implementation
-This fork implements **Array Shape Return Types** for PHP, allowing you to specify
-element types for array return values using the `array<T>` syntax.
+This fork implements **Typed Arrays** and **Array Shapes** for PHP—two complementary features that bring type safety to PHP's most versatile data structure.
-### Features
+### The Problem
-- **Basic typed arrays**: `array<int>`, `array<string>`, `array<float>`, `array<bool>`
-- **Object typed arrays**: `array<MyClass>`, `array<DateTime>`
-- **Union types**: `array<int|string>`, `array<MyClass|OtherClass|int>`
-- **Nested arrays**: `array<array<int>>`, `array<array<array<string>>>` (up to 4 levels)
-- **Compile-time validation** for constant arrays (escape analysis optimization)
-- **Runtime validation** with detailed error messages
+PHP arrays are incredibly flexible, serving as lists, dictionaries, and structured records. But this flexibility comes at a cost: no way to express or enforce what an array should contain.
-### Usage
+```php
+function getUsers(): array {
+ // What's in this array? Objects? Associative arrays? Integers?
+ // The type system can't tell you.
+}
+```
-Enable strict array checking with the `strict_arrays` declare:
+### The Solution: Two Complementary Features
-```php
-<?php
-declare(strict_arrays=1);
+#### Typed Arrays — For Collections
-// Basic typed array
+When you have a **list of things of the same type**, use typed arrays:
+
+```php
+// A list of integers
function getIds(): array<int> {
return [1, 2, 3];
}
-// Union types
-function getValues(): array<int|string> {
- return [1, "two", 3];
+// A list of User objects
+function getActiveUsers(): array<User> {
+ return $this->repository->findActive();
+}
+
+// A dictionary with string keys and integer values
+function getScores(): array<string, int> {
+ return ['alice' => 95, 'bob' => 87, 'charlie' => 92];
+}
+```
+
+This is what you reach for when working with collections—arrays where every element is the same kind of thing.
+
+#### Array Shapes — For Structured Data
+
+When you have **structured data with known keys**, like records from a database or responses from an API, use array shapes:
+
+```php
+// Data from a database row
+function getUser(int $id): array{id: int, name: string, email: string} {
+ return $this->db->fetch("SELECT id, name, email FROM users WHERE id = ?", $id);
+}
+
+// Response from an external API
+function getWeather(string $city): array{temp: float, humidity: int, conditions: string} {
+ return json_decode(file_get_contents("https://api.weather.com/$city"), true);
+}
+```
+
+### Real-World Examples
+
+#### Working with Database Results
+
+```php
+// Define the shape of a user record
+shape UserRecord = array{
+ id: int,
+ name: string,
+ email: string,
+ created_at: string,
+ is_active?: bool
+};
+
+class UserRepository {
+ // Single record
+ public function find(int $id): ?UserRecord {
+ return $this->db->fetch("SELECT * FROM users WHERE id = ?", $id);
+ }
+
+ // Collection of records — combining both features!
+ public function findAll(): array<UserRecord> {
+ return $this->db->fetchAll("SELECT * FROM users");
+ }
+}
+```
+
+#### Working with API Responses
+
+```php
+// Shape describing the API response structure
+shape ApiResponse = array{
+ success: bool,
+ data: mixed,
+ error?: string,
+ meta?: array{page: int, total: int}
+};
+
+shape ProductData = array{
+ id: int,
+ name: string,
+ price: float,
+ tags: array<string> // Nested typed array!
+};
+
+function fetchProduct(int $id): ProductData {
+ $response = $this->http->get("/api/products/$id");
+ return $response['data'];
+}
+
+function fetchProducts(): array<ProductData> {
+ $response = $this->http->get("/api/products");
+ return $response['data'];
+}
+```
+
+#### Configuration Arrays
+
+```php
+shape DatabaseConfig = array{
+ host: string,
+ port: int,
+ database: string,
+ username: string,
+ password: string,
+ options?: array<string, mixed>
+};
+
+shape AppConfig = array{
+ debug: bool,
+ env: string,
+ database: DatabaseConfig,
+ cache_ttl?: int
+};
+
+function loadConfig(string $path): AppConfig {
+ return require $path;
}
+```
+
+### This is NOT About DTOs
+
+A common misconception: "Why not just use classes/DTOs?"
+
+**These features work with arrays, not objects.** They're designed for the many situations where arrays are the right tool:
+
+- **Database results** — PDO and other drivers return arrays
+- **JSON APIs** — `json_decode()` returns arrays
+- **Configuration files** — Often loaded as arrays
+- **Legacy code** — Millions of lines of PHP use arrays for structured data
+- **Interoperability** — Arrays are PHP's universal data interchange format
-// Object types
-function getUsers(): array<User> {
- return [new User("Alice"), new User("Bob")];
+You don't have to choose between arrays and objects. Use objects when you need behavior (methods), use typed arrays when you're working with data.
+
+```php
+// Arrays for data from external sources
+function getApiUser(): array{id: int, name: string} {
+ return json_decode($response, true);
}
-// Nested arrays (matrix)
-function getMatrix(): array<array<int>> {
- return [[1, 2], [3, 4], [5, 6]];
+// Objects when you need behavior
+class User {
+ public function __construct(
+ public int $id,
+ public string $name
+ ) {}
+
+ public function greet(): string {
+ return "Hello, {$this->name}!";
+ }
}
+```
+
+### Quick Reference
-// Mixed union with objects
-function getItems(): array<Product|Service|int> {
- return [new Product(), 42, new Service()];
+```php
+// Typed arrays — for collections
+array<int> // List of integers
+array<string> // List of strings
+array<User> // List of User objects
+array<int|string> // List of integers or strings
+array<string, int> // Dictionary: string keys, int values
+array<array<int>> // List of integer lists
+
+// Array shapes — for structured data
+array{id: int, name: string} // Required keys
+array{id: int, email?: string} // Optional key (may be absent)
+array{data: ?string} // Nullable value (can be null)
+array{user: array{id: int}} // Nested shapes
+array{id: int, name: string}! // Closed shape (no extra keys allowed)
+
+// Shape type aliases — for reusability
+shape User = array{id: int, name: string};
+shape Point = array{x: int, y: int};
+shape Config = array{debug: bool, cache?: int};
+
+// Shape inheritance
+shape BaseUser = array{id: int, name: string};
+shape AdminUser extends BaseUser = array{role: string, permissions: array<string>};
+```
+
+### Shape Inheritance
+
+Shapes support single inheritance with type covariance:
+
+```php
+shape Entity = array{id: int, created_at: string};
+shape User extends Entity = array{name: string, email: string};
+shape Admin extends User = array{role: string, permissions: array<string>};
+
+// Admin inherits all fields: id, created_at, name, email, role, permissions
+function getAdmin(): Admin {
+ return [
+ 'id' => 1,
+ 'created_at' => '2024-01-01',
+ 'name' => 'Alice',
+ 'email' => 'alice@example.com',
+ 'role' => 'superadmin',
+ 'permissions' => ['read', 'write', 'delete']
+ ];
}
```
-### Error Handling
+**Covariance rules:**
+- Child shapes can narrow parent types (e.g., `string|int` → `string`)
+- Child shapes cannot widen types (e.g., `string` → `int` is rejected)
+- Child shapes can make optional properties required
+- Child shapes cannot make required properties optional
+
+### Closed Shapes
-When validation fails, a `TypeError` is thrown with details about the failing element:
+By default, shapes are "open" — they allow extra keys beyond what's defined. Use the `!` suffix for closed shapes that reject extra keys:
```php
-function getInts(): array<int> {
- return [1, "two", 3]; // TypeError: array element at index 1 is string
+// Open shape (default) — extra keys allowed
+function getUser(): array{id: int, name: string} {
+ return ['id' => 1, 'name' => 'Alice', 'extra' => 'allowed']; // OK
+}
+
+// Closed shape — no extra keys allowed
+function getStrictUser(): array{id: int, name: string}! {
+ return ['id' => 1, 'name' => 'Alice', 'extra' => 'forbidden'];
+ // TypeError: unexpected extra key "extra"
}
```
+### Error Messages
+
+When validation fails, you get clear error messages:
+
+```php
+function getIds(): array<int> {
+ return [1, "two", 3];
+}
+// TypeError: getIds(): Return value must be of type array<int>,
+// array element at index 1 is string
+
+function getUser(): array{id: int, name: string} {
+ return ['id' => 1];
+}
+// TypeError: getUser(): Return value must be of type array{name: string, ...},
+// array given with missing key "name"
+```
+
+### Shape Autoloading
+
+Shapes can be autoloaded like classes, keeping your codebase organized:
+
+```php
+// shapes/UserRecord.php
+<?php
+shape UserRecord = array{id: int, name: string, email: string};
+
+// Somewhere else in your code
+spl_autoload_register(function($name) {
+ $file = __DIR__ . "/shapes/$name.php";
+ if (file_exists($file)) require_once $file;
+});
+
+// UserRecord is autoloaded when first used
+function getUser(): UserRecord { ... }
+```
+
### Implementation Status
-- [x] Parser support for `array<T>` syntax
-- [x] Single type validation (`array<int>`, `array<string>`, etc.)
-- [x] Object/class type validation (`array<MyClass>`)
-- [x] Union type support (`array<int|string|MyClass>`)
-- [x] Nested array support (`array<array<T>>`)
-- [x] Compile-time escape analysis optimization
-- [x] Runtime validation with error reporting
+- [x] Typed arrays: `array<T>`, `array<K, V>`
+- [x] Array shapes: `array{key: type}`
+- [x] Optional keys: `array{key?: type}`
+- [x] Nullable values: `array{key: ?type}`
+- [x] Union types: `array<int|string>`
+- [x] Nested structures: `array<array<int>>`, `array{user: array{id: int}}`
+- [x] Shape type aliases: `shape Name = array{...}`
+- [x] Shape inheritance: `shape Child extends Parent = array{...}`
+- [x] Type covariance validation for shape inheritance
+- [x] Closed shapes: `array{...}!` (reject extra keys)
+- [x] Shape autoloading via `spl_autoload_register()`
+- [x] Reflection API support (`ReflectionArrayType`, `ReflectionArrayShapeType`)
+- [x] Runtime validation with detailed error messages
+- [x] Performance optimizations (string interning, cached key lookups)
---
diff --git a/Zend/tests/get_class_methods/bug32296.phpt b/Zend/tests/get_class_methods/bug32296.phpt
index 16914a71..612fab16 100644
--- a/Zend/tests/get_class_methods/bug32296.phpt
+++ b/Zend/tests/get_class_methods/bug32296.phpt
@@ -7,12 +7,12 @@ function __construct(){}
abstract protected function unfold();
}
-abstract class shape extends space{
+abstract class polygon extends space{
private function x1() {}
protected final function unfold(){}
}
-abstract class quad extends shape{
+abstract class quad extends polygon{
private function x2() {}
function buggy(){
$c = get_class($this);
diff --git a/Zend/tests/type_declarations/array_shapes/callable_in_shape.phpt b/Zend/tests/type_declarations/array_shapes/callable_in_shape.phpt
new file mode 100644
index 00000000..6fa8a061
--- /dev/null
+++ b/Zend/tests/type_declarations/array_shapes/callable_in_shape.phpt
@@ -0,0 +1,79 @@
+--TEST--
+Callable type in array shapes
+--XLEAK--
+--FILE--
+<?php
+
+// Test 1: Basic callable in shape
+function processWithCallback(array{data: array<int>, callback: callable} $config): array<int> {
+ return array_map($config['callback'], $config['data']);
+}
+
+$result = processWithCallback([
+ 'data' => [1, 2, 3],
+ 'callback' => fn($x) => $x * 2
+]);
+echo "Doubled: ";
+print_r($result);
+
+// Test 2: Callable as closure
+function executeHandler(array{name: string, handler: callable} $action): string {
+ return $action['handler']($action['name']);
+}
+
+$greeting = executeHandler([
+ 'name' => 'World',
+ 'handler' => fn($name) => "Hello, $name!"
+]);
+echo "$greeting\n";
+
+// Test 3: Callable as function name
+function myUppercase(string $s): string {
+ return strtoupper($s);
+}
+
+$result = executeHandler([
+ 'name' => 'test',
+ 'handler' => 'myUppercase'
+]);
+echo "$result\n";
+
+// Test 4: Callable as static method reference
+class StringUtils {
+ public static function reverse(string $s): string {
+ return strrev($s);
+ }
+}
+
+$result = executeHandler([
+ 'name' => 'hello',
+ 'handler' => [StringUtils::class, 'reverse']
+]);
+echo "$result\n";
+
+// Test 5: Optional callable
+function maybeProcess(array{value: int, transformer?: callable} $data): int {
+ if (isset($data['transformer'])) {
+ return $data['transformer']($data['value']);
+ }
+ return $data['value'];
+}
+
+echo "Without transformer: " . maybeProcess(['value' => 5]) . "\n";
+echo "With transformer: " . maybeProcess(['value' => 5, 'transformer' => fn($x) => $x * 10]) . "\n";
+
+echo "Done\n";
+?>
+--EXPECT--
+Doubled: Array
+(
+ [0] => 2
+ [1] => 4
+ [2] => 6
+)
+Hello, World!
+TEST
+olleh
+Without transformer: 5
+With transformer: 50
+Done
diff --git a/Zend/tests/type_declarations/array_shapes/callable_in_shape_error.phpt b/Zend/tests/type_declarations/array_shapes/callable_in_shape_error.phpt
new file mode 100644
index 00000000..5fc6ecaa
--- /dev/null
+++ b/Zend/tests/type_declarations/array_shapes/callable_in_shape_error.phpt
@@ -0,0 +1,38 @@
+--TEST--
+Callable type in array shapes - type error
+--XLEAK--
+--FILE--
+<?php
+
+function processWithCallback(array{callback: callable} $config): void {
+ ($config['callback'])();
+}
+
+// Test 1: Non-callable value
+try {
+ processWithCallback(['callback' => 'not_a_real_function']);
+} catch (TypeError $e) {
+ echo "TypeError: " . $e->getMessage() . "\n";
+}
+
+// Test 2: Integer instead of callable
+try {
+ processWithCallback(['callback' => 123]);
+} catch (TypeError $e) {
+ echo "TypeError: " . $e->getMessage() . "\n";
+}
+
+// Test 3: Array that's not a valid callable
+try {
+ processWithCallback(['callback' => ['NotAClass', 'notAMethod']]);
+} catch (TypeError $e) {
+ echo "TypeError: " . $e->getMessage() . "\n";
+}
+
+echo "Done\n";
+?>
+--EXPECTF--
+TypeError: processWithCallback(): Argument #1 ($config) must be of type array{callback: callable, ...}, array key "callback" is string
+TypeError: processWithCallback(): Argument #1 ($config) must be of type array{callback: callable, ...}, array key "callback" is int
+TypeError: processWithCallback(): Argument #1 ($config) must be of type array{callback: callable, ...}, array key "callback" is array
+Done
diff --git a/Zend/tests/type_declarations/array_shapes/class_cannot_extend_shape.phpt b/Zend/tests/type_declarations/array_shapes/class_cannot_extend_shape.phpt
new file mode 100644
index 00000000..74898cf6
--- /dev/null
+++ b/Zend/tests/type_declarations/array_shapes/class_cannot_extend_shape.phpt
@@ -0,0 +1,13 @@
+--TEST--
+Class cannot extend a shape
+--FILE--
+<?php
+
+shape MyShape = array{id: int, name: string};
+
+class BadClass extends MyShape {
+}
+
+?>
+--EXPECTF--
+Fatal error: Class BadClass cannot extend shape MyShape in %s on line %d
diff --git a/Zend/tests/type_declarations/array_shapes/class_method.phpt b/Zend/tests/type_declarations/array_shapes/class_method.phpt
index fd4ae661..6e6047f6 100644
--- a/Zend/tests/type_declarations/array_shapes/class_method.phpt
+++ b/Zend/tests/type_declarations/array_shapes/class_method.phpt
@@ -1,8 +1,8 @@
--TEST--
Array shape in class methods
+--XLEAK--
--FILE--
<?php
-declare(strict_arrays=1);
class UserService {
public function createUser(array{name: string, email: string} $data): array{id: int, name: string, email: string} {
diff --git a/Zend/tests/type_declarations/array_shapes/closed_shape_basic.phpt b/Zend/tests/type_declarations/array_shapes/closed_shape_basic.phpt
new file mode 100644
index 00000000..e147be7e
--- /dev/null
+++ b/Zend/tests/type_declarations/array_shapes/closed_shape_basic.phpt
@@ -0,0 +1,31 @@
+--TEST--
+Closed array shape - basic validation
+--SKIPIF--
+<?php if (getenv('USE_ZEND_ALLOC') === '0') die('skip Not compatible with valgrind'); ?>
+--FILE--
+<?php
+
+// Closed shape: no extra keys allowed
+function getUser(): array{id: int, name: string}! {
+ return ['id' => 1, 'name' => 'Alice'];
+}
+
+$user = getUser();
+var_dump($user);
+
+// Verify reflection
+$ref = new ReflectionFunction('getUser');
+$type = $ref->getReturnType();
+var_dump($type->isClosed());
+echo $type . "\n";
+
+?>
+--EXPECTF--
+array(2) {
+ ["id"]=>
+ int(1)
+ ["name"]=>
+ string(5) "Alice"
+}
+bool(true)
+array{id: int, name: string}!%A
diff --git a/Zend/tests/type_declarations/array_shapes/closed_shape_extra_key_error.phpt b/Zend/tests/type_declarations/array_shapes/closed_shape_extra_key_error.phpt
new file mode 100644
index 00000000..2bc0a2ed
--- /dev/null
+++ b/Zend/tests/type_declarations/array_shapes/closed_shape_extra_key_error.phpt
@@ -0,0 +1,20 @@
+--TEST--
+Closed array shape - extra key error
+--SKIPIF--
+<?php if (getenv('USE_ZEND_ALLOC') === '0') die('skip Not compatible with valgrind'); ?>
+--FILE--
+<?php
+
+function getUser(): array{id: int, name: string}! {
+ return ['id' => 1, 'name' => 'Alice', 'extra' => 'not allowed'];
+}
+
+try {
+ getUser();
+} catch (TypeError $e) {
+ echo $e->getMessage() . "\n";
+}
+
+?>
+--EXPECTF--
+getUser(): Return value must be of type closed shape, unexpected extra key "extra"%A
diff --git a/Zend/tests/type_declarations/array_shapes/closed_shape_param.phpt b/Zend/tests/type_declarations/array_shapes/closed_shape_param.phpt
new file mode 100644
index 00000000..5163dc52
--- /dev/null
+++ b/Zend/tests/type_declarations/array_shapes/closed_shape_param.phpt
@@ -0,0 +1,25 @@
+--TEST--
+Closed array shape - parameter type
+--SKIPIF--
+<?php if (getenv('USE_ZEND_ALLOC') === '0') die('skip Not compatible with valgrind'); ?>
+--FILE--
+<?php
+
+function processUser(array{id: int, name: string}! $user): void {
+ echo "Processing user: " . $user['name'] . "\n";
+}
+
+// Valid: exact match
+processUser(['id' => 1, 'name' => 'Alice']);
+
+// Invalid: extra key
+try {
+ processUser(['id' => 2, 'name' => 'Bob', 'extra' => 'data']);
+} catch (TypeError $e) {
+ echo $e->getMessage() . "\n";
+}
+
+?>
+--EXPECTF--
+Processing user: Alice
+processUser(): Argument #1 ($user) must be of type closed shape, unexpected extra key "extra"%A
diff --git a/Zend/tests/type_declarations/array_shapes/closure_in_shape.phpt b/Zend/tests/type_declarations/array_shapes/closure_in_shape.phpt
new file mode 100644
index 00000000..21a2faa4
--- /dev/null
+++ b/Zend/tests/type_declarations/array_shapes/closure_in_shape.phpt
@@ -0,0 +1,56 @@
+--TEST--
+Closure type in array shapes
+--XLEAK--
+--FILE--
+<?php
+
+// Test 1: Closure type in shape (more specific than callable)
+function processWithClosure(array{handler: Closure} $config): mixed {
+ return $config['handler']();
+}
+
+$result = processWithClosure([
+ 'handler' => fn() => 'Hello from closure'
+]);
+echo "$result\n";
+
+// Test 2: Closure with use()
+$multiplier = 3;
+$result = processWithClosure([
+ 'handler' => function() use ($multiplier) {
+ return 10 * $multiplier;
+ }
+]);
+echo "Result: $result\n";
+
+// Test 3: Array of closures
+function runAll(array{tasks: array<Closure>} $config): array<mixed> {
+ $results = [];
+ foreach ($config['tasks'] as $task) {
+ $results[] = $task();
+ }
+ return $results;
+}
+
+$results = runAll([
+ 'tasks' => [
+ fn() => 1,
+ fn() => 2,
+ fn() => 3,
+ ]
+]);
+echo "Tasks results: ";
+print_r($results);
+
+echo "Done\n";
+?>
+--EXPECT--
+Hello from closure
+Result: 30
+Tasks results: Array
+(
+ [0] => 1
+ [1] => 2
+ [2] => 3
+)
+Done
diff --git a/Zend/tests/type_declarations/array_shapes/closure_in_shape_error.phpt b/Zend/tests/type_declarations/array_shapes/closure_in_shape_error.phpt
new file mode 100644
index 00000000..bf106c51
--- /dev/null
+++ b/Zend/tests/type_declarations/array_shapes/closure_in_shape_error.phpt
@@ -0,0 +1,54 @@
+--TEST--
+Closure type in array shapes - type error (callable but not Closure)
+--XLEAK--
+--FILE--
+<?php
+
+function processWithClosure(array{handler: Closure} $config): mixed {
+ return $config['handler']();
+}
+
+// Test 1: Function name string (callable but not Closure)
+function myFunc(): string {
+ return 'hello';
+}
+
+try {
+ processWithClosure(['handler' => 'myFunc']);
+} catch (TypeError $e) {
+ echo "TypeError: " . $e->getMessage() . "\n";
+}
+
+// Test 2: Static method array (callable but not Closure)
+class Helper {
+ public static function run(): string {
+ return 'helper';
+ }
+}
+
+try {
+ processWithClosure(['handler' => [Helper::class, 'run']]);
+} catch (TypeError $e) {
+ echo "TypeError: " . $e->getMessage() . "\n";
+}
+
+// Test 3: Invokable object (callable but not Closure)
+class Invokable {
+ public function __invoke(): string {
+ return 'invoked';
+ }
+}
+
+try {
+ processWithClosure(['handler' => new Invokable()]);
+} catch (TypeError $e) {
+ echo "TypeError: " . $e->getMessage() . "\n";
+}
+
+echo "Done\n";
+?>
+--EXPECTF--
+TypeError: processWithClosure(): Argument #1 ($config) must be of type array{handler: Closure, ...}, array key "handler" is string
+TypeError: processWithClosure(): Argument #1 ($config) must be of type array{handler: Closure, ...}, array key "handler" is array
+TypeError: processWithClosure(): Argument #1 ($config) must be of type array{handler: Closure, ...}, array key "handler" is Invokable
+Done
diff --git a/Zend/tests/type_declarations/array_shapes/interface_covariance.phpt b/Zend/tests/type_declarations/array_shapes/interface_covariance.phpt
new file mode 100644
index 00000000..34ead6fd
--- /dev/null
+++ b/Zend/tests/type_declarations/array_shapes/interface_covariance.phpt
@@ -0,0 +1,64 @@
+--TEST--
+Interface implementation with covariant array shape return types
+--XLEAK--
+--FILE--
+<?php
+
+// Test 1: Implementation returns more specific shape (valid covariance)
+interface BaseDataProvider {
+ public function getData(): array{id: int};
+}
+
+class ExtendedDataProvider implements BaseDataProvider {
+ // Returns more specific type - adds extra fields (covariant)
+ public function getData(): array{id: int, name: string, email: string} {
+ return ['id' => 1, 'name' => 'Test', 'email' => 'test@example.com'];
+ }
+}
+
+$provider = new ExtendedDataProvider();
+$data = $provider->getData();
+echo "Got data with id={$data['id']}, name={$data['name']}\n";
+
+// Test 2: Child class narrows parent's interface implementation
+interface ConfigProvider {
+ public function getConfig(): array{debug: bool, options?: array<string>};
+}
+
+class ProductionConfig implements ConfigProvider {
+ public function getConfig(): array{debug: bool, options: array<string>} {
+ // Makes optional field required (valid narrowing)
+ return ['debug' => false, 'options' => ['cache', 'minify']];
+ }
+}
+
+$config = new ProductionConfig();
+$cfg = $config->getConfig();
+echo "Debug: " . ($cfg['debug'] ? 'yes' : 'no') . ", Options: " . count($cfg['options']) . "\n";
+
+// Test 3: Abstract class with shape, concrete implementation
+abstract class AbstractRepository {
+ abstract public function find(int $id): array{id: int, created_at: string};
+}
+
+class ConcreteRepository extends AbstractRepository {
+ public function find(int $id): array{id: int, created_at: string, updated_at: string} {
+ return [
+ 'id' => $id,
+ 'created_at' => '2024-01-01',
+ 'updated_at' => '2024-06-15'
+ ];
+ }
+}
+
+$repo = new ConcreteRepository();
+$item = $repo->find(5);
+echo "Item {$item['id']} created: {$item['created_at']}\n";
+
+echo "Done\n";
+?>
+--EXPECT--
+Got data with id=1, name=Test
+Debug: no, Options: 2
+Item 5 created: 2024-01-01
+Done
diff --git a/Zend/tests/type_declarations/array_shapes/interface_with_shapes.phpt b/Zend/tests/type_declarations/array_shapes/interface_with_shapes.phpt
new file mode 100644
index 00000000..b4814ae6
--- /dev/null
+++ b/Zend/tests/type_declarations/array_shapes/interface_with_shapes.phpt
@@ -0,0 +1,90 @@
+--TEST--
+Interfaces with array shape return types
+--XLEAK--
+--FILE--
+<?php
+
+// Test 1: Interface method with array shape return type
+interface UserRepositoryInterface {
+ public function findById(int $id): array{id: int, name: string, email: string};
+ public function findAll(): array<array{id: int, name: string}>;
+}
+
+class InMemoryUserRepository implements UserRepositoryInterface {
+ private array $users = [];
+
+ public function __construct() {
+ $this->users = [
+ 1 => ['id' => 1, 'name' => 'Alice', 'email' => 'alice@example.com'],
+ 2 => ['id' => 2, 'name' => 'Bob', 'email' => 'bob@example.com'],
+ ];
+ }
+
+ public function findById(int $id): array{id: int, name: string, email: string} {
+ return $this->users[$id];
+ }
+
+ public function findAll(): array<array{id: int, name: string}> {
+ return array_values($this->users);
+ }
+}
+
+$repo = new InMemoryUserRepository();
+$user = $repo->findById(1);
+echo "User: {$user['name']} <{$user['email']}>\n";
+
+$all = $repo->findAll();
+echo "Total users: " . count($all) . "\n";
+
+// Test 2: Interface with typed array parameter
+interface DataProcessorInterface {
+ public function process(array<int> $data): int;
+}
+
+class SumProcessor implements DataProcessorInterface {
+ public function process(array<int> $data): int {
+ return array_sum($data);
+ }
+}
+
+$processor = new SumProcessor();
+echo "Sum: " . $processor->process([1, 2, 3, 4, 5]) . "\n";
+
+// Test 3: Multiple interfaces with shapes
+interface Identifiable {
+ public function getIdentity(): array{id: int, type: string};
+}
+
+interface Describable {
+ public function describe(): array{title: string, description: string};
+}
+
+class Product implements Identifiable, Describable {
+ public function __construct(
+ private int $id,
+ private string $name,
+ private string $desc
+ ) {}
+
+ public function getIdentity(): array{id: int, type: string} {
+ return ['id' => $this->id, 'type' => 'product'];
+ }
+
+ public function describe(): array{title: string, description: string} {
+ return ['title' => $this->name, 'description' => $this->desc];
+ }
+}
+
+$product = new Product(42, 'Widget', 'A useful widget');
+$identity = $product->getIdentity();
+$desc = $product->describe();
+echo "Product #{$identity['id']} ({$identity['type']}): {$desc['title']}\n";
+
+echo "Done\n";
+?>
+--EXPECT--
+User: Alice <alice@example.com>
+Total users: 2
+Sum: 15
+Product #42 (product): Widget
+Done
diff --git a/Zend/tests/type_declarations/array_shapes/open_shape_extra_keys.phpt b/Zend/tests/type_declarations/array_shapes/open_shape_extra_keys.phpt
new file mode 100644
index 00000000..c915464e
--- /dev/null
+++ b/Zend/tests/type_declarations/array_shapes/open_shape_extra_keys.phpt
@@ -0,0 +1,35 @@
+--TEST--
+Open array shape - extra keys allowed (default)
+--SKIPIF--
+<?php if (getenv('USE_ZEND_ALLOC') === '0') die('skip Not compatible with valgrind'); ?>
+--FILE--
+<?php
+
+// Open shape (default): extra keys are allowed
+function getUser(): array{id: int, name: string} {
+ return ['id' => 1, 'name' => 'Alice', 'extra' => 'allowed', 'more' => 'data'];
+}
+
+$user = getUser();
+var_dump($user);
+
+// Verify reflection shows not closed
+$ref = new ReflectionFunction('getUser');
+$type = $ref->getReturnType();
+var_dump($type->isClosed());
+echo $type . "\n";
+
+?>
+--EXPECTF--
+array(4) {
+ ["id"]=>
+ int(1)
+ ["name"]=>
+ string(5) "Alice"
+ ["extra"]=>
+ string(7) "allowed"
+ ["more"]=>
+ string(4) "data"
+}
+bool(false)
+array{id: int, name: string}%A
diff --git a/Zend/tests/type_declarations/array_shapes/param_basic.phpt b/Zend/tests/type_declarations/array_shapes/param_basic.phpt
index 84c2e0b1..28bbadde 100644
--- a/Zend/tests/type_declarations/array_shapes/param_basic.phpt
+++ b/Zend/tests/type_declarations/array_shapes/param_basic.phpt
@@ -2,7 +2,6 @@
Array shape as parameter type - basic validation
--FILE--
<?php
-declare(strict_arrays=1);
function processPoint(array{x: int, y: int} $point): int {
return $point['x'] + $point['y'];
diff --git a/Zend/tests/type_declarations/array_shapes/param_contravariance.phpt b/Zend/tests/type_declarations/array_shapes/param_contravariance.phpt
new file mode 100644
index 00000000..fee1a787
--- /dev/null
+++ b/Zend/tests/type_declarations/array_shapes/param_contravariance.phpt
@@ -0,0 +1,85 @@
+--TEST--
+Parameter contravariance with array shapes - child accepts wider types
+--XLEAK--
+--FILE--
+<?php
+
+// Test 1: Child class accepts wider array shape (fewer required fields)
+class BaseProcessor {
+ public function process(array{id: int, name: string, email: string} $data): void {
+ echo "Base processing: {$data['id']}\n";
+ }
+}
+
+class FlexibleProcessor extends BaseProcessor {
+ // Contravariant: accepts wider type (fewer required fields)
+ public function process(array{id: int} $data): void {
+ echo "Flexible processing: {$data['id']}\n";
+ }
+}
+
+$processor = new FlexibleProcessor();
+$processor->process(['id' => 1, 'name' => 'Test', 'email' => 'test@test.com']);
+$processor->process(['id' => 2]); // Would fail on parent, works on child
+
+// Test 2: Interface implementation with wider parameter type
+interface StrictHandler {
+ public function handle(array{action: string, payload: array{id: int}} $request): void;
+}
+
+class LenientHandler implements StrictHandler {
+ // Accepts wider type - payload only needs to be an array
+ public function handle(array{action: string, payload: array} $request): void {
+ echo "Handling action: {$request['action']}\n";