@tolki/ts 1.0.3 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1310 -212
- package/dist/enums.d.ts +1 -1
- package/dist/enums.d.ts.map +1 -1
- package/dist/enums.js +1 -7
- package/dist/index.js +3 -16
- package/dist/routes.js +201 -258
- package/dist/vite-plugin.d.ts +2 -10
- package/dist/vite-plugin.d.ts.map +1 -1
- package/dist/vite-plugin.js +76 -121
- package/package.json +12 -4
package/README.md
CHANGED
|
@@ -229,7 +229,7 @@ php artisan ts:publish --source="app/Enums/Status.php"
|
|
|
229
229
|
php artisan ts:publish --source="App\Http\Resources\UserResource"
|
|
230
230
|
```
|
|
231
231
|
|
|
232
|
-
The class can be an enum, a model, an API resource, a controller with at least one registered route, a form request, or a
|
|
232
|
+
The class can be an enum, a model, an API resource, a controller with at least one registered route, a form request, a broadcast event, or a class with a [composed type](https://tolki.abe.dev/ts/custom-types.html#composed-types). On a large project, a single-class run is much faster than a full publish. The [Vite plugin](https://tolki.abe.dev/ts/vite-plugin.html#single-file-republishing) uses it during development to republish only the file that changed.
|
|
233
233
|
|
|
234
234
|
A single-class run differs from a full run in these ways:
|
|
235
235
|
|
|
@@ -343,6 +343,7 @@ Pass one `--only-*` flag to publish a single feature for one run:
|
|
|
343
343
|
| `--only-form-requests` | Form requests |
|
|
344
344
|
| `--only-broadcast-channels` | Broadcast channels |
|
|
345
345
|
| `--only-broadcast-events` | Broadcast events |
|
|
346
|
+
| `--only-class-types` | [Composed types](https://tolki.abe.dev/ts/custom-types.html#composed-types) |
|
|
346
347
|
| `--only-functional` | Every enabled feature except model and resource interfaces |
|
|
347
348
|
|
|
348
349
|
For example:
|
|
@@ -411,6 +412,8 @@ let user: app.models.User;
|
|
|
411
412
|
let status: app.enums.StatusType;
|
|
412
413
|
```
|
|
413
414
|
|
|
415
|
+
Unlike in [the enum's own file](https://tolki.abe.dev/ts/enums.html#value-key-types), an enum's name in this file, such as `app.enums.Status`, is an interface of its cases, so type an enum value as `app.enums.StatusType`.
|
|
416
|
+
|
|
414
417
|
A namespace segment of more than one word is camel-cased, because a hyphen isn't valid in a namespace name. `App\Http\Resources\ReportCards\SummaryCardResource` is `app.http.resources.reportCards.SummaryCardResource`, while its file is written under `report-cards/`. An acronym is lowered as one word, so `API` is `api` and `HTTPClient` is `httpClient`.
|
|
415
418
|
|
|
416
419
|
When two published types share a name, such as `App\Models\User` and `Crm\Models\User`, each reference from another namespace is qualified with the namespace of the class your PHP code names, such as `crm.models.User`.
|
|
@@ -419,7 +422,7 @@ TypeScript sees these types only when your `tsconfig.json` includes the file.
|
|
|
419
422
|
|
|
420
423
|
#### JSON Definitions File
|
|
421
424
|
|
|
422
|
-
When `json.enabled` is `true`, the package also writes `laravel-ts-definitions.json`. It describes every published model, enum, resource, form request,
|
|
425
|
+
When `json.enabled` is `true`, the package also writes `laravel-ts-definitions.json`. It describes every published model, enum, resource, form request, broadcast event, and [composed type](https://tolki.abe.dev/ts/custom-types.html#composed-types) as data, such as properties, cases, and methods, instead of TypeScript source:
|
|
423
426
|
|
|
424
427
|
```php
|
|
425
428
|
// config/ts-publish.php
|
|
@@ -430,7 +433,7 @@ When `json.enabled` is `true`, the package also writes `laravel-ts-definitions.j
|
|
|
430
433
|
],
|
|
431
434
|
```
|
|
432
435
|
|
|
433
|
-
The file has one top-level object per feature: `models`, `enums`, `resources`, `formRequests`, and `
|
|
436
|
+
The file has one top-level object per feature: `models`, `enums`, `resources`, `formRequests`, `broadcastEvents`, and `classTypes`. Each object is keyed by fully-qualified class name, and each entry has a `name` field that holds the short class name. A `classTypes` entry's `name` holds the composed type's name instead, such as `ChartType`, and its `extends` field lists the types that interface extends:
|
|
434
437
|
|
|
435
438
|
```json
|
|
436
439
|
{
|
|
@@ -559,6 +562,8 @@ export const Color = defineEnum({
|
|
|
559
562
|
|
|
560
563
|
export type ColorType = "red" | "green" | "blue";
|
|
561
564
|
export type ColorKind = "Red" | "Green" | "Blue";
|
|
565
|
+
|
|
566
|
+
export type Color = ColorType;
|
|
562
567
|
```
|
|
563
568
|
|
|
564
569
|
Each part of the file does one job:
|
|
@@ -567,7 +572,7 @@ Each part of the file does one job:
|
|
|
567
572
|
- **`backed`**: whether the PHP enum is backed. [`EnumResource`](https://tolki.abe.dev/ts/enum-api-resource.html) responses include the same key, and [`AsEnum`](#type-reference) types it.
|
|
568
573
|
- **`hex`**: an instance method published with [`#[TsEnumMethod]`](#tsenummethod), with one value per case.
|
|
569
574
|
- **`_cases`, `_methods` and `_static`**: the lists the `@tolki/ts` functions read to build a PHP-like instance. See [Runtime Utilities](#runtime-utilities).
|
|
570
|
-
- **`ColorType` and `
|
|
575
|
+
- **`ColorType`, `ColorKind` and `Color`**: type aliases for the case values and the case names. The `Color` type is another name for `ColorType`, so `Color` is both the enum object and the type of its values. See [Value & Key Types](#value--key-types).
|
|
571
576
|
|
|
572
577
|
### Enum Attributes
|
|
573
578
|
|
|
@@ -629,6 +634,8 @@ The attribute takes these parameters:
|
|
|
629
634
|
| `description` | `string` | `''` | A JSDoc comment above the property. |
|
|
630
635
|
| `params` | `array` | `[]` | Named arguments to call the method with. See [Methods With Required Parameters](#methods-with-required-parameters). |
|
|
631
636
|
|
|
637
|
+
The method must be public. A private or protected method with the attribute isn't published, and `ts:publish` warns about it.
|
|
638
|
+
|
|
632
639
|
##### Methods With Required Parameters
|
|
633
640
|
|
|
634
641
|
A method with required parameters is skipped by default, instead of publishing misleading `null` values. To include one, pass `params`. The package calls the method once per case, with those values as named arguments:
|
|
@@ -654,7 +661,7 @@ An instance or static method's value publishes as `json_encode()` writes it, whi
|
|
|
654
661
|
|
|
655
662
|
A value that `json_encode()` can't write, such as `NAN` or a string that isn't valid UTF-8, publishes as `null`.
|
|
656
663
|
|
|
657
|
-
An array whose integer keys don't count up from 0 in order publishes as an object keyed by those numbers, because that's how `json_encode()` writes it. `array_filter()` keeps each item's key, so it returns such an array whenever it removes an item before one it keeps.
|
|
664
|
+
An array whose integer keys don't count up from 0 in order publishes as an object keyed by those numbers, because that's how `json_encode()` writes it, and an `EnumResource` response sends the same object. `array_filter()` keeps each item's key, so it returns such an array whenever it removes an item before one it keeps. Wrap the array in `array_values()` to publish and send a list:
|
|
658
665
|
|
|
659
666
|
```php
|
|
660
667
|
#[TsEnumMethod]
|
|
@@ -691,7 +698,7 @@ export const Status = defineEnum({
|
|
|
691
698
|
} as const);
|
|
692
699
|
```
|
|
693
700
|
|
|
694
|
-
|
|
701
|
+
The same rules apply as with `#[TsEnumMethod]`: the method must be public, and a method with required parameters is skipped unless you pass `params`.
|
|
695
702
|
|
|
696
703
|
#### `#[TsEnum]`
|
|
697
704
|
|
|
@@ -720,6 +727,8 @@ export const UserStatus = defineEnum({
|
|
|
720
727
|
|
|
721
728
|
export type UserStatusType = "active" | "inactive";
|
|
722
729
|
export type UserStatusKind = "Active" | "Inactive";
|
|
730
|
+
|
|
731
|
+
export type UserStatus = UserStatusType;
|
|
723
732
|
```
|
|
724
733
|
|
|
725
734
|
The file takes the new name too (`user-status.ts`), and models that use the enum refer to it as `UserStatusType`. The attribute takes these parameters:
|
|
@@ -729,7 +738,7 @@ The file takes the new name too (`user-status.ts`), and models that use the enum
|
|
|
729
738
|
| `name` | `string` | The TypeScript const name. Use it when two enums in one namespace publish the same name, or when a [route file](https://tolki.abe.dev/ts/routing.html#what-the-props-expression-can-be) uses two same-named enums from different namespaces. |
|
|
730
739
|
| `description` | `string` | A JSDoc comment. It takes priority over any PHPDoc description. |
|
|
731
740
|
|
|
732
|
-
|
|
741
|
+
When two classes in one namespace publish the same name, their barrel file and the global declaration file can't export both. For example, an enum `Role` publishes the type `RoleType`, so a second enum named `RoleType` in the same namespace clashes with it. `ts:publish` warns about any such pair, whether the classes are enums, models, resources, form requests, broadcast events or [composed types](https://tolki.abe.dev/ts/custom-types.html#composed-types). Move one of them to a namespace of its own, or rename it. An enum takes a new name with `#[TsEnum]`. In two different namespaces the pair is fine, because a file that imports both gets an alias for one. Two kinds of class in one directory, such as an enum `App\Models\Status` beside the models, drop each other's barrel exports, so keep each kind of class in a namespace of its own.
|
|
733
742
|
|
|
734
743
|
#### `#[TsCase]`
|
|
735
744
|
|
|
@@ -760,8 +769,12 @@ export const Status = defineEnum({
|
|
|
760
769
|
|
|
761
770
|
export type StatusType = "enabled" | "disabled";
|
|
762
771
|
export type StatusKind = "Enabled" | "Disabled";
|
|
772
|
+
|
|
773
|
+
export type Status = StatusType;
|
|
763
774
|
```
|
|
764
775
|
|
|
776
|
+
A published [instance method](#tsenummethod) keys its values by the new case names too. `Status.from("enabled")` resolves each method to its value for `Status::Active`, and [`EnumResource`](https://tolki.abe.dev/ts/enum-api-resource.html) sends the same values.
|
|
777
|
+
|
|
765
778
|
The attribute takes these parameters:
|
|
766
779
|
|
|
767
780
|
| Parameter | Type | Description |
|
|
@@ -781,6 +794,8 @@ export type StatusType = "active" | "inactive";
|
|
|
781
794
|
export type StatusKind = "Active" | "Inactive"; // backed enums only
|
|
782
795
|
```
|
|
783
796
|
|
|
797
|
+
An enum with no cases publishes `never` for each alias.
|
|
798
|
+
|
|
784
799
|
Use the aliases to type a raw value or a case name:
|
|
785
800
|
|
|
786
801
|
```typescript
|
|
@@ -790,6 +805,90 @@ function setStatus(status: StatusType) {} // only 'active' | 'inactive'
|
|
|
790
805
|
function setStatusByKey(status: StatusKind) {} // only 'Active' | 'Inactive'
|
|
791
806
|
```
|
|
792
807
|
|
|
808
|
+
The enum's own name is also a type, an alias of its `{Name}Type`, so for a unit enum it's the union of its case names. One import gives you the enum object and the type of its values, as a native TypeScript `enum` does:
|
|
809
|
+
|
|
810
|
+
```typescript
|
|
811
|
+
import { Color } from "@js/types/data/app/enums";
|
|
812
|
+
|
|
813
|
+
let color: Color = Color.Red; // only 'red' | 'green' | 'blue'
|
|
814
|
+
|
|
815
|
+
Color.from(color).hex; // '#EF4444'
|
|
816
|
+
```
|
|
817
|
+
|
|
818
|
+
Use `import type { Color }` when you need only the type. Every enum file has this alias, with or without metadata and the `defineEnum()` wrapper.
|
|
819
|
+
|
|
820
|
+
To list the values or the names at runtime, call [`values`](#values) or [`keys`](#keys).
|
|
821
|
+
|
|
822
|
+
#### Reading `->value` and `->name`
|
|
823
|
+
|
|
824
|
+
Read an enum's `->value` or `->name` in an API resource, an Inertia page prop, a broadcast event, or anything else the package types, and the property publishes the enum's alias, or the case's own value when you name the case. The file imports the alias for you. Here a `PostSummaryResource` reads a `Post` model that casts `status` to the int-backed `PostStatus` enum and `visibility` to the unit enum `Visibility`:
|
|
825
|
+
|
|
826
|
+
```php
|
|
827
|
+
enum PostStatus: int
|
|
828
|
+
{
|
|
829
|
+
case Draft = 0;
|
|
830
|
+
case Published = 1;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
// PostSummaryResource
|
|
834
|
+
public function toArray(Request $request): array
|
|
835
|
+
{
|
|
836
|
+
return [
|
|
837
|
+
'status' => $this->status->value,
|
|
838
|
+
'status_name' => $this->status->name,
|
|
839
|
+
'visibility' => $this->visibility->name,
|
|
840
|
+
'published' => PostStatus::Published->value,
|
|
841
|
+
];
|
|
842
|
+
}
|
|
843
|
+
```
|
|
844
|
+
|
|
845
|
+
Each property publishes what PHP can send for it:
|
|
846
|
+
|
|
847
|
+
```typescript
|
|
848
|
+
import type {
|
|
849
|
+
PostStatusKind,
|
|
850
|
+
PostStatusType,
|
|
851
|
+
VisibilityType,
|
|
852
|
+
} from "../../enums";
|
|
853
|
+
|
|
854
|
+
export interface PostSummaryResource {
|
|
855
|
+
status: PostStatusType;
|
|
856
|
+
status_name: PostStatusKind;
|
|
857
|
+
visibility: VisibilityType;
|
|
858
|
+
published: 1;
|
|
859
|
+
}
|
|
860
|
+
```
|
|
861
|
+
|
|
862
|
+
A backed enum's `->value` publishes its `{Name}Type`, and its `->name` publishes its `{Name}Kind`. A unit enum's `->name` publishes its `{Name}Type`, because its values are its case names.
|
|
863
|
+
|
|
864
|
+
A case you write out can send only its own value, so it publishes that value: `PostStatus::Published->value` publishes `1`, and `PostStatus::Published->name` publishes `'Published'`. A ternary between two cases publishes both values. `PostStatus::from($value)->value` publishes `PostStatusType`, and after `PostStatus::tryFrom()`, `?->value` publishes `PostStatusType | null`. A method you call on a case publishes its return type.
|
|
865
|
+
|
|
866
|
+
In an API resource, `PostStatus::cases()` publishes a list of the alias. A map over the cases publishes what its callback reads from each case, with or without a type hint:
|
|
867
|
+
|
|
868
|
+
```php
|
|
869
|
+
'statuses' => PostStatus::cases(),
|
|
870
|
+
'values' => array_map(fn ($case) => $case->value, PostStatus::cases()),
|
|
871
|
+
'names' => collect(PostStatus::cases())
|
|
872
|
+
->map(fn (PostStatus $case) => $case->name)
|
|
873
|
+
->all(),
|
|
874
|
+
```
|
|
875
|
+
|
|
876
|
+
Each key publishes a list:
|
|
877
|
+
|
|
878
|
+
```typescript
|
|
879
|
+
statuses: PostStatusType[];
|
|
880
|
+
values: PostStatusType[];
|
|
881
|
+
names: PostStatusKind[];
|
|
882
|
+
```
|
|
883
|
+
|
|
884
|
+
`array_column(PostStatus::cases(), 'value')` publishes `unknown`, so map the cases instead.
|
|
885
|
+
|
|
886
|
+
The property uses the alias only when `ts:publish` publishes the enum, and when no case's `#[TsCase]` changes what the alias lists. For a `{Name}Type` that's the case's `value`, and for a `{Name}Kind` its `name`. Otherwise the property publishes the literal union of what PHP sends.
|
|
887
|
+
|
|
888
|
+
An enum the [filters](#filtering--excluding-enums) leave out publishes the literal union too, and so does every enum while `enums.enabled` is off. For the `Status` enum in the [`#[TsCase]`](#tscase) example, `->value` publishes `1 | 0` and `->name` publishes `'Active' | 'Inactive'`. An int-backed enum with a case outside JavaScript's safe integer range (±2⁵³−1) publishes `number` for `->value`.
|
|
889
|
+
|
|
890
|
+
As in a resource, two enums with the same class name, such as `App\Enums\Status` and `App\Crm\Enums\Status`, are imported under aliases in a [route file](https://tolki.abe.dev/ts/routing.html), the [Inertia shared data](https://tolki.abe.dev/ts/inertia.html) file and a [model metadata](https://tolki.abe.dev/ts/model-metadata.html) companion, as in `StatusKind as CrmStatusKind`.
|
|
891
|
+
|
|
793
892
|
### Metadata & the `defineEnum()` Wrapper
|
|
794
893
|
|
|
795
894
|
With `enums.metadata_enabled` on, every enum has a `_cases` list, plus `_methods` and `_static` lists when it publishes instance or static methods. You don't read these lists yourself. `defineEnum()` and the standalone `from`, `tryFrom` and `cases` functions use them to build a PHP-like instance from a case value:
|
|
@@ -801,7 +900,7 @@ const instance = Status.from("active");
|
|
|
801
900
|
// { name: 'Active', value: 'active', backed: true, label: 'Active User', options: [...] }
|
|
802
901
|
```
|
|
803
902
|
|
|
804
|
-
An instance method resolves to its value for the matched case (`label`), and a static method passes through as it is (`options`). See [Runtime Utilities](#runtime-utilities) for every function.
|
|
903
|
+
An instance method resolves to its value for the matched case (`label`), and a static method passes through as it is (`options`). See [Runtime Utilities](#runtime-utilities) for every function. [`values`](#values) and [`keys`](#keys) read `_cases` too.
|
|
805
904
|
|
|
806
905
|
#### Disabling Metadata or the `@tolki/ts` Wrapper
|
|
807
906
|
|
|
@@ -881,9 +980,9 @@ Enums use the same include and exclude settings as models, resources and the oth
|
|
|
881
980
|
|
|
882
981
|
### Runtime Utilities
|
|
883
982
|
|
|
884
|
-
`@tolki/ts` exports these functions
|
|
983
|
+
`@tolki/ts` exports these functions. `from`, `tryFrom` and `cases` give `defineEnum()` its PHP-like behavior, and you normally call them through the published enum (`Status.from(...)`). `values` and `keys` aren't bound to the enum, so you import them.
|
|
885
984
|
|
|
886
|
-
[cases](#cases) [defineEnum](#defineenum) [from](#from) [tryFrom](#tryfrom)
|
|
985
|
+
[cases](#cases) [defineEnum](#defineenum) [from](#from) [keys](#keys) [tryFrom](#tryfrom) [values](#values)
|
|
887
986
|
|
|
888
987
|
#### `cases`
|
|
889
988
|
|
|
@@ -928,6 +1027,19 @@ const result = from(Status, "active");
|
|
|
928
1027
|
from(Status, "non-valid-key"); // throws
|
|
929
1028
|
```
|
|
930
1029
|
|
|
1030
|
+
#### `keys`
|
|
1031
|
+
|
|
1032
|
+
Like `array_column(Color::cases(), 'name')` in PHP, `keys` returns the enum's case names in case order, typed as a union of those names:
|
|
1033
|
+
|
|
1034
|
+
```typescript
|
|
1035
|
+
import { keys } from "@tolki/ts";
|
|
1036
|
+
import { Color } from "@js/types/data/app/enums";
|
|
1037
|
+
|
|
1038
|
+
keys(Color); // ['Red', 'Green', 'Blue']
|
|
1039
|
+
```
|
|
1040
|
+
|
|
1041
|
+
Like `values`, `keys` reads the `_cases` list and returns an empty array without `enums.metadata_enabled`.
|
|
1042
|
+
|
|
931
1043
|
#### `tryFrom`
|
|
932
1044
|
|
|
933
1045
|
Like PHP's [tryFrom](https://www.php.net/manual/en/backedenum.tryfrom.php), `tryFrom` works like `from` but returns `null` for a value that matches no case:
|
|
@@ -940,6 +1052,21 @@ const result = tryFrom(Status, "active");
|
|
|
940
1052
|
const missing = tryFrom(Status, "non-valid-key"); // null
|
|
941
1053
|
```
|
|
942
1054
|
|
|
1055
|
+
#### `values`
|
|
1056
|
+
|
|
1057
|
+
Like `array_column(Color::cases(), 'value')` in PHP, `values` returns the enum's case values in case order, typed as its `{Name}Type` union:
|
|
1058
|
+
|
|
1059
|
+
```typescript
|
|
1060
|
+
import { values } from "@tolki/ts";
|
|
1061
|
+
import { Color } from "@js/types/data/app/enums";
|
|
1062
|
+
|
|
1063
|
+
values(Color); // ['red', 'green', 'blue']
|
|
1064
|
+
```
|
|
1065
|
+
|
|
1066
|
+
A unit enum publishes each case name as its value, so `values` returns its case names. PHP's `array_column()` returns an empty array for a unit enum.
|
|
1067
|
+
|
|
1068
|
+
`values` and `keys` read the `_cases` list, so they need `enums.metadata_enabled` and return an empty array without it. `defineEnum()` doesn't add `values` or `keys` to the enum. An enum that publishes its own `values()` or `keys()` static method keeps that published value under the name, so `Status.values` is the static method's published output while `values(Status)` returns the case values.
|
|
1069
|
+
|
|
943
1070
|
### Vite Plugin
|
|
944
1071
|
|
|
945
1072
|
The `@tolki/ts` package ships a Vite plugin that republishes enums and routes automatically during development. See the [Vite Plugin documentation](https://tolki.abe.dev/ts/vite-plugin.html).
|
|
@@ -956,6 +1083,7 @@ The runtime functions come from `@tolki/ts`. The types come from `@tolki/types`,
|
|
|
956
1083
|
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
957
1084
|
| `defineEnum()` | Wraps a raw enum const with bound `from`, `tryFrom` and `cases` helpers. |
|
|
958
1085
|
| `from()`, `tryFrom()`, `cases()` | Standalone versions that take the enum object as their first argument. |
|
|
1086
|
+
| `values()`, `keys()` | The case values, or the case names, in case order. |
|
|
959
1087
|
| `EnumConst` | The base shape every generated enum const satisfies. |
|
|
960
1088
|
| `CaseKeys<T>` / `CaseValue<T>` | The union of case key names, or of case values, for an enum const. |
|
|
961
1089
|
| `MethodKeys<T>` / `StaticKeys<T>` | The union of instance method key names, or of static method key names. |
|
|
@@ -975,7 +1103,7 @@ The `ts:publish` command publishes each model as follows:
|
|
|
975
1103
|
|
|
976
1104
|
- **One file per model**: `App\Models\User` is written to `app/models/user.ts`, following the model's namespace. Each namespace directory also gets an `index.ts` barrel that re-exports its files (`export * from './user'`), the same as [enums](https://tolki.abe.dev/ts/enums.html#how-enums-are-generated).
|
|
977
1105
|
- **Split interfaces**: columns, accessors and relations go into separate interfaces by default. See [Model Templates](#model-templates).
|
|
978
|
-
- **Column types**: a column's type comes from the first source that applies. In order, those are a [`#[TsCasts]`](#tscasts) entry, an accessor with the column's name, the model's cast in `casts()` or `$casts`, and the database column type. A custom cast class can set its own type with [`#[TsType]`](#
|
|
1106
|
+
- **Column types**: a column's type comes from the first source that applies. In order, those are a [`#[TsCasts]`](#tscasts) entry, an accessor with the column's name, the model's cast in `casts()` or `$casts`, and the database column type. A custom cast class can set its own type with [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html#model-attributes-and-casts). When the result is still vague, such as `unknown[]`, a class-level `@property` tag refines it. The [Type Mapping Reference](#type-mapping-reference) lists the default types.
|
|
979
1107
|
- **Accessors**: new-style `Attribute` accessors and old-style `get{Name}Attribute()` methods that aren't columns publish as mutators, typed from their return types, their docblocks or what their getters return.
|
|
980
1108
|
- **Relations**: each relation publishes, plus a `_count` and an `_exists` property for it.
|
|
981
1109
|
- **Metadata companions**: an opt-in feature writes a runtime `{model}_meta.ts` file beside the interface. See [Model Metadata](https://tolki.abe.dev/ts/model-metadata.html).
|
|
@@ -1255,11 +1383,11 @@ A relation's `_count` and `_exists` properties follow the same rule. When a colu
|
|
|
1255
1383
|
|
|
1256
1384
|
All attributes live in the `AbeTwoThree\LaravelTsPublish\Attributes` namespace.
|
|
1257
1385
|
|
|
1258
|
-
| Attribute | Target | Description
|
|
1259
|
-
| -------------- | --------------------------------------------------- |
|
|
1260
|
-
| `#[TsCasts]` | `casts()` method, `$casts` property, or model class | Override or add TypeScript types for columns, mutators or relations.
|
|
1261
|
-
| `#[TsType]` |
|
|
1262
|
-
| `#[TsExclude]` | Model class, accessor method, or relation method | Exclude a whole model, or one accessor or relation.
|
|
1386
|
+
| Attribute | Target | Description |
|
|
1387
|
+
| -------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------- |
|
|
1388
|
+
| `#[TsCasts]` | `casts()` method, `$casts` property, or model class | Override or add TypeScript types for columns, mutators or relations. |
|
|
1389
|
+
| `#[TsType]` | Any class, such as a custom cast class | Set the TypeScript type of every value of the class, or of every column that uses the cast. |
|
|
1390
|
+
| `#[TsExclude]` | Model class, accessor method, or relation method | Exclude a whole model, or one accessor or relation. |
|
|
1263
1391
|
|
|
1264
1392
|
#### `#[TsCasts]`
|
|
1265
1393
|
|
|
@@ -1304,39 +1432,7 @@ Put `#[TsCasts]` on `casts()` or `$casts`, so the TypeScript type sits next to t
|
|
|
1304
1432
|
|
|
1305
1433
|
#### `#[TsType]`
|
|
1306
1434
|
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
```php
|
|
1310
|
-
use AbeTwoThree\LaravelTsPublish\Attributes\TsType;
|
|
1311
|
-
|
|
1312
|
-
#[TsType(['type' => 'ProductDimensions', 'import' => '@js/types/product'])]
|
|
1313
|
-
class ProductDimensionsCast implements CastsAttributes
|
|
1314
|
-
{
|
|
1315
|
-
public function get($model, string $key, $value, array $attributes) { /* ... */ }
|
|
1316
|
-
}
|
|
1317
|
-
|
|
1318
|
-
class Product extends Model
|
|
1319
|
-
{
|
|
1320
|
-
public function casts(): array
|
|
1321
|
-
{
|
|
1322
|
-
return ['dimensions' => ProductDimensionsCast::class];
|
|
1323
|
-
}
|
|
1324
|
-
}
|
|
1325
|
-
```
|
|
1326
|
-
|
|
1327
|
-
Every column that uses the cast publishes with that type:
|
|
1328
|
-
|
|
1329
|
-
```typescript
|
|
1330
|
-
import type { ProductDimensions } from "@js/types/product";
|
|
1331
|
-
|
|
1332
|
-
export interface Product {
|
|
1333
|
-
dimensions: ProductDimensions;
|
|
1334
|
-
}
|
|
1335
|
-
```
|
|
1336
|
-
|
|
1337
|
-
`#[TsType]` also takes a plain string, such as `#[TsType('{width: number, height: number}')]`, when the type needs no import. Without `#[TsType]`, a custom cast publishes the return type of its `get()` method. A cast class that implements `SerializesCastableAttributes`, including one a `Castable` value object names, publishes the return type of its `serialize()` method instead, because that's what Laravel sends when it converts the model to JSON.
|
|
1338
|
-
|
|
1339
|
-
When `get()`'s native type is missing or vague, such as a bare `array`, the `@return` docblock sets the type, so `@return list<LegDto>` publishes a list of `LegDto`'s public properties, the shape `json_encode()` writes. A `@return` that names a model, such as `list<User>`, or another class that doesn't publish as an inline shape keeps `unknown[]`. A `get()` that declares neither publishes `unknown`.
|
|
1435
|
+
Put `#[TsType]` on a custom cast class, or on any class a column holds, to set the column's type. [Custom Types](https://tolki.abe.dev/ts/custom-types.html) describes the attribute.
|
|
1340
1436
|
|
|
1341
1437
|
### Laravel 13 Model Attributes
|
|
1342
1438
|
|
|
@@ -1365,7 +1461,7 @@ Most columns and accessors type themselves. When one publishes `unknown` or `unk
|
|
|
1365
1461
|
2. A class-level `@property` or `@property-read` tag, including one that uses a `@phpstan-type` or `@phpstan-import-type` alias.
|
|
1366
1462
|
3. A `@return MorphTo<A|B, $this>` generic on a `morphTo()` relation.
|
|
1367
1463
|
|
|
1368
|
-
PHPStan and Larastan read all of them, so the annotation that fixes your TypeScript is also checked by static analysis, and the package reads them with no configuration. `#[TsCasts]` is still the right tool when a shape's keys are built at runtime, or when the type belongs to the frontend and needs its own import. The [Annotation Checklist](#annotation-checklist) lists each case by symptom.
|
|
1464
|
+
PHPStan and Larastan read all of them, so the annotation that fixes your TypeScript is also checked by static analysis, and the package reads them with no configuration. When a docblock has more than one tag of a kind, the package reads them in PHPStan's order: `@phpstan-return`, then `@psalm-return`, then `@return`, and the same for `@var`, `@param`, `@property` and `@use`. A prefixed tag that's vague, such as `@phpstan-return array<string, mixed>`, yields to a precise plain tag. `#[TsCasts]` is still the right tool when a shape's keys are built at runtime, or when the type belongs to the frontend and needs its own import. The [Annotation Checklist](#annotation-checklist) lists each case by symptom.
|
|
1369
1465
|
|
|
1370
1466
|
#### Accessor Getter Bodies
|
|
1371
1467
|
|
|
@@ -1405,7 +1501,7 @@ export interface ReleaseMutators {
|
|
|
1405
1501
|
}
|
|
1406
1502
|
```
|
|
1407
1503
|
|
|
1408
|
-
The package reads `Attribute::make()`, `Attribute::get()`, `new Attribute(get: ...)` and old-style `get{Name}Attribute()` bodies. An accessor declared in a trait is read against the model that uses the trait. A method the getter calls is read the same way: `channelOptions()` returns `static::channelLabels()`, whose signature is a bare `: array`, and still publishes `{ "1": string; "2": string }`. A getter that returns an untyped property is typed from the property's default
|
|
1504
|
+
The package reads `Attribute::make()`, `Attribute::get()`, `new Attribute(get: ...)` and old-style `get{Name}Attribute()` bodies. An accessor declared in a trait is read against the model that uses the trait. A method the getter calls is read the same way: `channelOptions()` returns `static::channelLabels()`, whose signature is a bare `: array`, and still publishes `{ "1": string; "2": string }`. A getter that returns an untyped property is typed from the property's default joined with what the class and its children write to it, so `channels()`, which returns `protected $allowedChannels`, publishes `string[]` when nothing writes it.
|
|
1409
1505
|
|
|
1410
1506
|
A specific return type or `Attribute<Get, Set>` generic is always read first, so the getter body never overrides an accurate annotation. When the getter can't be typed, the accessor keeps the type from its signature or docblock, or publishes `unknown` if it has neither. That happens when the getter:
|
|
1411
1507
|
|
|
@@ -1419,9 +1515,15 @@ A specific return type or `Attribute<Get, Set>` generic is always read first, so
|
|
|
1419
1515
|
|
|
1420
1516
|
The `null` case keeps a getter from publishing a type that's plainly wrong: `fn ($value, array $attributes) => $attributes['title'] ?? null` publishes `unknown`, not `null`, because its real value is the title.
|
|
1421
1517
|
|
|
1518
|
+
A getter closure with no native return type takes its type from a `@return` docblock written just before it, so `Attribute::get(/** @return int */ fn () => json_decode($this->stats_json))` publishes `number`. The package reads that docblock only when it can't type what the getter returns, and ignores a vague one, such as `@return mixed`.
|
|
1519
|
+
|
|
1520
|
+
A getter that reads an attribute through `getAttribute()` or `getAttributeValue()` with a literal name takes the attribute's type, so `Attribute::get(fn () => $this->getAttribute('title'))` publishes `string`, as `fn () => $this->title` does.
|
|
1521
|
+
|
|
1522
|
+
Laravel runs an accessor's getter for a `NULL` column too, so an accessor on a nullable column publishes `| null` only where its getter can return `null`. A getter whose native return type is non-null, such as `fn (?string $value): array => …`, publishes no `| null`. One whose native return type allows `null`, such as `: ?array`, always publishes it, even when its `Attribute<…>` docblock leaves the `null` out.
|
|
1523
|
+
|
|
1422
1524
|
#### Typing `array` Casts With `@property`
|
|
1423
1525
|
|
|
1424
|
-
A column cast to `'array'`, or to any cast with no more specific type, publishes as `unknown[]`. Instead of `#[TsCasts]`, add a class-level `@property` or `@property-read` tag with the real shape. It's the same tag PHPStan and Larastan read:
|
|
1526
|
+
A column cast to `'array'`, or to any cast with no more specific type, publishes as `unknown[]`. Laravel sends the decoded JSON as it is, so a column holding an object, such as `{"theme":"dark"}`, is sent as that object, which `unknown[]` doesn't describe. The same holds for `collection` and `AsCollection` casts. Instead of `#[TsCasts]`, add a class-level `@property` or `@property-read` tag with the real shape. It's the same tag PHPStan and Larastan read:
|
|
1425
1527
|
|
|
1426
1528
|
```php
|
|
1427
1529
|
/**
|
|
@@ -1441,7 +1543,7 @@ A tag applies only when the column's own type is vague. It never overrides a spe
|
|
|
1441
1543
|
|
|
1442
1544
|
A tag that is still partly vague is used when it's more specific than the type it replaces. `@property array<string, mixed>|null $settings` turns a plain `'array'` cast into `Record<string, unknown> | null`: the type still names `unknown`, but it beats `unknown[] | null`. A tag that is exactly as vague as the original is ignored: `unknown`, `unknown[]`, `object`, or the `unknown[] | Record<string, unknown>` of a bare collection.
|
|
1443
1545
|
|
|
1444
|
-
The package also reads `@property` tags on the traits the model and its parents use, and on the traits those traits use. A trait that supplies an accessor can document it that way. The `$`-less form some packages use, `@property string[] labels`, works as long as nothing follows the property name.
|
|
1546
|
+
The package also reads `@property` tags on the traits the model and its parents use, and on the traits those traits use. A trait that supplies an accessor can document it that way. A class a trait's docblocks name resolves through the trait file's imports, not the model's, and so does the `@var` of a property the trait declares. The `$`-less form some packages use, `@property string[] labels`, works as long as nothing follows the property name.
|
|
1445
1547
|
|
|
1446
1548
|
#### Typing JSON Columns With `@phpstan-type` Aliases
|
|
1447
1549
|
|
|
@@ -1516,16 +1618,18 @@ A docblock intersection resolves each member and joins them with `&`:
|
|
|
1516
1618
|
protected function assignedUsers(): Attribute
|
|
1517
1619
|
```
|
|
1518
1620
|
|
|
1519
|
-
|
|
1621
|
+
Both classes keep their types, and the file imports both:
|
|
1520
1622
|
|
|
1521
1623
|
```typescript
|
|
1624
|
+
import type { TaskAssignment, User } from ".";
|
|
1625
|
+
|
|
1522
1626
|
export interface ProjectMutators {
|
|
1523
|
-
assigned_users: (User & { pivot:
|
|
1627
|
+
assigned_users: (User & { pivot: TaskAssignment })[];
|
|
1524
1628
|
// …
|
|
1525
1629
|
}
|
|
1526
1630
|
```
|
|
1527
1631
|
|
|
1528
|
-
A
|
|
1632
|
+
A model or an enum inside a docblock shape keeps its type at any depth, as `TaskAssignment` does here. Two kinds of shape publish each model and enum in them as `unknown`: one that also names another class, such as an API resource, and one that spells a class's name as a string literal or a key, as in `array{kind: 'User', owner: User}`. A member that can't be resolved is dropped from the intersection, instead of turning the whole type into `unknown`, since `A & B` is assignable to `A`.
|
|
1529
1633
|
|
|
1530
1634
|
#### Trait `@template` Bindings
|
|
1531
1635
|
|
|
@@ -1555,7 +1659,19 @@ export interface ProjectMutators {
|
|
|
1555
1659
|
}
|
|
1556
1660
|
```
|
|
1557
1661
|
|
|
1558
|
-
PHPStan reads the `@use` tag for the same purpose, so static analysis checks the binding too.
|
|
1662
|
+
PHPStan reads the `@use` tag for the same purpose, so static analysis checks the binding too. The trait's name in the tag resolves through the file's imports, then the model's namespace, so a trait declared beside the model needs no `use` import.
|
|
1663
|
+
|
|
1664
|
+
#### Custom Cast Classes
|
|
1665
|
+
|
|
1666
|
+
A custom cast without [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) publishes the return type of its `get()` method. When the cast class has a `serialize()` method, including one a `Castable` value object names, Laravel sends what `serialize()` returns when it converts the model to JSON, with or without the `SerializesCastableAttributes` interface. The column then publishes:
|
|
1667
|
+
|
|
1668
|
+
- **No declared type, or `mixed`**: the type its `return` statements prove, so `return (string) $value;` publishes `string`. Where they prove none, the column keeps `get()`'s type, except a `mixed` `serialize()` on a cast that implements the interface, which publishes `unknown | null`.
|
|
1669
|
+
- **A bare `array` or `object`, on a cast without the interface**: `get()`'s type, where `get()` returns a value object or an array shape. `?object` and `array|object` work the same way. Over a scalar `get()`, a bare `array` publishes `unknown[] | Record<string, unknown>`.
|
|
1670
|
+
- **Any other declared type**: that type, such as `string`.
|
|
1671
|
+
|
|
1672
|
+
Laravel calls `get()` for a `NULL` column too, so a nullable column cast to a class whose `get()` declares a non-null return type publishes no `| null`. For a `coordinate_data` column that may be `NULL`, cast with a `get()` that always returns a `Coordinate`, the model publishes `coordinate_data: { lat: number; lng: number }`. Laravel sends a `null` from `get()` without calling `serialize()`, so a `get()` that declares a nullable return type, or returns `null` itself, adds `| null` to the `serialize()` type.
|
|
1673
|
+
|
|
1674
|
+
When `get()`'s native type is missing or vague, such as a bare `array`, the `@return` docblock sets the type, so `@return list<LegDto>` publishes a list of `LegDto`'s public properties, the shape `json_encode()` writes. A `@return` that names a model, such as `list<User>`, or another class that doesn't publish as an inline shape keeps `unknown[]`. A `get()` that declares neither publishes `unknown`.
|
|
1559
1675
|
|
|
1560
1676
|
#### Typing Castable-With-Arguments Casts
|
|
1561
1677
|
|
|
@@ -1661,7 +1777,9 @@ final readonly class ShippingOptions implements Arrayable
|
|
|
1661
1777
|
}
|
|
1662
1778
|
```
|
|
1663
1779
|
|
|
1664
|
-
An accessor or cast that returns this DTO publishes as `{ carrier: string; insured: boolean; trackingUrl: string | null }`. Nullable properties keep their `| null`. Private, protected and static properties are left out, because `(array) $this` doesn't include them. A property typed as
|
|
1780
|
+
An accessor or cast that returns this DTO publishes as `{ carrier: string; insured: boolean; trackingUrl: string | null }`. Nullable properties keep their `| null`. Private, protected and static properties are left out, because `(array) $this` doesn't include them. A property typed as an enum or a published model publishes that type, and the file imports it, so `public Status $status` publishes `status: StatusType`. A property whose class has or inherits a [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) publishes that type, with its import.
|
|
1781
|
+
|
|
1782
|
+
A promoted property with no `@var` takes its type from the constructor's `@param`, as PHPStan reads it. So a constructor documented `@param list<string> $stops` publishes its promoted `public array $stops` as `stops: string[]` instead of `unknown[]`.
|
|
1665
1783
|
|
|
1666
1784
|
Optional is separate from nullable. A property that is neither promoted nor given a default value publishes as an optional key. Add `public string $summary;` to the class body above, assigned in the constructor, and it publishes as `summary?: string`. PHP leaves an unassigned typed property out of `(array) $this`, and the package can't tell whether the constructor always assigns it. To keep the key required, promote the property, or give it a default value on a DTO that isn't `readonly`. A `@return array{...}` docblock on `toArray()` always wins, so add one when the properties don't tell the whole story.
|
|
1667
1785
|
|
|
@@ -1779,7 +1897,7 @@ To change how a type publishes everywhere, add it to `custom_ts_mappings`. Keys
|
|
|
1779
1897
|
|
|
1780
1898
|
To see which entry a cast, a column or a date follows, read [`custom_ts_mappings`](https://tolki.abe.dev/ts/configuration-reference.html#custom-ts-mappings) in the Configuration Reference.
|
|
1781
1899
|
|
|
1782
|
-
To change one property instead of every column of a type, use [`#[TsCasts]`](#tscasts) or [`#[TsType]`](
|
|
1900
|
+
To change one property instead of every column of a type, use [`#[TsCasts]`](#tscasts) or [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html).
|
|
1783
1901
|
|
|
1784
1902
|
### Type Mapping Reference
|
|
1785
1903
|
|
|
@@ -1827,11 +1945,11 @@ The `unknown[]` collection row is the bare form. `AsEnumCollection::of(...)`, `A
|
|
|
1827
1945
|
|
|
1828
1946
|
A parameterized docblock generic in `@return`, `@property` or `Attribute<>` publishes a more specific type, based on its key type. Every container behaves the same way for a given key type:
|
|
1829
1947
|
|
|
1830
|
-
| Key type
|
|
1831
|
-
|
|
|
1832
|
-
| `int`, or omitted
|
|
1833
|
-
| `string`
|
|
1834
|
-
| `array-key`, `mixed` | `X[] \| Record<string, X>` | `array<…>`, `iterable<…>`, `Collection<…>` |
|
|
1948
|
+
| Key type | Emitted | Containers |
|
|
1949
|
+
| ----------------------------------- | -------------------------- | ----------------------------------------------------- |
|
|
1950
|
+
| `int`, or omitted | `X[]` | `list<X>`, `array<…>`, `iterable<…>`, `Collection<…>` |
|
|
1951
|
+
| `string` | `Record<string, X>` | `array<…>`, `iterable<…>`, `Collection<…>` |
|
|
1952
|
+
| `int\|string`, `array-key`, `mixed` | `X[] \| Record<string, X>` | `array<…>`, `iterable<…>`, `Collection<…>` |
|
|
1835
1953
|
|
|
1836
1954
|
`list<X>` has no key type, so it always publishes as `X[]`. A container with no generic at all, such as a bare `Collection`, uses the [Arrays & Objects](#arrays--objects) table above instead.
|
|
1837
1955
|
|
|
@@ -2033,6 +2151,46 @@ Point `model_metadata.provider_class` at your class. The published config ships
|
|
|
2033
2151
|
|
|
2034
2152
|
Prefer a precise `@return array{...}` shape. PHPStan or Psalm checks the contract, and the package publishes the same shape. The published config names no classes of its own. Every `*_class` key, `provider_class` included, is a commented line that shows what you can swap, and the default applies in code.
|
|
2035
2153
|
|
|
2154
|
+
Your provider can inherit `provide()` from a base class, or take it from a trait. The package reads it as PHP runs it on the provider that `provider_class` names. `$this->` and `static::` reach that provider, and `self::` reaches the class that declares `provide()`, which for a trait is the class that uses it:
|
|
2155
|
+
|
|
2156
|
+
```php
|
|
2157
|
+
abstract class BaseModelMetadataProvider implements ModelMetadataProvider
|
|
2158
|
+
{
|
|
2159
|
+
public function provide(Model $model): array
|
|
2160
|
+
{
|
|
2161
|
+
return [
|
|
2162
|
+
'morphClass' => (string) $model->getMorphClass(),
|
|
2163
|
+
'channel' => $this->channel($model),
|
|
2164
|
+
];
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
protected function channel(Model $model): ?string
|
|
2168
|
+
{
|
|
2169
|
+
return null;
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
|
|
2173
|
+
final class AppModelMetadataProvider extends BaseModelMetadataProvider
|
|
2174
|
+
{
|
|
2175
|
+
protected function channel(Model $model): string
|
|
2176
|
+
{
|
|
2177
|
+
return $model->getTable().'.updates';
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
```
|
|
2181
|
+
|
|
2182
|
+
With `provider_class` set to `AppModelMetadataProvider`, `channel` publishes the override's `string`, not the base class's `string | null`:
|
|
2183
|
+
|
|
2184
|
+
```typescript
|
|
2185
|
+
export const UserModelMetadata = {
|
|
2186
|
+
morphClass: "App\\Models\\User",
|
|
2187
|
+
channel: "users.updates",
|
|
2188
|
+
} as const satisfies {
|
|
2189
|
+
morphClass: string;
|
|
2190
|
+
channel: string;
|
|
2191
|
+
};
|
|
2192
|
+
```
|
|
2193
|
+
|
|
2036
2194
|
### How Each Key Is Typed
|
|
2037
2195
|
|
|
2038
2196
|
Each returned key's TypeScript type comes from the first of these that applies:
|
|
@@ -2042,13 +2200,14 @@ Each returned key's TypeScript type comes from the first of these that applies:
|
|
|
2042
2200
|
3. **The method body**: the package reads the returned array literal, with `$model` typed as its declared class. These need no annotation:
|
|
2043
2201
|
- Scalars, casts such as `(string) …`, and nested inline arrays
|
|
2044
2202
|
- Calls on `$model` whose Laravel signature or docblock declares a return type, such as `getTable()`, `getKeyName()`, `getRouteKeyName()` and `getMorphClass()`, which all publish as `string`
|
|
2045
|
-
- Enum values, including a case written inline such as `'status' => Status::Active`, which import their `{Name}Type` alias from the generated enums, the same as a `#[TsCasts]` import would
|
|
2203
|
+
- Enum values, including a case written inline such as `'status' => Status::Active`, which import their `{Name}Type` alias from the generated enums, the same as a `#[TsCasts]` import would. Two enums with the same class name are imported under aliases, such as `StatusType as CrmStatusType`, and so are their `{Name}Kind` aliases
|
|
2204
|
+
- An `instanceof` test on `$model`, which narrows it where the test holds, and relation calls that the query answers, as in `$model instanceof Post ? $model->comments()->count() : null`, which publishes `number | null`
|
|
2046
2205
|
|
|
2047
|
-
When the body's type for a key still contains `unknown`, the package ignores it, and the key needs a docblock or `#[TsCasts]` type. A helper with no declared return type, such as `private function tableFor($model)`, is that case.
|
|
2206
|
+
When the body's type for a key still contains `unknown`, the package ignores it, and the key needs a docblock or `#[TsCasts]` type. A helper with no declared return type, such as `private function tableFor($model)`, is that case. Inside a ternary or another union, a value the body can't type is left out instead, as in an API resource. See [Values Left Out of a Union](https://tolki.abe.dev/ts/api-resources.html#values-left-out-of-a-union).
|
|
2048
2207
|
|
|
2049
2208
|
Marking a key optional decides whether the payload has to return it, not how the key is written once it's returned. The `satisfies` type lists exactly the keys the payload returned, each one required.
|
|
2050
2209
|
|
|
2051
|
-
Two kinds of value
|
|
2210
|
+
An enum named in the docblock is imported from the generated enums, at any depth, so `pair: array{role: Role}` publishes `pair: { role: RoleType }`. So is one named in a `#[TsCasts]` entry with no `import`, when the key's value holds that enum. Two kinds of value still need a `#[TsCasts]` entry with an `import`. The first is any other class the docblock names at any depth, such as a model or an API resource, because a docblock string carries no import path. The second is a model or a resource the method body returns, because a metadata value doesn't have to match either interface, so the package never imports one for it. Without the entry, the companion fails, and the error names the model, the key and its type.
|
|
2052
2211
|
|
|
2053
2212
|
Every returned key must end up with a type, and every required key must be returned. Otherwise the companion fails, and the error names the model and the keys.
|
|
2054
2213
|
|
|
@@ -2225,8 +2384,8 @@ export interface WarehouseResource {
|
|
|
2225
2384
|
The package types most properties from the resource's backing Eloquent model, using its database columns, casts, accessors, and relations. It looks for that model in this order:
|
|
2226
2385
|
|
|
2227
2386
|
1. The `#[TsResource(model: User::class)]` attribute.
|
|
2228
|
-
2. A `@mixin
|
|
2229
|
-
3. The nearest parent class whose docblock has
|
|
2387
|
+
2. A `@mixin`, `@extends`, or `@property … $resource` tag in the resource's own docblock. The class name resolves through the file's `use` imports.
|
|
2388
|
+
3. The nearest parent class whose docblock has one of those tags.
|
|
2230
2389
|
4. A `$resource` property redeclared with a `@var` type, such as `/** @var User */ public $resource;`.
|
|
2231
2390
|
5. Laravel's naming convention in reverse, so `App\Http\Resources\UserResource` maps to `App\Models\User`.
|
|
2232
2391
|
6. A model whose `#[UseResource(UserResource::class)]` attribute names the resource. This attribute needs Laravel 12.29 or later.
|
|
@@ -2237,10 +2396,49 @@ Step 3 lets a subclass use its parent's model without repeating the docblock, wh
|
|
|
2237
2396
|
|
|
2238
2397
|
If no model resolves, a property read from the model, such as `$this->id`, publishes `unknown`.
|
|
2239
2398
|
|
|
2240
|
-
`$this->resource` holds the backing model, so a key that returns it whole publishes the model's interface. `'post' => $this->resource` publishes `post: Post`. If the resource
|
|
2399
|
+
`$this->resource` holds the backing model, so a key that returns it whole publishes the model's interface. `'post' => $this->resource` publishes `post: Post`. If the resource declares `$resource` as nullable, such as `/** @var Post|null */ public $resource;`, `?Post`, or `@extends JsonResource<Post|null>`, the key keeps that `null`: `post: Post | null`.
|
|
2241
2400
|
|
|
2242
2401
|
A `ResourceCollection` is backed by no model, whatever its docblock or `#[TsResource(model:)]` names, because its `$this->resource` holds the collected items. A model read in a collection, such as `$this->title`, publishes `unknown`. See [Reading `$this->resource`](#reading-this-resource).
|
|
2243
2402
|
|
|
2403
|
+
#### Resources That Wrap Other Classes
|
|
2404
|
+
|
|
2405
|
+
A resource can wrap a class that isn't a model, such as a value object. Name the class in an `@extends JsonResource<X>`, `@mixin X`, or `@property X $resource` tag, or redeclare `$resource` with `@var X`. Reads through `$this->resource` and through the resource itself then take the types that class declares:
|
|
2406
|
+
|
|
2407
|
+
```php
|
|
2408
|
+
/**
|
|
2409
|
+
* @extends JsonResource<PostStats>
|
|
2410
|
+
*/
|
|
2411
|
+
class StatsSummaryResource extends JsonResource
|
|
2412
|
+
{
|
|
2413
|
+
public function toArray(Request $request): array
|
|
2414
|
+
{
|
|
2415
|
+
return [
|
|
2416
|
+
'views' => $this->resource->views,
|
|
2417
|
+
'shares' => $this->shares,
|
|
2418
|
+
'summary' => $this->summary(),
|
|
2419
|
+
];
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
```
|
|
2423
|
+
|
|
2424
|
+
`PostStats` declares `public float $views`, `public int $shares`, and `summary(): string`, so the resource publishes:
|
|
2425
|
+
|
|
2426
|
+
```typescript
|
|
2427
|
+
export interface StatsSummaryResource {
|
|
2428
|
+
views: number;
|
|
2429
|
+
shares: number;
|
|
2430
|
+
summary: string;
|
|
2431
|
+
}
|
|
2432
|
+
```
|
|
2433
|
+
|
|
2434
|
+
A tag that names a class other than a model stops the naming-convention and `#[UseResource]` guesses, because the resource doesn't wrap a model. The guess stands only when the guessed model is an instance of the class the tag names, such as `@mixin Arrayable`, an interface every model implements. `#[TsResource(model:)]` always wins over the tag.
|
|
2435
|
+
|
|
2436
|
+
A tag that names no class the package can load, such as an IDE helper's `@mixin IdeHelperPost`, is skipped, and so is one that names `Model` itself or the `Eloquent` alias. The model the other steps find still applies.
|
|
2437
|
+
|
|
2438
|
+
A tag can also name an intersection of a model and an interface it implements. With `@extends JsonResource<Post&HasLabel>`, `$this->title` reads the `Post` column and `$this->label()` reads the method `HasLabel` declares, so both publish `string`.
|
|
2439
|
+
|
|
2440
|
+
A subclass that redeclares `$resource` with its own `@var` decides what an inherited `toArray()` reads, because PHP has only one `$resource` property.
|
|
2441
|
+
|
|
2244
2442
|
### Supported `toArray()` Patterns
|
|
2245
2443
|
|
|
2246
2444
|
These sections cover the Laravel resource features you use in `toArray()`. Each one shows the PHP you write and the TypeScript it produces.
|
|
@@ -2263,9 +2461,9 @@ name: string;
|
|
|
2263
2461
|
status: StatusType;
|
|
2264
2462
|
```
|
|
2265
2463
|
|
|
2266
|
-
`$this->resource->name` reads the same attribute, so it publishes the same type. A property you declare on the resource class itself, such as a promoted constructor parameter, takes its type from that declaration. It wins over a model attribute with the same name, as it does in PHP.
|
|
2464
|
+
`$this->resource->name` reads the same attribute, so it publishes the same type. A property you declare on the resource class itself, such as a promoted constructor parameter, takes its type from that declaration. It wins over a model attribute with the same name, as it does in PHP. A `@var` docblock on the property names classes through the imports of the file that declares it, so a property a trait declares uses the trait's imports. A promoted property with no `@var` takes its type from the constructor's `@param`, as PHPStan reads it.
|
|
2267
2465
|
|
|
2268
|
-
An untyped property
|
|
2466
|
+
An untyped property publishes its default's type joined with each value the resource, its parents, its traits, or its children write to it, so `protected $stage = Status::Draft;` publishes `StatusType`, and a protected or private one declared without a value, such as `protected $name;`, publishes `null`. Writes include element writes and writes inside a closure, typed by the closure's parameters and `use` imports, so `protected $sizes = ['small' => 1];` extended by `$this->sizes['large'] = 2;` publishes `{ small: number; large?: number }`. A write in a trait method the resource overrides doesn't count. The property publishes `unknown` when a write is a value from an untyped parameter, a by-reference call such as `sort($this->sizes)`, or an `unset()` of the whole property.
|
|
2269
2467
|
|
|
2270
2468
|
#### Conditional Methods
|
|
2271
2469
|
|
|
@@ -2316,6 +2514,8 @@ For `whenNotNull()` and `whenNull()`, the second argument is that default value,
|
|
|
2316
2514
|
'discount' => $this->whenNotNull($this->discount_percent, 0), // discount: number
|
|
2317
2515
|
```
|
|
2318
2516
|
|
|
2517
|
+
A closure or a first-class callable is never `null`, so `whenNotNull()` always includes the key and sends what the call returns, `null` included. Over a nullable `rating` column, `'rating' => $this->whenNotNull(fn () => $this->rating)` publishes `rating: string | null`.
|
|
2518
|
+
|
|
2319
2519
|
A default of the value's own type makes the property required without widening it. A default of another type, such as a string fallback for a number column, publishes a union of both.
|
|
2320
2520
|
|
|
2321
2521
|
An explicit `null` counts as a default, because Laravel checks whether you passed the argument, not what it holds. So `$this->whenLoaded('user', fn ($user) => $user, null)` is required, and it publishes `User | null` instead of `User`.
|
|
@@ -2357,11 +2557,11 @@ When you pass a closure as the value, its first parameter holds whatever Laravel
|
|
|
2357
2557
|
| `whenExistsLoaded()` | The relation's `{relation}_exists` flag, a `boolean` |
|
|
2358
2558
|
| `whenCounted()`, and `whenAggregated()` with the `count` function | The count, a `number` |
|
|
2359
2559
|
| `whenAggregated()` with any other function | The aggregate, never `null` |
|
|
2360
|
-
| `transform()` | The value you pass as its first argument
|
|
2361
|
-
| `when()`, `unless()`
|
|
2560
|
+
| `transform()` | The value you pass as its first argument, without `null`, since Laravel calls the closure only for a filled value |
|
|
2561
|
+
| `when()`, `unless()`, `whenNotNull()` | No value, since Laravel passes none. A closure that requires a parameter throws `ArgumentCountError` whenever Laravel calls it, and `ts:publish` warns about it. |
|
|
2362
2562
|
| `whenAppended()` | No value, since Laravel passes none |
|
|
2363
2563
|
|
|
2364
|
-
When Laravel passes no value, a parameter with a default holds that default's type.
|
|
2564
|
+
When Laravel passes no value, a parameter with a default holds that default's type. A default that builds a model holds that model, so `fn ($post = new Post) => $post->author?->name` publishes `string | null`.
|
|
2365
2565
|
|
|
2366
2566
|
The closure's return type becomes the property's type:
|
|
2367
2567
|
|
|
@@ -2370,7 +2570,7 @@ The closure's return type becomes the property's type:
|
|
|
2370
2570
|
'has_comments' => $this->whenExistsLoaded('comments', fn ($exists) => $exists), // has_comments?: boolean
|
|
2371
2571
|
```
|
|
2372
2572
|
|
|
2373
|
-
Here `author` is a relation that can't load `null`. When a relation is loaded as `null`, Laravel returns `null` without calling the closure, so a relation that can load `null` publishes `author_name?: string | null`. A `whenAggregated()` closure works the same way when its function is a string literal other than `'count'`, because SQL returns `NULL` for that aggregate over no rows. So `fn ($max) => ['max' => $max]` publishes `{ max: number } | null`, unless an accessor or `@property` on your model types the attribute without `null`. See [Nullable Relations](#nullable-relations) for which relations can load `null`.
|
|
2573
|
+
Here `author` is a relation that can't load `null`. When a relation is loaded as `null`, Laravel returns `null` without calling the closure, so a relation that can load `null` publishes `author_name?: string | null`. A `whenAggregated()` closure works the same way when its function is a string literal other than `'count'`, because SQL returns `NULL` for that aggregate over no rows. So `fn ($max) => ['max' => $max]` publishes `{ max: number } | null`, unless an accessor or `@property` on your model types the attribute without `null`. A closure that hands the relation to a resource's `collection()` adds `| null` only for a to-one relation that can load `null`. See [Nullable Relations](#nullable-relations) for which relations can load `null`.
|
|
2374
2574
|
|
|
2375
2575
|
##### `whenHas()`, `whenAppended()`, and `whenExistsLoaded()` Type From the Value You Pass
|
|
2376
2576
|
|
|
@@ -2399,7 +2599,17 @@ export interface PostResource {
|
|
|
2399
2599
|
}
|
|
2400
2600
|
```
|
|
2401
2601
|
|
|
2402
|
-
When the package can't type the value of `whenHas()` or `whenAppended()`, the property publishes `unknown`, not the attribute's type, because the value replaces the attribute in the response. `json_decode()` returns `mixed`, and a plain title decodes to `null`, so `title_unresolvable` is `unknown`. To type it, give the closure a native return type
|
|
2602
|
+
When the package can't type the value of `whenHas()` or `whenAppended()`, the property publishes `unknown`, not the attribute's type, because the value replaces the attribute in the response. `json_decode()` returns `mixed`, and a plain title decodes to `null`, so `title_unresolvable` is `unknown`. To type it, give the closure a native return type, or a `@return` docblock written just before the closure:
|
|
2603
|
+
|
|
2604
|
+
```php
|
|
2605
|
+
'title_typed' => $this->whenHas('title', fn ($title): ?string => json_decode($title)),
|
|
2606
|
+
'title_documented' => $this->whenHas('title',
|
|
2607
|
+
/** @return string|null */
|
|
2608
|
+
fn ($title) => json_decode($title),
|
|
2609
|
+
),
|
|
2610
|
+
```
|
|
2611
|
+
|
|
2612
|
+
Both properties publish `string | null`, and both stay optional. The package reads the docblock only on a closure with no native return type, and ignores a vague one, such as `@return mixed`. A docblock written before the whole call, or above the array item, describes the call's value rather than the closure, so it isn't read. To type the key itself, use [`#[TsCasts]`](#overriding-property-types-with-tscasts).
|
|
2403
2613
|
|
|
2404
2614
|
`whenExistsLoaded()` keeps `boolean` for a value it can't type. Without a value argument, `whenHas('phone')` types from its column, and `whenExistsLoaded('user')` publishes `boolean`.
|
|
2405
2615
|
|
|
@@ -2608,6 +2818,23 @@ visibility_from_helper: AsEnum<typeof Visibility> | null;
|
|
|
2608
2818
|
|
|
2609
2819
|
Wrapping a conditional value, as in `EnumResource::make($this->whenHas('status'))`, makes the property optional, as the conditional method alone would.
|
|
2610
2820
|
|
|
2821
|
+
`EnumResource::make(Status::tryFrom($value))` adds `| null`, because `tryFrom()` returns `null` for a value that matches no case. A `map()` that wraps each element is different: kept as a collection, it sends `[]` for an element whose enum is `null`. Laravel turns an empty `EnumResource` into `null` only inside an array, so end the chain with `->all()` to get `null` instead:
|
|
2822
|
+
|
|
2823
|
+
```php
|
|
2824
|
+
'roles' => $this->members
|
|
2825
|
+
->map(fn (User $user) => EnumResource::make($user->role)),
|
|
2826
|
+
'role_list' => $this->members
|
|
2827
|
+
->map(fn (User $user) => EnumResource::make($user->role))
|
|
2828
|
+
->all(),
|
|
2829
|
+
```
|
|
2830
|
+
|
|
2831
|
+
The two keys publish what each sends for a member with no role:
|
|
2832
|
+
|
|
2833
|
+
```typescript
|
|
2834
|
+
roles: (AsEnum<typeof Role> | never[])[];
|
|
2835
|
+
role_list: (AsEnum<typeof Role> | null)[];
|
|
2836
|
+
```
|
|
2837
|
+
|
|
2611
2838
|
A ternary that wraps only one of its arms keeps both shapes. The property publishes a union, with the import each side needs, even inside an inline array:
|
|
2612
2839
|
|
|
2613
2840
|
```php
|
|
@@ -2712,6 +2939,8 @@ $this->merge(function () {
|
|
|
2712
2939
|
|
|
2713
2940
|
The closure publishes `user_name?: string` and `user_email?: string`.
|
|
2714
2941
|
|
|
2942
|
+
A closure can also build its array in a variable and return it. The merge then publishes the keys that the variable's writes set, as [Building the Array in a Variable](#building-the-array-in-a-variable) describes. If an `unset()` that the package can't follow may remove one of its keys, the merge adds none of them. A variable the closure assigns is its own, even when the method has one with the same name.
|
|
2943
|
+
|
|
2715
2944
|
A merge can also take the resource's own model, `$this->resource`, or a call to one of the resource's methods, such as `$this->labelFields()`, passed as it is or returned from a closure:
|
|
2716
2945
|
|
|
2717
2946
|
```php
|
|
@@ -2743,19 +2972,78 @@ A closure or an arrow function in value position is typed from what it returns:
|
|
|
2743
2972
|
}),
|
|
2744
2973
|
```
|
|
2745
2974
|
|
|
2746
|
-
This works wherever a value goes, including `when()`, `whenLoaded()`, `whenNotNull()`, `merge()`, and `mergeWhen()`.
|
|
2975
|
+
This works wherever a value goes, including `when()`, `whenLoaded()`, `whenNotNull()`, `merge()`, and `mergeWhen()`. When the package can't type what a closure returns, the closure's native return type types the value, and so does a `@return` docblock on a closure with no native return type, as [`whenHas()`, `whenAppended()`, and `whenExistsLoaded()`](#whenhas-whenappended-and-whenexistsloaded-type-from-the-value-you-pass) shows.
|
|
2747
2976
|
|
|
2748
|
-
A
|
|
2977
|
+
A closure that builds an array in a variable and returns it publishes the keys its writes set, as [Building the Array in a Variable](#building-the-array-in-a-variable) describes:
|
|
2749
2978
|
|
|
2750
2979
|
```php
|
|
2751
|
-
'
|
|
2752
|
-
'
|
|
2753
|
-
|
|
2980
|
+
'summary' => $this->when($this->published_at !== null, function () {
|
|
2981
|
+
$summary = ['id' => $this->id];
|
|
2982
|
+
|
|
2983
|
+
if ($this->is_pinned) {
|
|
2984
|
+
$summary['flag'] = 'pinned';
|
|
2985
|
+
} else {
|
|
2986
|
+
$summary['flag'] = 0;
|
|
2987
|
+
}
|
|
2988
|
+
|
|
2989
|
+
return $summary;
|
|
2990
|
+
}),
|
|
2991
|
+
```
|
|
2992
|
+
|
|
2993
|
+
The property publishes `summary?: { id: number; flag: string | number }`.
|
|
2994
|
+
|
|
2995
|
+
A first-class callable, such as `$this->label(...)` or `UserResource::make(...)`, creates a closure. Where Laravel calls the value, as `when()`, `whenLoaded()`, `mergeWhen()` and the other conditional methods do, it publishes what the call returns, whether you pass the callable directly or through a local:
|
|
2996
|
+
|
|
2997
|
+
```php
|
|
2998
|
+
public function toArray(Request $request): array
|
|
2999
|
+
{
|
|
3000
|
+
$label = $this->label(...);
|
|
3001
|
+
|
|
3002
|
+
return [
|
|
3003
|
+
'label' => $this->when($request->has('label'), $label), // label?: string
|
|
3004
|
+
'supervisor' => $this->whenLoaded('supervisor', UserResource::make(...)), // supervisor?: UserResource | null
|
|
3005
|
+
'length' => strlen(...), // length: Record<string, never>
|
|
3006
|
+
$this->mergeWhen($request->has('stats'), $this->statFields(...)), // views?: number
|
|
3007
|
+
];
|
|
3008
|
+
}
|
|
3009
|
+
|
|
3010
|
+
/** @return array{views: int} */
|
|
3011
|
+
public function statFields(): array
|
|
3012
|
+
{
|
|
3013
|
+
return ['views' => 1];
|
|
3014
|
+
}
|
|
2754
3015
|
```
|
|
2755
3016
|
|
|
2756
3017
|
As a plain value, nothing calls it, and Laravel sends the `Closure` as `{}`, so a first-class callable there, like `length` above, publishes `Record<string, never>`. `ts:publish` warns about such a callable and names its line. Call the function instead, as in `'length' => strlen($this->name)`.
|
|
2757
3018
|
|
|
2758
|
-
|
|
3019
|
+
#### Values Left Out of a Union
|
|
3020
|
+
|
|
3021
|
+
When the package can't type one value of a union, it leaves that value out and publishes the others. Here `opaqueTags()` and `opaqueNote()` declare no return type and return something the package can't type:
|
|
3022
|
+
|
|
3023
|
+
```php
|
|
3024
|
+
'tags' => $this->is_published ? $this->opaqueTags() : [], // tags: never[]
|
|
3025
|
+
'note' => $this->is_published ? $this->opaqueNote() : null, // note: null
|
|
3026
|
+
```
|
|
3027
|
+
|
|
3028
|
+
The same happens to a `??`, a `match`, a write to a closure's or helper's parameter inside a block, and a key that one branch of a returned array writes, where the writes join, as [Local Variables and Narrowing](#local-variables-and-narrowing) describes. Some unions widen to `unknown` instead, such as a method you read as a value when one of its returns can't be typed.
|
|
3029
|
+
|
|
3030
|
+
When what's left is only `null`, an empty array, or both, the published type claims the value is always that. `ts:publish` prints a warning after its summary, naming the class, the line, and the value it left out:
|
|
3031
|
+
|
|
3032
|
+
```text
|
|
3033
|
+
App\Http\Resources\PostResource: The value on line 24 publishes `never[]`, an array that is always empty, because `$this->opaqueTags()` could not be typed and was left out of its union. Give what it reads a return type or a `@return` docblock.
|
|
3034
|
+
```
|
|
3035
|
+
|
|
3036
|
+
For a value left as `null`, the message reads "publishes `null`, as if it were always null", and for both, "publishes `null | never[]`, as if it were always null or an empty array".
|
|
3037
|
+
|
|
3038
|
+
A ternary or a `??` that leaves out a value beside a typed one raises no warning. A value left out where a parameter's writes, a returned array's branches, a merge's two sides or a spread helper's returns join raises one, because the published type may not cover everything Laravel sends:
|
|
3039
|
+
|
|
3040
|
+
```text
|
|
3041
|
+
App\Http\Resources\PostResource: The value on line 31 leaves out `$this->opaqueTitle()`, which could not be typed, so its published type may not admit every value it sends. Give what it reads a return type or a `@return` docblock.
|
|
3042
|
+
```
|
|
3043
|
+
|
|
3044
|
+
Give the method a return type or a `@return` docblock, and its value joins the union again. An inline [`@var`](#typing-a-variable-with-var) that types the variable also removes the warning. `--quiet` hides every warning.
|
|
3045
|
+
|
|
3046
|
+
`ts:publish` doesn't analyze a class again while the [generation cache](https://tolki.abe.dev/ts/generating-cache.html) holds it. A class the cache serves prints none of these warnings, nor the first-class callable warning above, so run `php artisan ts:publish --fresh` to see every one.
|
|
2759
3047
|
|
|
2760
3048
|
### Method Calls, Variables, and Collections
|
|
2761
3049
|
|
|
@@ -2763,7 +3051,7 @@ Values you compute in `toArray()` get types too: method calls, property reads on
|
|
|
2763
3051
|
|
|
2764
3052
|
#### Method Return Types
|
|
2765
3053
|
|
|
2766
|
-
A method call takes its type from the called method's signature: its native return type, or its `@return` docblock when the native type is missing or vague. This works for calls on enum casts, date casts, models, Eloquent collections, value objects, and services resolved from the container:
|
|
3054
|
+
A method call takes its type from the called method's signature: its native return type, or its `@return` docblock when the native type is missing or vague. When a method has more than one of `@phpstan-return`, `@psalm-return`, and `@return`, the package reads them in that order, as PHPStan does, and a vague one, such as `array<string, mixed>`, yields to a precise one. This works for calls on enum casts, date casts, models, Eloquent collections, value objects, and services resolved from the container:
|
|
2767
3055
|
|
|
2768
3056
|
```php
|
|
2769
3057
|
public function toArray(Request $request): array
|
|
@@ -2797,6 +3085,8 @@ export interface PostResource {
|
|
|
2797
3085
|
|
|
2798
3086
|
A property read works the same way. Once `$post` holds a `Post`, `$post?->author?->name` publishes `string | null`. A value object's public property takes its declared type, so `$this->stats?->views` publishes `number | null`. A `?->` adds `| null` to the result once, however many steps use it.
|
|
2799
3087
|
|
|
3088
|
+
A model or an enum named in a `@return` shape keeps its type at any depth, and the file imports it. A method documented `@return array{owner: User, count: int}` publishes `{ owner: User; count: number }`, whether you call it on the resource, on a service, or statically. Two kinds of shape publish each model and enum in them as `unknown`: one that also names another class, such as an API resource, and one that spells a class's name as a string literal or a key, as in `array{kind: 'User', owner: User}`.
|
|
3089
|
+
|
|
2800
3090
|
When the declaration says too little, as with no return type, `mixed`, or a bare `array`, the method's own `return` statements set the type:
|
|
2801
3091
|
|
|
2802
3092
|
```php
|
|
@@ -2844,10 +3134,12 @@ public function total(): mixed
|
|
|
2844
3134
|
}
|
|
2845
3135
|
```
|
|
2846
3136
|
|
|
2847
|
-
`$this->resource->total()` calls the model's method directly, so it publishes the model's type. When neither the resource method's declaration nor its body types the call, the key publishes `unknown`, never the model method's type. Give the method a return type to fix it. The same holds for a
|
|
3137
|
+
`$this->resource->total()` calls the model's method directly, so it publishes the model's type. When neither the resource method's declaration nor its body types the call, the key publishes `unknown`, never the model method's type. Give the method a return type to fix it. The same holds for a resource that [wraps a class other than a model](#resources-that-wrap-other-classes), such as one declared with `@extends JsonResource<CartTotals>` or `/** @var CartTotals */ public $resource;`. If `CartTotals` doesn't declare the method you call, the key publishes `unknown`, because Laravel throws there.
|
|
2848
3138
|
|
|
2849
3139
|
Some of Laravel's own methods declare loose types, so the package reads the model instead. `getKey()` publishes the model's key type, `number` or `string`, and `modelKeys()` publishes a list of it. That's why `comment_ids` above is `number[]`. `resolveRouteBinding()` publishes the model you call it on, or `null`, so `$this->author?->resolveRouteBinding($this->user_id)` publishes `User | null`.
|
|
2850
3140
|
|
|
3141
|
+
`getAttribute()` and `getAttributeValue()` with a literal name publish what reading the attribute as a property would. On a `Post` resource, `$this->getAttribute('title')` and `$this->resource->getAttributeValue('title')` publish `string`, as `$this->title` does, and `$this->resource->getAttribute('author')` publishes the relation's type, `User`. That works on a relation's model and a closure parameter too, so `$this->whenLoaded('author', fn ($author) => $author->getAttribute('name'))` publishes `string` as an optional property. A name the model doesn't declare publishes `unknown`, and so does a relation read through `getAttributeValue()`, which returns no relation.
|
|
3142
|
+
|
|
2851
3143
|
`getKey()` publishes the key type on any model the package can name, including one a variable holds, such as a `whenLoaded()` closure parameter, a `map()` element, or a helper's `Post $post` parameter. So `$this->comments->map(fn ($comment) => $comment->getKey())` publishes `number[]`.
|
|
2852
3144
|
|
|
2853
3145
|
A model that no database row backs yet has no key, so its `getKey()` adds `| null`. That covers a model you build with `new`, `replicate()`, `replicateQuietly()` or `newInstance()`, and one that a query, a relation or a factory builds without saving it:
|
|
@@ -2862,20 +3154,65 @@ A model that no database row backs yet has no key, so its `getKey()` adds `| nul
|
|
|
2862
3154
|
|
|
2863
3155
|
A call that returns the same model, such as `(new Post)->fill([...])`, keeps the `| null`. A helper's `Post $post` parameter adds it only where the call passes a model no row backs yet. The package doesn't follow `save()`, so a model you save after `new` still publishes `number | null`. On a model whose `$primaryKey` is `null`, `getKey()` publishes `null`.
|
|
2864
3156
|
|
|
3157
|
+
A model you build with `new` and no attributes holds no columns either, so Laravel sends `null` for each one, and a column read on it adds `| null`. `(new Post)->title` publishes `string | null`. A column you set keeps its type, whether you pass it to the constructor, `fill()` it, or write it, as in `$post->title = 'Draft'`. So does every column of a model from `replicate()`, `firstOrNew()` or a factory's `make()`. A relation, an accessor, and a column your model's `$attributes` gives a default publish their types as usual.
|
|
3158
|
+
|
|
2865
3159
|
On an abstract model, `getKey()` publishes the key type the class declares, through `$keyType`, `HasUuids`, `HasUlids` or Laravel 13's `#[Table]`, joined with the key type of each published model that extends it. So a base whose subclasses key by integer and by UUID publishes `number | string`. When the abstract model works its key out in code, such as in an overridden `getKeyType()`, `getKey()` publishes `unknown`.
|
|
2866
3160
|
|
|
2867
3161
|
`getAuthIdentifier()` on an authenticatable model publishes the type of the column the model identifies users by. That's the key type, or the type of the column a literal `getAuthIdentifierName()` returns, so a model whose `getAuthIdentifierName()` returns `'email'` publishes `string`. A model no row backs yet adds `| null`, and a model that overrides `getAuthIdentifier()` publishes the return type it declares.
|
|
2868
3162
|
|
|
2869
3163
|
A method that returns a plain PHP `DateTime` or `DateTimeImmutable` publishes `{ date: string; timezone_type: number; timezone: string }`, the object `json_encode()` writes for it. A Carbon date publishes `string`, or `Date` under `timestamps_as_date`, and so do the `now()` and `today()` helpers, which return one. A `DateTimeInterface` can hold either kind, so it publishes the Carbon date's type or that object, and a `CarbonPeriod` publishes a list of the Carbon date's type. A `CarbonInterval` publishes the `DateInterval` fields `json_encode()` writes for it, such as `y`, `m`, `d` and `days`. `str($value)` publishes `string`, and `str()` with no argument publishes `Record<string, never>`. `url($path)` publishes `string` when the path can't be `null`, and `unknown` when it can or has no type.
|
|
2870
3164
|
|
|
2871
|
-
A value built in place publishes what `json_encode()` writes for it as well, so `new DateTime()` publishes that date object and `new RuntimeException('x')` publishes `Record<string, never>`. `new Collection($items)` publishes as `collect($items)` does.
|
|
3165
|
+
A value built in place publishes what `json_encode()` writes for it as well, so `new DateTime()` publishes that date object and `new RuntimeException('x')` publishes `Record<string, never>`. `new Collection($items)` publishes as `collect($items)` does. `new stdClass`, and a method declared to return `stdClass`, publish `Record<string, unknown>`, because a `stdClass` can gain properties at run time.
|
|
3166
|
+
|
|
3167
|
+
These values stay `unknown` when built in place:
|
|
2872
3168
|
|
|
2873
3169
|
- An `Arrayable` or a `Responsable`
|
|
2874
3170
|
- An Inertia `ProvidesInertiaProperty` class
|
|
2875
3171
|
- A model
|
|
2876
|
-
- A class with no public property and no `__toString()
|
|
3172
|
+
- A class with no public property and no `__toString()`
|
|
2877
3173
|
|
|
2878
|
-
Type such a key with [`#[TsCasts]`](#overriding-property-types-with-tscasts).
|
|
3174
|
+
Type such a key with [`#[TsCasts]`](#overriding-property-types-with-tscasts), or give the class a [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html). A `new` of a class that has or inherits one publishes that type, unless the class is a model.
|
|
3175
|
+
|
|
3176
|
+
`array_values()` keeps the element type and publishes a list. An `(object)` cast publishes the object `json_encode()` writes: a shape keeps its keys, a list becomes a `Record` keyed by its indexes, and `(object) []` publishes `Record<string, never>`. An `(array)` cast of an array keeps the array's type:
|
|
3177
|
+
|
|
3178
|
+
```php
|
|
3179
|
+
public function toArray(Request $request): array
|
|
3180
|
+
{
|
|
3181
|
+
return [
|
|
3182
|
+
'tags' => array_values(array_filter($this->tags())),
|
|
3183
|
+
'count_list' => array_values($this->tagCounts()),
|
|
3184
|
+
'tag_counts' => (object) $this->tagCounts(),
|
|
3185
|
+
'tag_object' => (object) $this->tags(),
|
|
3186
|
+
'size' => (object) ['width' => 640, 'label' => 'large'],
|
|
3187
|
+
'counts' => (array) $this->tagCounts(),
|
|
3188
|
+
];
|
|
3189
|
+
}
|
|
3190
|
+
|
|
3191
|
+
/** @return list<string> */
|
|
3192
|
+
private function tags(): array
|
|
3193
|
+
{
|
|
3194
|
+
return explode(',', $this->title);
|
|
3195
|
+
}
|
|
3196
|
+
|
|
3197
|
+
/** @return array<string, int> */
|
|
3198
|
+
private function tagCounts(): array
|
|
3199
|
+
{
|
|
3200
|
+
return array_count_values($this->tags());
|
|
3201
|
+
}
|
|
3202
|
+
```
|
|
3203
|
+
|
|
3204
|
+
Each key publishes the list or object PHP sends:
|
|
3205
|
+
|
|
3206
|
+
```typescript
|
|
3207
|
+
export interface PostTagsResource {
|
|
3208
|
+
tags: string[];
|
|
3209
|
+
count_list: number[];
|
|
3210
|
+
tag_counts: Record<string, number>;
|
|
3211
|
+
tag_object: Record<string, string>;
|
|
3212
|
+
size: { width: number; label: string };
|
|
3213
|
+
counts: Record<string, number>;
|
|
3214
|
+
}
|
|
3215
|
+
```
|
|
2879
3216
|
|
|
2880
3217
|
A method that returns the base `Model` class, `Illuminate\Foundation\Auth\User`, an abstract model, or a model that isn't published, such as one in `models.excluded`, publishes `unknown`, because no published file has a type for it. Declare the concrete model as the return type, such as `: Order`, to type the value.
|
|
2881
3218
|
|
|
@@ -2921,12 +3258,13 @@ Outside a resource, such as in an Inertia page prop, `tiers` publishes `{ "1": s
|
|
|
2921
3258
|
|
|
2922
3259
|
A `?array` declaration keeps its `null`, so the method publishes the shape `| null`. An `array|false` declaration keeps its `false` the same way.
|
|
2923
3260
|
|
|
2924
|
-
What the body reads from the method's parameters is typed too, whether you use its result as a value or spread it. Each parameter holds its declared type, from the signature, or from a `@param` tag when the signature's type is missing or vague, such as `array`. A parameter with no type, or only `mixed`, holds what each call passes. A closure you pass is the exception: in `$this->hold(fn () => 5)`, the parameter holds `unknown`, because a resource sends a closure as `{}`. A first-class callable that Laravel calls gets the value Laravel calls it with, as in `whenLoaded()`:
|
|
3261
|
+
What the body reads from the method's parameters is typed too, whether you use its result as a value or spread it. Each parameter holds its declared type, from the signature, or from a `@param` tag when the signature's type is missing or vague, such as `array`. A parameter with no type, or only `mixed`, holds what each call passes, and a collection you pass keeps its model, so a read such as `$comments->first()?->content` is typed. A closure you pass is the exception: in `$this->hold(fn () => 5)`, the parameter holds `unknown`, because a resource sends a closure as `{}`. A first-class callable that Laravel calls gets the value Laravel calls it with, as in `whenLoaded()`:
|
|
2925
3262
|
|
|
2926
3263
|
```php
|
|
2927
3264
|
'card' => $this->card($this->resource), // card: { id: number; title: string }
|
|
2928
3265
|
'author_card' => $this->authorCard($this->author), // author_card: { name: string }
|
|
2929
3266
|
'loaded_card' => $this->whenLoaded('author', $this->authorCard(...)), // loaded_card?: { name: string }
|
|
3267
|
+
'first_comment' => $this->firstContent($this->comments), // first_comment: { first: string | null }
|
|
2930
3268
|
|
|
2931
3269
|
private function card(Post $post): array
|
|
2932
3270
|
{
|
|
@@ -2937,6 +3275,11 @@ private function authorCard($author): array
|
|
|
2937
3275
|
{
|
|
2938
3276
|
return ['name' => $author->name];
|
|
2939
3277
|
}
|
|
3278
|
+
|
|
3279
|
+
private function firstContent($comments): array
|
|
3280
|
+
{
|
|
3281
|
+
return ['first' => $comments->first()?->content];
|
|
3282
|
+
}
|
|
2940
3283
|
```
|
|
2941
3284
|
|
|
2942
3285
|
When the method can return something other than an array literal, apart from a `null`, boolean, string, or number literal its declaration allows, the package reads each `return` as a value instead, as [Method Return Types](#method-return-types) describes. So a method that returns a collection pipeline publishes its list:
|
|
@@ -2950,41 +3293,95 @@ private function contents(): array
|
|
|
2950
3293
|
}
|
|
2951
3294
|
```
|
|
2952
3295
|
|
|
2953
|
-
|
|
3296
|
+
The pipeline can also start at a relation of a model parameter, at a query's `get()`, or at a local holding either:
|
|
2954
3297
|
|
|
2955
|
-
|
|
3298
|
+
```php
|
|
3299
|
+
final class CommentRowsService
|
|
3300
|
+
{
|
|
3301
|
+
public function forPost(Post $post): array
|
|
3302
|
+
{
|
|
3303
|
+
return $post->comments->map(fn ($comment) => ['id' => $comment->id])->values()->all();
|
|
3304
|
+
}
|
|
2956
3305
|
|
|
2957
|
-
|
|
3306
|
+
public function unflagged(): array
|
|
3307
|
+
{
|
|
3308
|
+
$rows = Comment::query()->where('is_flagged', false)->get();
|
|
2958
3309
|
|
|
2959
|
-
|
|
3310
|
+
return $rows->map(fn ($comment) => ['id' => $comment->id])->all();
|
|
3311
|
+
}
|
|
3312
|
+
}
|
|
2960
3313
|
|
|
2961
|
-
|
|
2962
|
-
|
|
2963
|
-
|
|
3314
|
+
// in toArray():
|
|
3315
|
+
'post_rows' => resolve(CommentRowsService::class)->forPost($this->resource), // post_rows: { id: number }[]
|
|
3316
|
+
'unflagged_rows' => resolve(CommentRowsService::class)->unflagged(), // unflagged_rows: { id: number }[]
|
|
3317
|
+
```
|
|
2964
3318
|
|
|
2965
|
-
|
|
3319
|
+
A method that builds its array in a variable and returns it publishes the keys its writes set. Beside a `return` of another array, each `return` is one shape of a union:
|
|
3320
|
+
|
|
3321
|
+
```php
|
|
3322
|
+
'summary' => $this->summary($request), // summary: { id: number } | { id: number; title: string }
|
|
3323
|
+
|
|
3324
|
+
private function summary(Request $request): array
|
|
3325
|
+
{
|
|
3326
|
+
if ($request->boolean('short')) {
|
|
3327
|
+
return ['id' => $this->id];
|
|
3328
|
+
}
|
|
3329
|
+
|
|
3330
|
+
$data = ['id' => $this->id];
|
|
3331
|
+
$data['title'] = $this->title;
|
|
3332
|
+
|
|
3333
|
+
return $data;
|
|
3334
|
+
}
|
|
3335
|
+
```
|
|
3336
|
+
|
|
3337
|
+
If one `return` can't be typed, or the method yields, the property publishes `unknown`.
|
|
2966
3338
|
|
|
2967
|
-
|
|
3339
|
+
When you use the method's result as a value, its array publishes what the same expressions publish in `toArray()`. That includes models, API resources, and enums, and the file imports what they name. One value differs. A backed enum case you write out, such as `PostStatus::Draft`, publishes the value it sends, `0`, instead of the enum's alias. A list of such cases publishes a list of their values, such as `(0 | 1)[]`.
|
|
3340
|
+
|
|
3341
|
+
Here a `Post` casts `status` to the int-backed `PostStatus` enum, whose cases are `Draft = 0` and `Published = 1`, and `author` is a `BelongsTo` relation whose foreign key isn't nullable. The resource uses `card()` as a value:
|
|
2968
3342
|
|
|
2969
3343
|
```php
|
|
2970
|
-
|
|
2971
|
-
public function relationSummary(): array
|
|
3344
|
+
public function toArray(Request $request): array
|
|
2972
3345
|
{
|
|
2973
3346
|
return [
|
|
2974
|
-
'
|
|
2975
|
-
|
|
2976
|
-
|
|
2977
|
-
|
|
3347
|
+
'card' => $this->card(),
|
|
3348
|
+
];
|
|
3349
|
+
}
|
|
3350
|
+
|
|
3351
|
+
private function card(): array
|
|
3352
|
+
{
|
|
3353
|
+
return [
|
|
3354
|
+
'author' => $this->author,
|
|
3355
|
+
'status' => $this->status,
|
|
3356
|
+
'status_resource' => EnumResource::make($this->status),
|
|
3357
|
+
'first_status' => PostStatus::Draft,
|
|
2978
3358
|
];
|
|
2979
3359
|
}
|
|
2980
3360
|
```
|
|
2981
3361
|
|
|
2982
|
-
|
|
3362
|
+
Each member keeps its type, and `first_status` publishes the case's value:
|
|
2983
3363
|
|
|
2984
3364
|
```typescript
|
|
2985
|
-
|
|
3365
|
+
import { type AsEnum } from "@tolki/ts";
|
|
3366
|
+
|
|
3367
|
+
import { PostStatus } from "../../enums";
|
|
3368
|
+
import type { PostStatusType } from "../../enums";
|
|
3369
|
+
import type { User } from "../../models";
|
|
3370
|
+
|
|
3371
|
+
export interface PostCardResource {
|
|
3372
|
+
card: {
|
|
3373
|
+
author: User;
|
|
3374
|
+
status: PostStatusType;
|
|
3375
|
+
status_resource: AsEnum<typeof PostStatus>;
|
|
3376
|
+
first_status: 0;
|
|
3377
|
+
};
|
|
3378
|
+
}
|
|
2986
3379
|
```
|
|
2987
3380
|
|
|
3381
|
+
Written in `toArray()` itself, or spread with `...$this->card()`, `first_status` publishes `PostStatusType`.
|
|
3382
|
+
|
|
3383
|
+
A model's own `toArray()`, called as a value, publishes `Record<string, unknown>`, because the relations it includes depend on what's loaded at runtime. A relation's collection, as in `$this->comments->toArray()`, publishes `Record<string, unknown>[]`. To publish the model's keys, spread it instead, as [Model `toArray()` Spread](#model-toarray-spread) shows.
|
|
3384
|
+
|
|
2988
3385
|
##### Resource Macros
|
|
2989
3386
|
|
|
2990
3387
|
Laravel runs a macro you register on `JsonResource` before it forwards a call to the model, so a call the macro answers publishes what the macro returns, never the type of a model method with the same name:
|
|
@@ -3000,7 +3397,7 @@ JsonResource::macro('label', function (): string {
|
|
|
3000
3397
|
'model_label' => $this->resource->label(), // model_label: number
|
|
3001
3398
|
```
|
|
3002
3399
|
|
|
3003
|
-
`$this->resource->label()` calls the model directly, so it keeps the model's type. `$this?->label()`, `static::label()`, `self::label()` and `$this::label()` reach the macro, as `$this->label()` does. A method the resource declares or inherits, such as `whenLoaded()`, runs before any macro with its name, so a macro
|
|
3400
|
+
`$this->resource->label()` calls the model directly, so it keeps the model's type. `$this?->label()`, `static::label()`, `self::label()` and `$this::label()` reach the macro, as `$this->label()` does. A method the resource declares or inherits, such as `whenLoaded()`, runs before any macro with its name, so a macro doesn't change it. In a parent resource's body, `self::label()` looks only at that parent: if the parent doesn't declare `label()`, the macro runs even when the child declares one, and the key publishes the macro's type.
|
|
3004
3401
|
|
|
3005
3402
|
The package types a macro from its native return type, then its `@return` docblock, then its body. It reads the body without the values the call passes, so a body whose result depends on its arguments publishes `unknown`. It doesn't read the body of a closure declared outside a class method, such as in `bootstrap/app.php`. To type such a macro, give the closure a return type. A `@return` docblock works only on a closure declared inside a class, such as in a service provider's `boot()` method.
|
|
3006
3403
|
|
|
@@ -3010,7 +3407,7 @@ Registering, removing, or re-pointing a macro makes the next `ts:publish` rebuil
|
|
|
3010
3407
|
|
|
3011
3408
|
#### Local Variables and Narrowing
|
|
3012
3409
|
|
|
3013
|
-
A variable
|
|
3410
|
+
A variable keeps the type of the value you assign it, so you don't need to inline the expression:
|
|
3014
3411
|
|
|
3015
3412
|
```php
|
|
3016
3413
|
public function toArray(Request $request): array
|
|
@@ -3023,6 +3420,20 @@ public function toArray(Request $request): array
|
|
|
3023
3420
|
}
|
|
3024
3421
|
```
|
|
3025
3422
|
|
|
3423
|
+
A variable assigned inside an `if`, a loop, or a `try` block keeps that type for the reads after it in the same block:
|
|
3424
|
+
|
|
3425
|
+
```php
|
|
3426
|
+
'title_or_count' => $this->when($request->has('title'), function () {
|
|
3427
|
+
if ($this->is_pinned) {
|
|
3428
|
+
$title = $this->title;
|
|
3429
|
+
|
|
3430
|
+
return $title;
|
|
3431
|
+
}
|
|
3432
|
+
|
|
3433
|
+
return 7;
|
|
3434
|
+
}), // title_or_count?: string | number
|
|
3435
|
+
```
|
|
3436
|
+
|
|
3026
3437
|
A conditional value keeps its `?` through the variable, and through a `??` or a ternary. With `$loaded = $this->whenLoaded('author')`, `'author' => $loaded ?? 'none'` publishes `author?: User | string`: a missing value isn't `null`, so `??` returns it, and Laravel drops the key.
|
|
3027
3438
|
|
|
3028
3439
|
A closure or arrow-function parameter with the same name doesn't affect the outer variable. Inside its own closure, the parameter holds its own value:
|
|
@@ -3041,7 +3452,92 @@ public function toArray(Request $request): array
|
|
|
3041
3452
|
|
|
3042
3453
|
A closure that captures the variable by value, with `use ($member)`, and reassigns it doesn't change the outer variable either. Only `use (&$member)` does. An arrow function never does.
|
|
3043
3454
|
|
|
3044
|
-
A variable you write more than once publishes
|
|
3455
|
+
A variable you write more than once publishes every value that can reach the read. A write that always runs replaces the value before it, and a write inside an `if`, a loop, a `try`, or a `catch` joins it:
|
|
3456
|
+
|
|
3457
|
+
```php
|
|
3458
|
+
public function toArray(Request $request): array
|
|
3459
|
+
{
|
|
3460
|
+
$status = 'draft';
|
|
3461
|
+
|
|
3462
|
+
if ($this->is_pinned) {
|
|
3463
|
+
$status = 1;
|
|
3464
|
+
}
|
|
3465
|
+
|
|
3466
|
+
$first = null;
|
|
3467
|
+
|
|
3468
|
+
foreach ($this->comments as $comment) {
|
|
3469
|
+
if ($comment->content !== '') {
|
|
3470
|
+
$first = $comment->content;
|
|
3471
|
+
|
|
3472
|
+
break;
|
|
3473
|
+
}
|
|
3474
|
+
}
|
|
3475
|
+
|
|
3476
|
+
return [
|
|
3477
|
+
'status' => $status, // status: string | number
|
|
3478
|
+
'first' => $first, // first: string | null
|
|
3479
|
+
];
|
|
3480
|
+
}
|
|
3481
|
+
```
|
|
3482
|
+
|
|
3483
|
+
Each read sees only the writes that reach it. After `$x = $this->notes;`, a guard that returns `['early' => $x]` publishes `early: string | null`, and a later `$x = $this->resource->getKey(); return ['late' => $x];` publishes `late: number`. A write that reads the variable itself, as in `$label = $label.$this->title` or `$row = ['v' => $row]`, builds on the value before it.
|
|
3484
|
+
|
|
3485
|
+
A closure's or a helper's parameter follows the same rules. A write that always runs replaces the value the parameter was passed. A write inside a block is what later reads in that block see, and past the block it joins the value the parameter was passed. Here `$this->labelFor($this->title)` publishes `string | number`:
|
|
3486
|
+
|
|
3487
|
+
```php
|
|
3488
|
+
private function labelFor(string $label)
|
|
3489
|
+
{
|
|
3490
|
+
if ($this->is_pinned) {
|
|
3491
|
+
$label = $this->id;
|
|
3492
|
+
}
|
|
3493
|
+
|
|
3494
|
+
return $label;
|
|
3495
|
+
}
|
|
3496
|
+
```
|
|
3497
|
+
|
|
3498
|
+
A write to a closure's or helper's parameter inside a block, or a key one branch writes, that the package can't type is left out of the join, as [Values Left Out of a Union](#values-left-out-of-a-union) describes. On a plain local, such a write makes the read publish `unknown`.
|
|
3499
|
+
|
|
3500
|
+
A check that rules out `null` drops it from the reads it covers. With `$score = $this->rating` on a nullable column, `$score !== null ? $score : 'none'` publishes `string`, and so does `$this->when($score, fn () => $score)`, as an optional property.
|
|
3501
|
+
|
|
3502
|
+
Some variables still publish `unknown`:
|
|
3503
|
+
|
|
3504
|
+
- One a reference can write, through `use (&$x)`, `$alias = &$x`, `global` or `static`
|
|
3505
|
+
- One you change with `.=`, `++` or another compound assignment, apart from adding an array with `+=` as described below
|
|
3506
|
+
- One an `unset()` may remove
|
|
3507
|
+
- One you pass to a by-reference parameter that can change the value's form, such as `settype()`, `parse_str()`, or one of your own methods
|
|
3508
|
+
|
|
3509
|
+
Variables assigned inside a closure body follow the same rules within that closure. A reassignment inside an `if` branch that ends in `return` or `throw` applies only inside that branch, so the code after it keeps reading the original variable.
|
|
3510
|
+
|
|
3511
|
+
`preg_match()` and `preg_match_all()` type their `$matches` from the pattern's groups and the flags you pass. After `preg_match('/(\w+)-(\d+)/', $this->slug, $matches)`, both `$matches` and `$matches ?? []` publish `string[]`. Named groups and flags change the shape:
|
|
3512
|
+
|
|
3513
|
+
```php
|
|
3514
|
+
preg_match('/(?<first>B)/', $this->title, $named);
|
|
3515
|
+
preg_match('/(B)/', $this->title, $offset, PREG_OFFSET_CAPTURE);
|
|
3516
|
+
preg_match('/(B)(x)?/', $this->title, $nulls, PREG_UNMATCHED_AS_NULL);
|
|
3517
|
+
preg_match_all('/(B)/', $this->title, $all);
|
|
3518
|
+
|
|
3519
|
+
return [
|
|
3520
|
+
'named' => $named,
|
|
3521
|
+
'first' => $named['first'] ?? null,
|
|
3522
|
+
'offset' => $offset ?? [],
|
|
3523
|
+
'nulls' => $nulls ?? [],
|
|
3524
|
+
'all' => $all,
|
|
3525
|
+
];
|
|
3526
|
+
```
|
|
3527
|
+
|
|
3528
|
+
Each key publishes the shape its call writes:
|
|
3529
|
+
|
|
3530
|
+
```typescript
|
|
3531
|
+
named: { "0": string; first?: string; "1"?: string } | never[];
|
|
3532
|
+
first: string | null;
|
|
3533
|
+
offset: [string, number][];
|
|
3534
|
+
nulls: (string | null)[];
|
|
3535
|
+
all: string[][];
|
|
3536
|
+
```
|
|
3537
|
+
|
|
3538
|
+
A named group's matches publish an object keyed by name and number, or `never[]` for the empty array a failed match leaves. A pattern the package can't read as a literal, such as one held in a variable, leaves `$matches ?? []` as `never[]`. A call that may not run, such as one inside an `if`, types `$matches` only when nothing else writes the variable.
|
|
3539
|
+
|
|
3540
|
+
A literal key read on a variable that holds an array shape takes that key's type. With `$row = ['a' => 1, 'b' => 'x']`, `$row['b']` publishes `string`, and `$row['c'] ?? null`, a key the shape lacks, publishes `null`. A `map()` parameter and a method whose `@return` declares a shape work the same way, so `$this->pair()[1]` on a method declared `@return array{int, string}` publishes `string`.
|
|
3045
3541
|
|
|
3046
3542
|
A by-reference built-in that keeps the value's form keeps its type:
|
|
3047
3543
|
|
|
@@ -3066,13 +3562,27 @@ sort($original); // $copy keeps the type $original had before the sort
|
|
|
3066
3562
|
|
|
3067
3563
|
A call on one of a local's keys, such as `sort($groups['x'])`, keeps the local's type when it keeps that key's form.
|
|
3068
3564
|
|
|
3069
|
-
|
|
3565
|
+
A variable you build with key writes or `+=` and read as a value publishes the keys written before the read:
|
|
3566
|
+
|
|
3567
|
+
```php
|
|
3568
|
+
$meta = ['id' => $this->id];
|
|
3569
|
+
$meta['name'] = $this->name;
|
|
3570
|
+
$early = ['meta' => $meta];
|
|
3571
|
+
$meta['late'] = true;
|
|
3572
|
+
|
|
3573
|
+
return [
|
|
3574
|
+
'meta' => $meta, // meta: { id: number; name: string; late: boolean }
|
|
3575
|
+
'early' => $early, // early: { meta: { id: number; name: string } }
|
|
3576
|
+
];
|
|
3577
|
+
```
|
|
3578
|
+
|
|
3579
|
+
For a variable that `toArray()` returns, the package follows each write the same way, as [Building the Array in a Variable](#building-the-array-in-a-variable) describes.
|
|
3070
3580
|
|
|
3071
3581
|
To type a variable the package can't read, annotate its assignment. See [Typing a Variable With `@var`](#typing-a-variable-with-var).
|
|
3072
3582
|
|
|
3073
3583
|
##### Narrowing With `instanceof`
|
|
3074
3584
|
|
|
3075
|
-
An early-exit `instanceof` guard narrows a variable for
|
|
3585
|
+
An early-exit `instanceof` guard narrows a variable for the statements after it, up to the end of the block it sits in. Here `attachable` is a `morphTo`, so `$parent` can hold several models until the guard proves it holds a `Post`:
|
|
3076
3586
|
|
|
3077
3587
|
```php
|
|
3078
3588
|
$record = $this->attachable;
|
|
@@ -3104,21 +3614,52 @@ export interface AttachmentResource {
|
|
|
3104
3614
|
}
|
|
3105
3615
|
```
|
|
3106
3616
|
|
|
3107
|
-
|
|
3617
|
+
An `if` narrows a variable wherever its test is proven:
|
|
3618
|
+
|
|
3619
|
+
- **After a guard**: an `if` whose body ends in `return` or `throw` narrows the reads after it, up to the end of the block it sits in. Inside a loop, so does one whose body ends in `continue` or `break`. A guard nested in a loop or in another `if` narrows only the rest of that block.
|
|
3620
|
+
- **Inside a positive test**: `if ($parent instanceof Post) { ... }` narrows the reads in its block. An `elseif` or `else` sees the earlier tests fail, so the `else` of `if (! $parent instanceof Post) { ... }` reads `Post`.
|
|
3621
|
+
|
|
3622
|
+
```php
|
|
3623
|
+
$owner = $this->imageable;
|
|
3624
|
+
$data = [];
|
|
3625
|
+
|
|
3626
|
+
if ($owner instanceof Post) {
|
|
3627
|
+
$data['post_title'] = $owner->title;
|
|
3628
|
+
} elseif ($owner instanceof User) {
|
|
3629
|
+
$data['user_email'] = $owner->email;
|
|
3630
|
+
}
|
|
3631
|
+
|
|
3632
|
+
return $data; // post_title?: string; user_email?: string
|
|
3633
|
+
```
|
|
3634
|
+
|
|
3635
|
+
The test can be one `instanceof`, negated or not, or an `||` chain of tests on the same variable, which narrows to any of their classes. A positive test can also join tests with `&&`. A positive test whose `||` joins two different variables narrows neither. A guard whose negated tests are joined with `||` narrows each, and one joined with `&&` narrows none. The test can read a local variable, a closure parameter, a `foreach` value variable, or a chain of property reads on `$this`, such as `$this->imageable`.
|
|
3108
3636
|
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
|
|
3112
|
-
|
|
3113
|
-
|
|
3637
|
+
A write to the variable between the test and the end of what it narrows cancels the narrowing, even for the reads before that write. A write through one of its members keeps the narrowing when it stores a literal the member's column holds, such as `$parent->title = 'Draft'`, or names no column or relation, such as `$parent->touched = true`. A write before the test doesn't matter, since the test checks the value it leaves.
|
|
3638
|
+
|
|
3639
|
+
A test on a `$this` property chain narrows reads of that same chain, so you don't need a local first. Here `imageable` is a `morphTo`:
|
|
3640
|
+
|
|
3641
|
+
```php
|
|
3642
|
+
if (! $this->imageable instanceof Post) {
|
|
3643
|
+
return ['title' => null];
|
|
3644
|
+
}
|
|
3645
|
+
|
|
3646
|
+
return ['title' => $this->imageable->title]; // title: string | null
|
|
3647
|
+
```
|
|
3114
3648
|
|
|
3115
|
-
|
|
3649
|
+
Each spelling narrows on its own, so a test on `$this->resource->imageable` doesn't narrow a read of `$this->imageable`. Because code between the test and a read could change the property, the narrowing ends at a write to the chain, at any write through a local, and at most calls, such as `$this->reload()`, `PostResource::make($this->resource)`, or a call on a local. These calls keep it:
|
|
3116
3650
|
|
|
3117
|
-
|
|
3651
|
+
- The resource's own helpers, such as `when()` and `whenLoaded()`
|
|
3652
|
+
- Gate and policy checks
|
|
3653
|
+
- Laravel's `route()` and `url()`
|
|
3654
|
+
- A call that's passed no local, no `$this`, and no `$this->resource`, such as `Str::limit($this->imageable->title, 50)`
|
|
3118
3655
|
|
|
3119
|
-
|
|
3656
|
+
A read in a guard's own body, in a `return` placed before the guard, or in the `if` condition itself still sees every class the variable can hold.
|
|
3120
3657
|
|
|
3121
|
-
|
|
3658
|
+
Narrowing applies to reads through the variable, such as `$parent->title`. A local's own value, as in `'parent' => $parent`, keeps its full union type. A closure parameter bound to one model is the exception: under a test for a published subclass of that model, its own value publishes the subclass, so `$this->whenLoaded('post', fn ($post) => $post instanceof DraftPost ? $post : null)` publishes `DraftPost | null`.
|
|
3659
|
+
|
|
3660
|
+
An `instanceof` ternary on a variable narrows its true arm the same way, as `record_title` above shows, and so does an `||` chain of tests on that variable. A negated test, such as `! $post instanceof Post ? null : $post->title`, narrows the false arm instead. A ternary that tests a chain of property reads on `$this` narrows reads through the same chain in its arm, so `$this->imageable instanceof Post ? $this->imageable->getKey() : null` publishes `number | null`.
|
|
3661
|
+
|
|
3662
|
+
A test that checks `$this->resource` against one model narrows the backing model wherever it's proven: in a ternary's arm, in an `if` block, or after a guard. So a relation that only a subclass declares resolves there. On a `Team` resource, `$this->resource instanceof SubscribedTeam ? $this->resource->subscriber?->name : null` publishes `string | null`. A method of the resource that the proven code calls reads the narrowed model too, so `$this->resource instanceof SubscribedTeam ? $this->subscriberName() : null` publishes `string | null` when `subscriberName()` returns `$this->resource->subscriber?->name`. In a resource collection, the same test narrows the collected items to the paginator it names, as [Reading `$this->resource`](#reading-this-resource) shows.
|
|
3122
3663
|
|
|
3123
3664
|
A variable assigned from an `instanceof` ternary keeps the narrowing for every read through it. The test can be an `||` chain of `instanceof` checks. Here `imageable` is a `morphTo` whose possible models include one with a string key:
|
|
3124
3665
|
|
|
@@ -3144,9 +3685,8 @@ return [
|
|
|
3144
3685
|
These forms don't narrow:
|
|
3145
3686
|
|
|
3146
3687
|
- **The ternary's own value**: `'either' => $either` publishes the whole union. Only reads through the variable narrow.
|
|
3147
|
-
- **A read inside the arm when the test is on a property**: `$this->imageable instanceof Post ? $this->imageable->getKey() : null` stays `number | string | null`. Assign the ternary to a variable, and read through that variable instead.
|
|
3148
3688
|
- **A test on a different spelling of the arm's value**: a variable bound to a ternary that tests `$this->resource->imageable` against a `$this->imageable` arm isn't narrowed.
|
|
3149
|
-
- **Mixed conditions**: a test joined with `&&`, or an `||` chain that mixes negated and plain tests.
|
|
3689
|
+
- **Mixed conditions in a ternary**: a test joined with `&&`, or an `||` chain that mixes negated and plain tests.
|
|
3150
3690
|
- **The arm the test doesn't prove**: `$this->resource instanceof SubscribedTeam ? null : $this->resource->subscriber` publishes `unknown`, since `Team` has no `subscriber` relation.
|
|
3151
3691
|
|
|
3152
3692
|
##### Typing a Variable With `@var`
|
|
@@ -3163,7 +3703,7 @@ return [
|
|
|
3163
3703
|
];
|
|
3164
3704
|
```
|
|
3165
3705
|
|
|
3166
|
-
It also restores a value the package would otherwise drop. Without the annotation, `$picked` below publishes `null`, because the package leaves out a ternary arm it can't type:
|
|
3706
|
+
It also restores a value the package would otherwise drop. Without the annotation, `$picked` below publishes `null`, because the package [leaves out a ternary arm it can't type](#values-left-out-of-a-union):
|
|
3167
3707
|
|
|
3168
3708
|
```php
|
|
3169
3709
|
/** @var string|null $picked */
|
|
@@ -3172,29 +3712,35 @@ $picked = $this->id > 0 ? json_decode('"x"') : null; // string | null
|
|
|
3172
3712
|
|
|
3173
3713
|
The annotation follows these rules:
|
|
3174
3714
|
|
|
3175
|
-
- **Placement**: it sits on a `$x = ...;` statement
|
|
3176
|
-
- **Span**: it types the reads after that statement, up to the next statement that writes the variable. A loop that writes the variable ends the span where the loop starts. So an annotation also types a variable you reassign, until its next write.
|
|
3715
|
+
- **Placement**: it sits on a `$x = ...;` statement anywhere in the method or closure body, including inside an `if` or a loop. It names the variable, as in `/** @var CartTotals $totals */`, or names none, as in `/** @var CartTotals */`. A `@phpstan-var` or `@psalm-var` tag wins over a plain `@var`, as in PHPStan.
|
|
3716
|
+
- **Span**: it types the reads after that statement, up to the next statement that writes the variable. A loop that writes the variable ends the span where the loop starts. So an annotation also types a variable you reassign, until its next write. Inside a block, it types the reads after it in that block. Past the block, where the variable held a value before it, the annotated type joins that value. Where the variable held none, reads past the block aren't typed. With `$post = null;` before an `if` whose annotated assignment reads `/** @var Post|null $post */`, `$post?->title` after the `if` publishes `string | null`.
|
|
3177
3717
|
- **Precedence**: it applies only where the package's own reading of the value is `unknown`, or is only the `null` left after an arm it can't type was dropped. Any other reading stands, whatever the annotation says: `/** @var int $n */ $n = $this->title;` still publishes `string`. To override a type the package got wrong, use [`#[TsCasts]`](#overriding-property-types-with-tscasts).
|
|
3178
3718
|
|
|
3179
3719
|
A conditional value stays optional, so `/** @var User $reviewer */ $reviewer = $this->whenLoaded('reviewer');` publishes `reviewer?: User`.
|
|
3180
3720
|
|
|
3181
|
-
A closure parameter you reassign reads the new value from that statement on, when the value or an annotation names its class. In `function (User $author)`, `$author = $author->profile;` makes the reads after it use `Profile`.
|
|
3721
|
+
A closure parameter you reassign reads the new value from that statement on, when the value or an annotation names its class. In `function (User $author)`, `$author = $author->profile;` makes the reads after it use `Profile`. `find()` with one literal key returns one of the collection's models or `null`. After `$author = $author->comments->find(1);`, `$author?->content` publishes `string | null`, and `$author->name` publishes `unknown`, since a comment has no `name`. A read of the variable itself after that write publishes `unknown`, as `first()` does.
|
|
3722
|
+
|
|
3723
|
+
A write the package can't type keeps a model parameter's model, so after `$author = $this->normalize($author);`, where `normalize()` declares no return type, both `$author->name` and `return $author;` still read `User`. Annotate such an assignment, as in `/** @var Comment $author */`, and the reads follow the annotation. A write of a typed value is read as that value, so after `$author = $author->name;`, `return $author;` publishes `string`. A parameter that holds a plain value takes what any write returns, so after `$title = json_decode($title);`, `return $title;` publishes `unknown`. A `foreach` variable bound to a model keeps reading that model.
|
|
3182
3724
|
|
|
3183
3725
|
The annotation's type counts only when it's built from these forms, and when every part of it resolves:
|
|
3184
3726
|
|
|
3185
3727
|
- Scalars: `int`, `string`, `bool`, `float`, `null`, `true`, and `false`
|
|
3186
|
-
- A class, interface, or enum that the file imports or
|
|
3187
|
-
- `
|
|
3728
|
+
- A class, interface, or enum that the file imports, writes in full, or declares in its own namespace
|
|
3729
|
+
- `self`, `static`, and `parent`, which name the classes `self::`, `static::`, and `parent::` reach in that method, as in an [inherited `toArray()`](#inheriting-a-parent-toarray). The variable may hold a subclass, so a read of a method or property a subclass can override takes its declared type, and publishes `unknown` where it has none. A closure parameter typed `self` or `parent` reads the same way.
|
|
3730
|
+
- `X[]`, `list<X>`, `array<int, X>`, `array<string, X>`, `array<int|string, X>`, `array<array-key, X>`, and `array<'a'|'b', X>`
|
|
3188
3731
|
- `array{...}` and `object{...}` shapes with plain or quoted keys, and `list{...}` tuples
|
|
3189
|
-
- `Collection<K, X>`, for both Laravel's support collection and its Eloquent collection
|
|
3732
|
+
- `Collection<X>` and `Collection<K, X>`, for both Laravel's support collection and its Eloquent collection
|
|
3733
|
+
- A type alias the class declares with `@phpstan-type`, or imports with `@phpstan-import-type`, under its own name or an `as` name
|
|
3190
3734
|
- A `callable` as a shape's member, which publishes `unknown`
|
|
3191
3735
|
- Unions of these forms, such as `Comment|User|null` or `list<User>|User`, and `?` before any form
|
|
3192
3736
|
|
|
3193
|
-
Any other type is ignored
|
|
3737
|
+
Any other type is ignored. A key that can be an `int` or a `string`, as in `array<int|string, Comment>` or `array<array-key, Comment>`, publishes both shapes PHP can send, `Comment[] | Record<string, Comment>`. A model or an enum inside a shape keeps its type, so `array{author: User, status: Status}` publishes `{ author: User; status: StatusType }`. A `?` before a shape adds `| null` even when a member already holds `null`, so `?array{a: ?int}` publishes `{ a: number | null } | null`.
|
|
3738
|
+
|
|
3739
|
+
A helper's or a closure's `@param` tag reads the same forms where the value passed in can't be typed. With `@param Collection<int, Comment> $comments`, a read such as `$comments->first()?->content` publishes `string | null`, and with `@param Pair $pair`, where `Pair` is a `@phpstan-type` alias, `$pair` takes the alias's shape. Where the value passed in is typed, its type wins over the tag.
|
|
3194
3740
|
|
|
3195
3741
|
#### Collection Pipelines
|
|
3196
3742
|
|
|
3197
|
-
A chain of collection methods keeps its element type to the end, whether it starts at a relation or
|
|
3743
|
+
A chain of collection methods keeps its element type to the end, whether it starts at a relation, a local, a query, or `collect()`:
|
|
3198
3744
|
|
|
3199
3745
|
```php
|
|
3200
3746
|
return [
|
|
@@ -3209,28 +3755,139 @@ return [
|
|
|
3209
3755
|
Each chain publishes its element type:
|
|
3210
3756
|
|
|
3211
3757
|
```typescript
|
|
3212
|
-
export interface PostResource {
|
|
3213
|
-
comment_ids: number[];
|
|
3214
|
-
title_words: { word: string }[];
|
|
3215
|
-
author_name: string | null;
|
|
3216
|
-
author_name_or_guest: string | null;
|
|
3217
|
-
doubled: Comment[];
|
|
3218
|
-
// …
|
|
3219
|
-
}
|
|
3758
|
+
export interface PostResource {
|
|
3759
|
+
comment_ids: number[];
|
|
3760
|
+
title_words: { word: string }[];
|
|
3761
|
+
author_name: string | null;
|
|
3762
|
+
author_name_or_guest: string | null;
|
|
3763
|
+
doubled: Comment[];
|
|
3764
|
+
// …
|
|
3765
|
+
}
|
|
3766
|
+
```
|
|
3767
|
+
|
|
3768
|
+
These helpers and methods publish as follows:
|
|
3769
|
+
|
|
3770
|
+
- **`all()` and `values()`**: a collection and the array behind it both publish `X[]`, so `all()` changes nothing. A method that breaks sequential keys, such as `filter()`, `sortBy()`, or `keyBy()`, adds a `Record<string, X>` arm, because `json_encode()` writes such a collection as an object. The arm stays through a local and through a later `map()`. `values()` restores sequential keys and removes that arm.
|
|
3771
|
+
- **`collect()`**: the element type comes from the argument, and the `map()` parameter holds that element, which is why `$word` above is a `string`. On its own, `collect([...])` publishes the list or object its array encodes as, such as `number[]` for `collect([1, 2])` or `{ title: string }` for `collect(['title' => $this->title])`. `collect()` with no argument publishes `never[]`. A bare array literal publishes the same way, so `['a', 'b']` publishes `string[]`. A list holding an element the package can't type publishes `unknown[]`.
|
|
3772
|
+
- **`data_get()`**: `data_get($target, 'a.b')` publishes what `$target?->a?->b` would. A default joins the type instead of removing `null`, because `data_get()` returns the default only when the key is missing, not when its value is `null`.
|
|
3773
|
+
- **`keys()`**: publishes the list of the keys, `number[]` for a list and `string[]` for a `Record<string, X>`. A literal array lists its own keys, so `collect(['a' => 1, 200 => 'x'])->keys()->all()` publishes `('a' | 200)[]`.
|
|
3774
|
+
- **`map()` parameters**: the callback's parameter holds the collection's element, with or without a type hint, whether the collection comes from a relation, a local, a `whenLoaded()` parameter, `getRelation()`, a query's `get()`, or `collect()`. Every read through it is typed, chained and nullsafe reads included. A class type hint, such as `fn (Comment $comment)` or a value object's class, types the parameter whatever the collection holds. A scalar type hint holds the value PHP converts the element to, so `collect(['5'])->map(fn (int $v) => $v)->all()` publishes `number[]`. A write that replaces the parameter is followed into the body.
|
|
3775
|
+
- **`map()` callbacks**: besides a closure, the callback can be a first-class callable, such as `$this->shout(...)`, or a callable string, such as `'strtoupper'`. A `map()` over a `Record<string, X>` keeps its string keys, so it publishes a `Record` of what the callback returns.
|
|
3776
|
+
|
|
3777
|
+
Here `PromoCode` is a value object with a `string` property `code`:
|
|
3778
|
+
|
|
3779
|
+
```php
|
|
3780
|
+
public function toArray(Request $request): array
|
|
3781
|
+
{
|
|
3782
|
+
$rows = $this->comments;
|
|
3783
|
+
$byContent = $this->comments->keyBy('content');
|
|
3784
|
+
|
|
3785
|
+
return [
|
|
3786
|
+
'collected_reads' => collect($this->comments)->map(fn ($comment) => ['content' => $comment->content, 'who' => $comment->user?->name])->all(),
|
|
3787
|
+
'local_rows' => $rows->map(fn ($comment) => ['who' => $comment->user?->name]),
|
|
3788
|
+
'author_names' => $rows->map(function (Comment $comment) {
|
|
3789
|
+
$comment = $comment->user;
|
|
3790
|
+
|
|
3791
|
+
return $comment->name;
|
|
3792
|
+
}),
|
|
3793
|
+
'keyed_rows' => $byContent->map(fn (Comment $comment) => ['id' => $comment->id])->all(),
|
|
3794
|
+
'query_rows' => Comment::query()->get()->map(fn (Comment $comment) => ['id' => $comment->id])->all(),
|
|
3795
|
+
'codes' => collect([new PromoCode('a')])->map(fn (PromoCode $code) => ['id' => $code->code])->all(),
|
|
3796
|
+
];
|
|
3797
|
+
}
|
|
3798
|
+
```
|
|
3799
|
+
|
|
3800
|
+
Each map publishes its callback's shape:
|
|
3801
|
+
|
|
3802
|
+
```typescript
|
|
3803
|
+
collected_reads: { content: string; who: string | null }[];
|
|
3804
|
+
local_rows: { who: string | null }[];
|
|
3805
|
+
author_names: string[];
|
|
3806
|
+
keyed_rows: { id: number }[] | Record<string, { id: number }>;
|
|
3807
|
+
query_rows: { id: number }[];
|
|
3808
|
+
codes: { id: string }[];
|
|
3809
|
+
```
|
|
3810
|
+
|
|
3811
|
+
`Model::all()` names its model the same way, so `Post::all()->toResourceCollection()` publishes `PostResource[]`. `map()` on a paginator maps the models on its page, so with `$page = Post::query()->paginate();`, `$page->map(fn (Post $post) => ['id' => $post->id])` publishes `{ id: number }[]`.
|
|
3812
|
+
|
|
3813
|
+
`concat($other)` keeps the type only when `$other` is exactly the same collection type. Concatenating `Comment[]` and `Tag[]` publishes `unknown`, since the result is a different collection, not a longer one. A `data_get()` key with a `*` segment also publishes `unknown`.
|
|
3814
|
+
|
|
3815
|
+
A chain can start at `$this->resource` too. `$this->resource->comments->map(fn ($comment) => $comment->id)` publishes `number[]`, as `$this->comments->map(...)` does. A `?->` on `$this->resource` adds `| null` once, since a resource can wrap `null`. `$this->resource?->comments->map(fn ($comment) => $comment->id)` publishes `number[] | null`.
|
|
3816
|
+
|
|
3817
|
+
`first()`, `last()` and `firstWhere()` on a collection of models return one of its models or `null`, so a read through them with `?->` is typed. That covers a relation's collection, a local holding one, and a variable an inline `@var Collection<int, Comment>` declares. `$this->comments->first()?->content` publishes `string | null`, and so does the same read after `last()`, `firstWhere('is_flagged', true)`, or `find()` with one literal key, such as `find(1)`. After a `first()` or `last()` call that passes a default, such as `first(null, 'none')`, the read publishes `unknown`, because Laravel returns that default when no model matches.
|
|
3818
|
+
|
|
3819
|
+
##### Array Functions
|
|
3820
|
+
|
|
3821
|
+
PHP's array functions keep the element type too. `array_map()` with one array keeps that array's keys, so a list maps to a list and a string-keyed array to an object. With two or more arrays it publishes a list, and a `null` callback zips the arrays into tuples. The callback can be any callable, as with `map()`:
|
|
3822
|
+
|
|
3823
|
+
```php
|
|
3824
|
+
public function toArray(Request $request): array
|
|
3825
|
+
{
|
|
3826
|
+
return [
|
|
3827
|
+
'messages' => array_map(fn (array $row): string => $row['message'], $this->rows()),
|
|
3828
|
+
'doubled' => array_map(fn (int $count): int => $count * 2, ['low' => 1, 'high' => 2]),
|
|
3829
|
+
'zipped' => array_map(null, $this->labels(), $this->counts()),
|
|
3830
|
+
'names' => array_map('strtoupper', $this->comments->pluck('content')->all()),
|
|
3831
|
+
];
|
|
3832
|
+
}
|
|
3833
|
+
```
|
|
3834
|
+
|
|
3835
|
+
Here `rows()` returns `list<array{message: string}>`, `labels()` a `list<string>`, and `counts()` a `list<int>`:
|
|
3836
|
+
|
|
3837
|
+
```typescript
|
|
3838
|
+
export interface ArrayMapResource {
|
|
3839
|
+
messages: string[];
|
|
3840
|
+
doubled: { low: number; high: number };
|
|
3841
|
+
zipped: [string | null, number | null][];
|
|
3842
|
+
names: string[];
|
|
3843
|
+
}
|
|
3844
|
+
```
|
|
3845
|
+
|
|
3846
|
+
`array_keys()` publishes the list of the keys, as `keys()` does, so `array_keys(['a' => 1, 'b' => 2])` publishes `('a' | 'b')[]`.
|
|
3847
|
+
|
|
3848
|
+
`array_filter()` of an array shape makes each key optional and leaves out a key that only ever holds `null`. `array_values()` of the result publishes the list of the values left:
|
|
3849
|
+
|
|
3850
|
+
```php
|
|
3851
|
+
'shape' => array_filter(['a' => $this->title, 'b' => $this->published_at]),
|
|
3852
|
+
'no_null' => array_filter(['a' => $this->title, 'b' => null]),
|
|
3853
|
+
'values' => array_values(array_filter(['a' => $this->title, 'b' => $this->published_at])),
|
|
3854
|
+
```
|
|
3855
|
+
|
|
3856
|
+
Here `published_at` is a nullable column:
|
|
3857
|
+
|
|
3858
|
+
```typescript
|
|
3859
|
+
shape: { a?: string; b?: string };
|
|
3860
|
+
no_null: { a?: string };
|
|
3861
|
+
values: string[];
|
|
3220
3862
|
```
|
|
3221
3863
|
|
|
3222
|
-
|
|
3864
|
+
A filter that keeps no key sends `[]`, not `{}`. Reading a key on it still gives `undefined`, as the optional keys allow, but code that checks for an array, such as `Array.isArray()`, sees one.
|
|
3223
3865
|
|
|
3224
|
-
|
|
3225
|
-
- **`collect()`**: the element type comes from the argument, and the `map()` parameter holds that element, which is why `$word` above is a `string`. On its own, `collect([...])` publishes the list or object its array encodes as, such as `number[]` for `collect([1, 2])` or `{ title: string }` for `collect(['title' => $this->title])`. `collect()` with no argument publishes `never[]`. A bare array literal publishes the same way, so `['a', 'b']` publishes `string[]`. A list holding an element the package can't type publishes `unknown[]`.
|
|
3226
|
-
- **`data_get()`**: `data_get($target, 'a.b')` publishes what `$target?->a?->b` would. A default joins the type instead of removing `null`, because `data_get()` returns the default only when the key is missing, not when its value is `null`.
|
|
3227
|
-
- **Typed `map()` parameters**: a model type hint on a `map()` parameter types every read through it, chained and nullsafe reads included, when you call `map()` on a variable such as a local or a `whenLoaded()` parameter. With `$rows = $this->resource->getRelation('comments')`, `$rows->map(fn (Comment $comment) => $comment->user?->name ?: null)->all()` publishes `(string | null)[]`. A relation chain such as `$this->comments->map(...)` uses the relation's model the same way. On a `collect(...)` root, or on a `map()` called straight on a method's result, such as `$this->resource->getRelation('comments')->map(...)`, the parameter holds no model, so reads through it publish `unknown`.
|
|
3866
|
+
PHP throws a `TypeError` when you pass a collection to `array_map()`, `array_keys()`, `array_values()`, or `array_filter()`, so `ts:publish` warns and names the line. Call `->values()->all()` on the collection first.
|
|
3228
3867
|
|
|
3229
|
-
|
|
3868
|
+
#### Query Chains
|
|
3230
3869
|
|
|
3231
|
-
A chain
|
|
3870
|
+
A query chain that starts at a model is typed step by step, as in [page props](https://tolki.abe.dev/ts/routing.html#what-the-props-expression-can-be):
|
|
3871
|
+
|
|
3872
|
+
```php
|
|
3873
|
+
return [
|
|
3874
|
+
'author' => User::find(1),
|
|
3875
|
+
'author_name' => User::find(1)?->name,
|
|
3876
|
+
'latest' => Post::query()->first(),
|
|
3877
|
+
'first_id' => Post::query()->pluck('id')->first(),
|
|
3878
|
+
'admins' => User::query()->where('id', 1)->get(),
|
|
3879
|
+
];
|
|
3880
|
+
```
|
|
3232
3881
|
|
|
3233
|
-
|
|
3882
|
+
Each chain publishes what its last step returns:
|
|
3883
|
+
|
|
3884
|
+
```typescript
|
|
3885
|
+
author: User | null;
|
|
3886
|
+
author_name: string | null;
|
|
3887
|
+
latest: Post | null;
|
|
3888
|
+
first_id: number | null;
|
|
3889
|
+
admins: User[];
|
|
3890
|
+
```
|
|
3234
3891
|
|
|
3235
3892
|
### Spreads and Inheritance
|
|
3236
3893
|
|
|
@@ -3305,6 +3962,77 @@ export interface BodylessOrderResource {
|
|
|
3305
3962
|
|
|
3306
3963
|
The nearest class up the parent chain that declares a `toArray()` provides the shape, so inheritance several levels deep works. The backing model comes from the parent chain too: a resource with no `@mixin` or `@extends` tag of its own uses the nearest ancestor's, as step 3 of [How the Backing Model Is Resolved](#how-the-backing-model-is-resolved) describes. That keeps the inherited properties typed from their columns.
|
|
3307
3964
|
|
|
3965
|
+
The package reads the inherited body as PHP runs it for the child:
|
|
3966
|
+
|
|
3967
|
+
- `$this->` and `static::` reach the child, so a method, constant, or property the child overrides publishes the child's type. That includes a helper that `toArray()` spreads.
|
|
3968
|
+
- `self::` reaches the class that declares the body, and `parent::` reaches that class's parent. Spreads follow the same rule: `...parent::extra()` adds the keys of the parent's `extra()`, as `...self::extra()` and `...static::extra()` add those of the method each reaches. A private or abstract parent method adds none because PHP throws on that call, and neither does one whose body the package can't read in full.
|
|
3969
|
+
- A `private` member stays the one in the class that declares `toArray()`, because PHP never overrides one.
|
|
3970
|
+
|
|
3971
|
+
```php
|
|
3972
|
+
class BaseCardResource extends JsonResource
|
|
3973
|
+
{
|
|
3974
|
+
public const KIND = 'card';
|
|
3975
|
+
|
|
3976
|
+
public function toArray(Request $request): array
|
|
3977
|
+
{
|
|
3978
|
+
return [
|
|
3979
|
+
'title' => $this->title(),
|
|
3980
|
+
'kind' => static::KIND,
|
|
3981
|
+
'label' => self::label(),
|
|
3982
|
+
'weight' => $this->weight(),
|
|
3983
|
+
];
|
|
3984
|
+
}
|
|
3985
|
+
|
|
3986
|
+
public function title(): int|string
|
|
3987
|
+
{
|
|
3988
|
+
return 0;
|
|
3989
|
+
}
|
|
3990
|
+
|
|
3991
|
+
public static function label(): int|string
|
|
3992
|
+
{
|
|
3993
|
+
return 0;
|
|
3994
|
+
}
|
|
3995
|
+
|
|
3996
|
+
private function weight(): int
|
|
3997
|
+
{
|
|
3998
|
+
return 1;
|
|
3999
|
+
}
|
|
4000
|
+
}
|
|
4001
|
+
|
|
4002
|
+
class NoticeCardResource extends BaseCardResource
|
|
4003
|
+
{
|
|
4004
|
+
public const KIND = 7;
|
|
4005
|
+
|
|
4006
|
+
public function title(): string
|
|
4007
|
+
{
|
|
4008
|
+
return 'Notice';
|
|
4009
|
+
}
|
|
4010
|
+
|
|
4011
|
+
public static function label(): string
|
|
4012
|
+
{
|
|
4013
|
+
return 'notice';
|
|
4014
|
+
}
|
|
4015
|
+
|
|
4016
|
+
public function weight(): string
|
|
4017
|
+
{
|
|
4018
|
+
return 'heavy';
|
|
4019
|
+
}
|
|
4020
|
+
}
|
|
4021
|
+
```
|
|
4022
|
+
|
|
4023
|
+
`title` and `kind` come from `NoticeCardResource`. `label` keeps the parent's `string | number`, because `self::label()` calls `BaseCardResource::label()`, and `weight` keeps `number`, because `weight()` is private to `BaseCardResource`:
|
|
4024
|
+
|
|
4025
|
+
```typescript
|
|
4026
|
+
export interface NoticeCardResource {
|
|
4027
|
+
title: string;
|
|
4028
|
+
kind: number;
|
|
4029
|
+
label: string | number;
|
|
4030
|
+
weight: number;
|
|
4031
|
+
}
|
|
4032
|
+
```
|
|
4033
|
+
|
|
4034
|
+
`self::make()` and `self::collection()` in the inherited body build the child, as they do in PHP. So a `FeaturedCategoryResource` that inherits `'children' => self::collection($this->whenLoaded('children'))` from `CategoryResource` publishes `children?: FeaturedCategoryResource[]`. A method that returns `static`, called through `self::` or `parent::`, returns the child too.
|
|
4035
|
+
|
|
3308
4036
|
If no class in the chain declares a `toArray()`, the resource publishes the model's properties, as [JsonResource Base Delegation](#jsonresource-base-delegation) describes. With no model either, the interface is empty, apart from any types `#[TsExtends]` adds. A `ResourceCollection` subclass with no `toArray()` still finds its element type as [Resource Collections](#resource-collections) describes.
|
|
3309
4037
|
|
|
3310
4038
|
#### A `toArray()` From a Trait
|
|
@@ -3345,6 +4073,45 @@ export interface LabelResource {
|
|
|
3345
4073
|
|
|
3346
4074
|
A subclass of `LabelResource` with no `toArray()` of its own publishes the same keys. A `ResourceCollection` can take its `toArray()` from a trait the same way.
|
|
3347
4075
|
|
|
4076
|
+
In the trait's `toArray()`, `self::` reaches the class that uses the trait, and `parent::` reaches that class's parent. `$this->` and `static::` reach the resource, as they do in an [inherited `toArray()`](#inheriting-a-parent-toarray). Here `TagCardResource` extends the `BaseCardResource` above:
|
|
4077
|
+
|
|
4078
|
+
```php
|
|
4079
|
+
trait ShapesCard
|
|
4080
|
+
{
|
|
4081
|
+
public function toArray(Request $request): array
|
|
4082
|
+
{
|
|
4083
|
+
return [
|
|
4084
|
+
...parent::toArray($request),
|
|
4085
|
+
'label' => self::label(),
|
|
4086
|
+
'kind' => static::KIND,
|
|
4087
|
+
];
|
|
4088
|
+
}
|
|
4089
|
+
}
|
|
4090
|
+
|
|
4091
|
+
class TagCardResource extends BaseCardResource
|
|
4092
|
+
{
|
|
4093
|
+
use ShapesCard;
|
|
4094
|
+
|
|
4095
|
+
public const KIND = 'tag';
|
|
4096
|
+
|
|
4097
|
+
public static function label(): string
|
|
4098
|
+
{
|
|
4099
|
+
return 'tag';
|
|
4100
|
+
}
|
|
4101
|
+
}
|
|
4102
|
+
```
|
|
4103
|
+
|
|
4104
|
+
`parent::toArray()` spreads `BaseCardResource`'s keys, and `label` and `kind` take `TagCardResource`'s types:
|
|
4105
|
+
|
|
4106
|
+
```typescript
|
|
4107
|
+
export interface TagCardResource {
|
|
4108
|
+
title: string | number;
|
|
4109
|
+
kind: string;
|
|
4110
|
+
label: string;
|
|
4111
|
+
weight: number;
|
|
4112
|
+
}
|
|
4113
|
+
```
|
|
4114
|
+
|
|
3348
4115
|
#### JsonResource Base Delegation
|
|
3349
4116
|
|
|
3350
4117
|
A resource with no `toArray()`, or whose `toArray()` returns `parent::toArray($request)`, publishes the backing model's columns, its appended accessors, and its relations, each relation an optional key. These follow the keys Laravel's `Model::toArray()` writes, with the differences below. A subclass of Laravel's `JsonApiResource` is the exception: it publishes the resource object it sends, as [JSON:API Resources](#jsonapi-resources) describes. This resource has no `toArray()`:
|
|
@@ -3450,7 +4217,7 @@ export interface PostResource {
|
|
|
3450
4217
|
}
|
|
3451
4218
|
```
|
|
3452
4219
|
|
|
3453
|
-
Multi-line `@return` shapes work too:
|
|
4220
|
+
Multi-line `@return` shapes work too, as long as the type starts on the tag's own line, as PHPStan requires:
|
|
3454
4221
|
|
|
3455
4222
|
```php
|
|
3456
4223
|
/**
|
|
@@ -3579,19 +4346,147 @@ The variable can start from an array literal, as above, or from any of these:
|
|
|
3579
4346
|
- `$this->only([...])` with a literal list of keys
|
|
3580
4347
|
- `array_merge()` of array literals and `parent::toArray($request)` calls
|
|
3581
4348
|
- A helper method on the resource that returns an array
|
|
4349
|
+
- A local you assign one of these once, as in `$data = $defaults;`
|
|
3582
4350
|
|
|
3583
4351
|
A spread of `...$this->with($request)` or `...parent::with($request)` in `toArray()` adds the `$with` keys too.
|
|
3584
4352
|
|
|
3585
4353
|
These rules decide each key:
|
|
3586
4354
|
|
|
3587
|
-
- **
|
|
3588
|
-
- **
|
|
3589
|
-
-
|
|
4355
|
+
- **Branches**: each branch of an `if` chain holds its own value for a key. A key that every branch of a chain ending in `else` writes is required, with each branch's type. A key that only some branches write publishes optional, and a key set before the chain keeps that value as one more type. A branch that ends in `throw`, or in a `return` of anything but the variable, stays out.
|
|
4356
|
+
- **Loops**: a loop may run no times, so a key it first writes publishes optional, and a key it re-sets keeps the value it held before the loop as one more type.
|
|
4357
|
+
- **`try`, `catch`, and `switch`**: their bodies are read in order. A key first written in one publishes optional, and a key re-set in one takes its last write's type.
|
|
4358
|
+
- **A key written more than once in a row**: the key takes the type of its last write. `+=` adds only the keys the array doesn't have yet. Assigning a whole new array drops the keys written before it. Inside one branch, it replaces them for that branch only, so a key that one side lacks publishes optional.
|
|
4359
|
+
- **An `unset()`**: `unset($data['slug'])` removes the key, and so does `unset($data[$key])` when `$key` is a local you assign a string literal once. Inside a block, it makes the key optional instead. In `unset($data['name'], $data[$hidden])`, the package removes `name` but can't follow `$data[$hidden]`. An index signature from an [interpolated key](#interpolated-keys) stays after an `unset()` of a literal key it matches, since its value already admits `undefined`.
|
|
3590
4360
|
- **Other `return` statements**: the variable counts as one branch beside the method's other returns, so a `return []` guard, or a returned array literal that leaves a key out, makes that key optional.
|
|
3591
4361
|
|
|
3592
|
-
|
|
4362
|
+
Here each key holds the value of every branch that can write it:
|
|
4363
|
+
|
|
4364
|
+
```php
|
|
4365
|
+
public function toArray(Request $request): array
|
|
4366
|
+
{
|
|
4367
|
+
$data = ['id' => $this->id, 'label' => $this->sort_order];
|
|
4368
|
+
|
|
4369
|
+
if ($this->is_active) {
|
|
4370
|
+
$data['mode'] = 1;
|
|
4371
|
+
} else {
|
|
4372
|
+
$data['mode'] = 'off';
|
|
4373
|
+
}
|
|
4374
|
+
|
|
4375
|
+
if ($this->sort_order === 1) {
|
|
4376
|
+
$data['tier'] = 'first';
|
|
4377
|
+
$data['first_only'] = true;
|
|
4378
|
+
} elseif ($this->sort_order === 2) {
|
|
4379
|
+
$data['tier'] = 2;
|
|
4380
|
+
} else {
|
|
4381
|
+
$data['tier'] = false;
|
|
4382
|
+
}
|
|
4383
|
+
|
|
4384
|
+
if ($this->description !== null) {
|
|
4385
|
+
$data['label'] = $this->name;
|
|
4386
|
+
$data['described'] = true;
|
|
4387
|
+
}
|
|
4388
|
+
|
|
4389
|
+
return $data;
|
|
4390
|
+
}
|
|
4391
|
+
```
|
|
4392
|
+
|
|
4393
|
+
On a `Category` resource, the variable publishes:
|
|
4394
|
+
|
|
4395
|
+
```typescript
|
|
4396
|
+
export interface CategorySummaryResource {
|
|
4397
|
+
id: number;
|
|
4398
|
+
label: number | string;
|
|
4399
|
+
mode: number | string;
|
|
4400
|
+
tier: string | number | boolean;
|
|
4401
|
+
first_only?: boolean;
|
|
4402
|
+
described?: boolean;
|
|
4403
|
+
}
|
|
4404
|
+
```
|
|
4405
|
+
|
|
4406
|
+
A value one branch writes that the package can't type is left out of the key's type, as [Values Left Out of a Union](#values-left-out-of-a-union) describes.
|
|
4407
|
+
|
|
4408
|
+
The package doesn't follow `$data[] = ...`, a key computed at runtime, such as `$data[$key]` where `$key` isn't a local holding one string literal, or a nested key such as `$data['meta']['label']`, whether written or passed to `unset()`. It also reads the method in one pass. A key written after an early `return $data;` publishes required when that write always runs, though the early return sends the array without it. A `continue` or `break` isn't followed either, so in a loop body, a write after an `if` that ends in `continue` replaces the `if`'s write, though Laravel can send the `if`'s value. In each case, return an array literal on each path, or list the keys with [`#[TsCasts]`](#overriding-property-types-with-tscasts), which can also mark a key optional.
|
|
4409
|
+
|
|
4410
|
+
`+` publishes PHP's array union, where the left side's keys win and the right side adds the keys it lacks. That holds in a key's value, so `['code' => 'in'] + ['code' => 0, 'lane' => 2]` publishes `{ code: string; lane: number }`, and in a whole return, such as `return parent::toArray($request) + ['note' => 'none'];`. Either side can be a local holding an array: with `$defaults = ['note' => 'none', 'id' => 'x']`, `return ['id' => $this->id] + $defaults;` publishes `id: number` and `note: string`.
|
|
4411
|
+
|
|
4412
|
+
A helper that you pass the array to, and that returns it, keeps the array's keys and adds the keys it writes. A vague `@return array<string, mixed>` on the helper doesn't hide them:
|
|
4413
|
+
|
|
4414
|
+
```php
|
|
4415
|
+
public function toArray(Request $request): array
|
|
4416
|
+
{
|
|
4417
|
+
$data = [
|
|
4418
|
+
'id' => $this->id,
|
|
4419
|
+
'title' => $this->title,
|
|
4420
|
+
'url' => url("/posts/{$this->id}"),
|
|
4421
|
+
'disabled' => false,
|
|
4422
|
+
];
|
|
4423
|
+
|
|
4424
|
+
return $this->guard($data);
|
|
4425
|
+
}
|
|
4426
|
+
|
|
4427
|
+
/**
|
|
4428
|
+
* @param array<string, mixed> $data
|
|
4429
|
+
* @return array<string, mixed>
|
|
4430
|
+
*/
|
|
4431
|
+
private function guard(array $data): array
|
|
4432
|
+
{
|
|
4433
|
+
if ($this->trashed()) {
|
|
4434
|
+
$data['url'] = null;
|
|
4435
|
+
$data['disabled'] = true;
|
|
4436
|
+
}
|
|
4437
|
+
|
|
4438
|
+
return $data;
|
|
4439
|
+
}
|
|
4440
|
+
```
|
|
4441
|
+
|
|
4442
|
+
The resource publishes the array's keys, with the helper's writes joined in:
|
|
4443
|
+
|
|
4444
|
+
```typescript
|
|
4445
|
+
export interface PostLinkResource {
|
|
4446
|
+
id: number;
|
|
4447
|
+
title: string;
|
|
4448
|
+
url: string | null;
|
|
4449
|
+
disabled: boolean;
|
|
4450
|
+
}
|
|
4451
|
+
```
|
|
4452
|
+
|
|
4453
|
+
The same holds when you use the helper's result as a value, so `'link' => $this->guard(['url' => url('/posts'), 'disabled' => false])` publishes `link: { url: string | null; disabled: boolean }`.
|
|
4454
|
+
|
|
4455
|
+
When a helper's array starts from a value the package can't read, such as `$request->all()`, a key that holds the helper's result publishes the keys the helper writes, plus an index signature for the rest. When all the package can read of a helper's array is its `@return array<string, mixed>`, such a key publishes `Record<string, unknown>`:
|
|
4456
|
+
|
|
4457
|
+
```php
|
|
4458
|
+
public function toArray(Request $request): array
|
|
4459
|
+
{
|
|
4460
|
+
return [
|
|
4461
|
+
'filters' => $this->filters($request),
|
|
4462
|
+
'options' => $this->options(),
|
|
4463
|
+
];
|
|
4464
|
+
}
|
|
4465
|
+
|
|
4466
|
+
/** @return array<string, mixed> */
|
|
4467
|
+
private function filters(Request $request): array
|
|
4468
|
+
{
|
|
4469
|
+
$filters = $request->all();
|
|
4470
|
+
$filters['page'] = 1;
|
|
4471
|
+
|
|
4472
|
+
return $filters;
|
|
4473
|
+
}
|
|
4474
|
+
|
|
4475
|
+
/** @return array<string, mixed> */
|
|
4476
|
+
private function options(): array
|
|
4477
|
+
{
|
|
4478
|
+
return json_decode($this->content, true);
|
|
4479
|
+
}
|
|
4480
|
+
```
|
|
4481
|
+
|
|
4482
|
+
`filters` keeps the key the helper writes, and `options` publishes a record:
|
|
3593
4483
|
|
|
3594
|
-
|
|
4484
|
+
```typescript
|
|
4485
|
+
export interface PostFiltersResource {
|
|
4486
|
+
filters: { page: number; [key: string]: unknown };
|
|
4487
|
+
options: Record<string, unknown>;
|
|
4488
|
+
}
|
|
4489
|
+
```
|
|
3595
4490
|
|
|
3596
4491
|
#### Return Branches and `@return` Shapes
|
|
3597
4492
|
|
|
@@ -3628,7 +4523,7 @@ trait GathersPermissions
|
|
|
3628
4523
|
/** Untyped, so only the docblocks above can type what it returns. */
|
|
3629
4524
|
protected function opaque()
|
|
3630
4525
|
{
|
|
3631
|
-
return $this->resource->
|
|
4526
|
+
return json_decode($this->resource->payload);
|
|
3632
4527
|
}
|
|
3633
4528
|
}
|
|
3634
4529
|
```
|
|
@@ -3648,13 +4543,45 @@ export interface PostPermissionsResource {
|
|
|
3648
4543
|
Both forms of `@return` count:
|
|
3649
4544
|
|
|
3650
4545
|
- **An `array{...}` shape**: each key gets its own type, and a key written `key?:` also becomes optional. A string or number literal type, such as `'draft'|'live'` or `1|2|3`, publishes as written.
|
|
3651
|
-
- **`array<string, V>`**: `V` types every key the body left
|
|
4546
|
+
- **`array<string, V>`**: `V` types every key the body left vague.
|
|
3652
4547
|
|
|
3653
4548
|
`toArray()`'s own `@return array{...}` fills keys the same way.
|
|
3654
4549
|
|
|
3655
|
-
The body
|
|
4550
|
+
The body wins wherever it's specific, so a stale `@return` can't overwrite a type the package already knows. The docblock fills only a key the body left vague, such as `unknown`, `unknown[]`, or `Record<string, unknown>`, and keeps any `| null` the body found. It also fills an [interpolated key's](#interpolated-keys) value that the body left `unknown | undefined`.
|
|
4551
|
+
|
|
4552
|
+
A shape value that names a model, an enum, or an API resource keeps it at any depth, and the file imports it. Here `tags` is a nullable column cast to `'array'`, which publishes `unknown[] | null` on its own, and `json_decode()` returns a value the package can't type:
|
|
4553
|
+
|
|
4554
|
+
```php
|
|
4555
|
+
/**
|
|
4556
|
+
* @return array{
|
|
4557
|
+
* tags: list<string>,
|
|
4558
|
+
* extra: array{author: User, status: PostStatus},
|
|
4559
|
+
* }
|
|
4560
|
+
*/
|
|
4561
|
+
public function toArray(Request $request): array
|
|
4562
|
+
{
|
|
4563
|
+
return [
|
|
4564
|
+
'tags' => $this->tags,
|
|
4565
|
+
'extra' => json_decode($this->extra_json, true),
|
|
4566
|
+
];
|
|
4567
|
+
}
|
|
4568
|
+
```
|
|
4569
|
+
|
|
4570
|
+
The docblock fills both keys, and `tags` keeps its `| null`:
|
|
4571
|
+
|
|
4572
|
+
```typescript
|
|
4573
|
+
import type { PostStatusType } from "../../enums";
|
|
4574
|
+
import type { User } from "../../models";
|
|
4575
|
+
|
|
4576
|
+
export interface PostExtrasResource {
|
|
4577
|
+
tags: string[] | null;
|
|
4578
|
+
extra: { author: User; status: PostStatusType };
|
|
4579
|
+
}
|
|
4580
|
+
```
|
|
4581
|
+
|
|
4582
|
+
A spread method's fill keeps its classes only when you spread the method at the top level of `toArray()`. Spread inside a nested array, as in `'meta' => [...$this->extras()]`, each model, enum, or API resource the fill names publishes `unknown`. Type such a key with `#[TsCasts]` and an `import`.
|
|
3656
4583
|
|
|
3657
|
-
A
|
|
4584
|
+
A name that isn't a PHP class, such as a type you declare only in TypeScript, publishes as written in a spread method's `@return`. In `toArray()`'s own `@return`, the key stays `unknown`, so type it with `#[TsCasts]`.
|
|
3658
4585
|
|
|
3659
4586
|
In a spread method, the branches count only while every `return` is an array literal, `[]`, or a variable the method builds. Otherwise, only the spread method's first `return` counts.
|
|
3660
4587
|
|
|
@@ -3769,6 +4696,8 @@ members?: (Omit<User, "flag"> & { flag: boolean })[];
|
|
|
3769
4696
|
|
|
3770
4697
|
The `Omit<>` matters. In PHP the later key wins, so `'flag'` replaces whatever the spread contributed. TypeScript's `&` would instead intersect both, and turn a conflicting key into `never`. When one literal holds several spreads, each spread's `Omit<>` removes every key that a later spread or an explicit key overwrites, in source order.
|
|
3771
4698
|
|
|
4699
|
+
The spread uses the model the variable holds, on any collection a `map()` runs over. `collect($this->comments)->map(fn (Comment $comment) => [...$comment->toArray(), 'flag' => true])->all()` publishes `(Omit<Comment, "flag"> & { flag: boolean })[]`. A local inside the callback spreads its own model, so `$author = $comment->user;` followed by `[...$author->toArray(), 'x' => 1]` publishes `Omit<User, "x"> & { x: number }` for each comment.
|
|
4700
|
+
|
|
3772
4701
|
At the top level of `toArray()`, a spread with no key flattens into the resource's own properties instead. `...$this->user->toArray()` adds the user's properties to the interface, and `...PostResource::make($this->post)->resolve()` adds the post resource's. A collection's `...$this->tags->toArray()` adds a `[key: number]` index signature.
|
|
3773
4702
|
|
|
3774
4703
|
The intersection references the `{Model}` interface instead of copying its shape. That comes close to what `toArray()` returns at runtime, with two differences:
|
|
@@ -3865,7 +4794,7 @@ replies: Comment[];
|
|
|
3865
4794
|
kept: Comment[] | null;
|
|
3866
4795
|
```
|
|
3867
4796
|
|
|
3868
|
-
A `?->` on `$this->resource` adds `| null` once, because a resource can wrap `null`. `$this->resource?->comments->only([1, 2])` publishes `Comment[] | null`.
|
|
4797
|
+
A `?->` on `$this->resource` adds `| null` once, because a resource can wrap `null`. `$this->resource?->comments->only([1, 2])` publishes `Comment[] | null`. A variable that holds the relation's collection filters the same way, so `'picked' => $this->whenLoaded('comments', fn ($comments) => $comments->only([1, 2]))` publishes `picked?: Comment[]`.
|
|
3869
4798
|
|
|
3870
4799
|
An accessor that returns an Eloquent collection of models filters the same way. It publishes a list of those models, such as `Comment[]`, whatever key type the accessor declares.
|
|
3871
4800
|
|
|
@@ -4154,13 +5083,30 @@ Laravel throws when the items are a plain collection, or a paginator without tha
|
|
|
4154
5083
|
|
|
4155
5084
|
If the collection always receives one kind of paginator, redeclare `$resource` with it. With `/** @var LengthAwarePaginator<int, UserResource> */ public $resource;`, `page` publishes `LengthAwarePaginator<UserResource>`.
|
|
4156
5085
|
|
|
5086
|
+
An `instanceof` test on `$this->resource` narrows the items to the paginator it names, in a ternary's arm, inside an `if` block, or after a guard. A read outside what the test proves keeps every shape:
|
|
5087
|
+
|
|
5088
|
+
```php
|
|
5089
|
+
public function toArray(Request $request): array
|
|
5090
|
+
{
|
|
5091
|
+
if ($this->resource instanceof LengthAwarePaginator) {
|
|
5092
|
+
return ['pager' => $this->resource];
|
|
5093
|
+
}
|
|
5094
|
+
|
|
5095
|
+
return ['pager' => null];
|
|
5096
|
+
}
|
|
5097
|
+
```
|
|
5098
|
+
|
|
5099
|
+
Here `pager` publishes `LengthAwarePaginator<UserResource> | null`.
|
|
5100
|
+
|
|
4157
5101
|
A call the collection forwards to `$this->resource`, such as `$this->first()` or `$this->total()`, publishes the same type. In a [key-preserving collection](#key-preserving-collections), the list type is `Record<string, UserResource>`. When no singular resource matches, each type holds `unknown`, such as `unknown[]` and `LengthAwarePaginator<unknown>`.
|
|
4158
5102
|
|
|
4159
|
-
|
|
5103
|
+
A read on the item `first()` or `last()` returns takes the type of the singular resource's model. In a `PostCollection` that collects `PostResource`, `$this->resource->first()?->title`, `$this->collection->first()?->title`, and `$this->collection->last()?->title` each publish `string | null`.
|
|
5104
|
+
|
|
5105
|
+
The package doesn't follow a collection pipeline on `$this->resource`, such as `map()`, `pluck()` or `values()`. Each publishes `unknown`. Type such a key with [`#[TsCasts]`](#overriding-property-types-with-tscasts).
|
|
4160
5106
|
|
|
4161
5107
|
#### Paginated Collections
|
|
4162
5108
|
|
|
4163
|
-
A collection's interface covers what its `toArray()` returns. The `links` and `meta` keys Laravel adds to a paginated response, and any data you add with `with()` or `additional()`, aren't part of it. An Inertia page prop that passes a paginator to a resource collection gets its pagination members from the page prop's type instead, with the `meta` block of each paginator kind. See [Paginating Inline in the Render Call](https://tolki.abe.dev/ts/inertia.html#paginating-inline-in-the-render-call) on the Inertia page.
|
|
5109
|
+
A collection's interface covers what its `toArray()` returns. The `links` and `meta` keys Laravel adds to a paginated response, and any data you add with `with()` or `additional()`, aren't part of it. An Inertia page prop that passes a paginator to a resource collection gets its pagination members from the page prop's type instead, with the `meta` block of each paginator kind. An Inertia prop's type also carries the `with()` and `additional()` keys. See [Paginating Inline in the Render Call](https://tolki.abe.dev/ts/inertia.html#paginating-inline-in-the-render-call) on the Inertia page.
|
|
4164
5110
|
|
|
4165
5111
|
Over a paginator, Laravel merges a `meta` or `links` key that your `toArray()` returns beside `data` into its own pagination block with `array_merge_recursive()`, and it merges the `with()` and `additional()` data the same way. A key your `toArray()` adds, such as `links.self`, is in the page prop's type. A key that two of these name, such as `meta.total`, is sent as a list of both values, such as `[3, 3]`, while the type still says `number`. Give your key another name, or remove from `paginationInformation()` only the key your `toArray()` also sends. The package doesn't read `paginationInformation()`, so any other change there leaves the published pagination type wrong.
|
|
4166
5112
|
|
|
@@ -4336,9 +5282,10 @@ The package already types these shapes without an override:
|
|
|
4336
5282
|
- A method call on an enum, a date, a model, or a service, and a property read on any of those or on a value object. See [Method Return Types](#method-return-types).
|
|
4337
5283
|
- A value behind a local variable, a closure-local variable, or an `instanceof` guard. See [Local Variables and Narrowing](#local-variables-and-narrowing).
|
|
4338
5284
|
- A collection chain, `data_get()`, and `only([...])` on any model. See [Collection Pipelines](#collection-pipelines) and [Attribute Filters on Any Model](#attribute-filters-on-any-model).
|
|
4339
|
-
- A key that only some branches return, or one that a spread method's `@return` describes. See [Return Branches and `@return` Shapes](#return-branches-and-return-shapes).
|
|
5285
|
+
- A key that only some branches return, or one that `toArray()`'s or a spread method's `@return` describes. See [Return Branches and `@return` Shapes](#return-branches-and-return-shapes).
|
|
5286
|
+
- A model, an enum, or an API resource in the array of a method you use as a value. See [Methods Declared as a Bare `array`](#methods-declared-as-a-bare-array).
|
|
4340
5287
|
|
|
4341
|
-
`#[TsCasts]` is the right tool when the frontend owns the type and it needs its own import, or when a shape is dynamic.
|
|
5288
|
+
`#[TsCasts]` is the right tool when the frontend owns the type and it needs its own import, or when a shape is dynamic. To type every value of a class that way, put [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) on the class instead.
|
|
4342
5289
|
|
|
4343
5290
|
Use `#[TsCasts]` to override a property's type, or to add a property that `toArray()` doesn't return:
|
|
4344
5291
|
|
|
@@ -4461,6 +5408,26 @@ A `when()`, ternary, `mergeWhen()`, `transform()`, `if` block or earlier `return
|
|
|
4461
5408
|
|
|
4462
5409
|
A resource built directly around a relation gets the `| null` only when the package can type that relation. A relation the model doesn't declare, a relation to a model the package doesn't publish, and a `morphTo` with no resolvable target publish without it. Inside a `whenLoaded()` closure, the relation's own rule applies instead, so `$this->whenLoaded('parent', fn ($parent) => CategoryResource::make($parent))` publishes `CategoryResource | null` whenever `parent` can load `null`. In that closure, a relation the model doesn't declare counts as one that can load `null` while `nullable_relations` is on.
|
|
4463
5410
|
|
|
5411
|
+
A `whenLoaded()` value that hands the relation to a resource's `collection()` is the exception. Only a to-many relation, which loads as a list, fits there, so `$this->whenLoaded('branches', CategoryResource::collection(...))` publishes `branches?: CategoryResource[]` even when the package can't read `branches`.
|
|
5412
|
+
|
|
5413
|
+
Inside a `map()`, Laravel turns a nested resource with a `null` payload into `null` only where it reaches the mapped items as an array, so the `| null` depends on how the chain ends. On a `Team` resource, where `members` holds users and `profile` is a `HasOne` relation:
|
|
5414
|
+
|
|
5415
|
+
```php
|
|
5416
|
+
'profiles' => $this->members->map(fn (User $member) => ['profile' => new ProfileResource($member->profile)]),
|
|
5417
|
+
'profiles_all' => $this->members->map(fn (User $member) => ['profile' => new ProfileResource($member->profile)])->all(),
|
|
5418
|
+
```
|
|
5419
|
+
|
|
5420
|
+
Only the chain that ends in `->all()` adds `| null`:
|
|
5421
|
+
|
|
5422
|
+
```typescript
|
|
5423
|
+
interface TeamResource {
|
|
5424
|
+
profiles: { profile: ProfileResource }[];
|
|
5425
|
+
profiles_all: { profile: ProfileResource | null }[];
|
|
5426
|
+
}
|
|
5427
|
+
```
|
|
5428
|
+
|
|
5429
|
+
Without `->all()`, or through `->values()`, a member with no profile makes Laravel throw instead of sending `null`.
|
|
5430
|
+
|
|
4464
5431
|
To turn off nullable relation detection everywhere:
|
|
4465
5432
|
|
|
4466
5433
|
```php
|
|
@@ -4819,7 +5786,7 @@ final class PostScheduled implements ShouldBroadcast
|
|
|
4819
5786
|
|
|
4820
5787
|
private function publishedAt() // no return type
|
|
4821
5788
|
{
|
|
4822
|
-
return $this->post->
|
|
5789
|
+
return json_decode($this->post->schedule)->published_at;
|
|
4823
5790
|
}
|
|
4824
5791
|
}
|
|
4825
5792
|
```
|
|
@@ -4883,6 +5850,58 @@ export interface ManifestAssembled {
|
|
|
4883
5850
|
|
|
4884
5851
|
[Building the Array in a Variable](https://tolki.abe.dev/ts/api-resources.html#building-the-array-in-a-variable) on the API Resources page lists the writes the package follows.
|
|
4885
5852
|
|
|
5853
|
+
A query chain that starts at a model is typed step by step, as in [page props](https://tolki.abe.dev/ts/routing.html#what-the-props-expression-can-be). `Post::query()->pluck('id')->first()` publishes `number | null`. A model the chain returns is presented as `Partial<Model>`, as a [model property](#model--enum-aware-properties) is, so `User::find($this->userId)` publishes `Partial<User> | null` and `User::query()->where('id', 1)->get()` publishes `Partial<User>[]`.
|
|
5854
|
+
|
|
5855
|
+
An `EnumResource` around an enum that may be `null` adds `| never[]`, and so does each element of a `map()` of such wraps, because an event sends the empty resource as `[]`.
|
|
5856
|
+
|
|
5857
|
+
#### `when()` and `unless()` From `Conditionable`
|
|
5858
|
+
|
|
5859
|
+
An event that uses Laravel's `Conditionable` trait can call `$this->when()` and `$this->unless()` in `broadcastWith()`. Unlike a resource's `when()`, they always send the key: the callback's value when the condition holds, the default's when it doesn't, and the event itself where either one returns `null` or no default is passed. The key publishes that union, required:
|
|
5860
|
+
|
|
5861
|
+
```php
|
|
5862
|
+
class PostPinned implements ShouldBroadcast
|
|
5863
|
+
{
|
|
5864
|
+
use Conditionable;
|
|
5865
|
+
|
|
5866
|
+
public function __construct(public Post $post) {}
|
|
5867
|
+
|
|
5868
|
+
public function broadcastWith(): array
|
|
5869
|
+
{
|
|
5870
|
+
$pinned = $this->post->is_pinned;
|
|
5871
|
+
|
|
5872
|
+
return [
|
|
5873
|
+
'label' => $this->when($pinned, fn () => 'active'),
|
|
5874
|
+
'with_default' => $this->when(
|
|
5875
|
+
$pinned,
|
|
5876
|
+
fn () => 'pinned',
|
|
5877
|
+
fn () => 'unpinned',
|
|
5878
|
+
),
|
|
5879
|
+
];
|
|
5880
|
+
}
|
|
5881
|
+
|
|
5882
|
+
public function broadcastOn(): Channel
|
|
5883
|
+
{
|
|
5884
|
+
return new Channel('posts');
|
|
5885
|
+
}
|
|
5886
|
+
}
|
|
5887
|
+
```
|
|
5888
|
+
|
|
5889
|
+
`label` can send the event itself, whose JSON is its public `post` property:
|
|
5890
|
+
|
|
5891
|
+
```typescript
|
|
5892
|
+
import type { Post } from "../models";
|
|
5893
|
+
|
|
5894
|
+
/** @see App\Events\PostPinned */
|
|
5895
|
+
export interface PostPinned {
|
|
5896
|
+
label: string | { post: Post };
|
|
5897
|
+
with_default: string;
|
|
5898
|
+
}
|
|
5899
|
+
```
|
|
5900
|
+
|
|
5901
|
+
The event's own JSON joins the type only when the package knows it. An event `make:event` generates uses `InteractsWithSockets`, whose untyped `$socket` property leaves that JSON unknown, so a key that can send such an event publishes `unknown`. Pass a default that returns a value, as `with_default` does, or type the key with [`#[TsCasts]`](#overriding-property-types-with-tscasts).
|
|
5902
|
+
|
|
5903
|
+
A resource built around the call, such as `UserResource::make($this->when(…))`, is always sent too, so it publishes required.
|
|
5904
|
+
|
|
4886
5905
|
### Model & Enum-Aware Properties
|
|
4887
5906
|
|
|
4888
5907
|
A property typed as an Eloquent model or a PHP enum resolves to the type the rest of the package uses for it. The file imports that type for you:
|
|
@@ -5018,6 +6037,8 @@ An entry publishes its type exactly as written, without the `Partial<>` a model
|
|
|
5018
6037
|
|
|
5019
6038
|
You can also put `#[TsCasts]` on `broadcastWith()`. It works the same way as on the class, and the class's entry wins when both name a key.
|
|
5020
6039
|
|
|
6040
|
+
To type every property that holds a given class, in every event, put [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) on that class instead of an entry on each event.
|
|
6041
|
+
|
|
5021
6042
|
### Extending Interfaces: Global Config vs. `#[TsExtends]`
|
|
5022
6043
|
|
|
5023
6044
|
An event interface can extend shared interfaces through config, through an attribute, or through both at once.
|
|
@@ -5296,11 +6317,11 @@ class UserResource extends JsonResource
|
|
|
5296
6317
|
}
|
|
5297
6318
|
```
|
|
5298
6319
|
|
|
5299
|
-
Inside another resource, `EnumResource::make($this->status)` and `new EnumResource($this->status)` both publish the property as `AsEnum<typeof Status>`. See [Enum Properties With `EnumResource`](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource) on the API Resources page.
|
|
6320
|
+
Inside another resource, `EnumResource::make($this->status)` and `new EnumResource($this->status)` both publish the property as `AsEnum<typeof Status>`. See [Enum Properties With `EnumResource`](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource) on the API Resources page. A bare value sends no object: `'status' => Status::Published->value` publishes that case's own value, `1`. [Reading `->value` and `->name`](https://tolki.abe.dev/ts/enums.html#reading-value-and-name) covers bare values and `cases()`.
|
|
5300
6321
|
|
|
5301
|
-
The same rewrite applies to [Inertia shared data](https://tolki.abe.dev/ts/inertia.html). With `enums.use_tolki_package` on (the default), an `EnumResource::make()` returned from your middleware's `share()` publishes as `AsEnum<typeof Role>` in `inertia-config.d.ts`, with `import { type AsEnum } from '@tolki/ts'` and an import of the `Role` const above the declarations.
|
|
6322
|
+
The same rewrite applies to [Inertia shared data](https://tolki.abe.dev/ts/inertia.html). With `enums.use_tolki_package` on (the default), an `EnumResource::make()` returned from your middleware's `share()` publishes as `AsEnum<typeof Role>` in `inertia-config.d.ts`, with `import { type AsEnum } from '@tolki/ts'` and an import of the `Role` const above the declarations. Route page props are rewritten the same way. See the `EnumResource` notes in [How the Augmentation File Is Generated](https://tolki.abe.dev/ts/inertia.html#how-the-augmentation-file-is-generated).
|
|
5302
6323
|
|
|
5303
|
-
`EnumResource` turns off Laravel's resource wrapping (`public static $wrap = ''`), so the response is the flat object shown below, not wrapped in a `data` key. When the enum is `null`, the resource returns `null` instead of an object.
|
|
6324
|
+
`EnumResource` turns off Laravel's resource wrapping (`public static $wrap = ''`), so the response is the flat object shown below, not wrapped in a `data` key. When the enum is `null`, the resource returns `null` instead of an object. As an Inertia page prop or shared value, Inertia sends `[]` instead, so the prop publishes `AsEnum<typeof Status> | never[]`. A broadcast event's payload, and a `map()` of wraps kept as a collection inside another resource, send `[]` too, and publish `| never[]`. See [Enum Properties With `EnumResource`](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource).
|
|
5304
6325
|
|
|
5305
6326
|
### Response Shape
|
|
5306
6327
|
|
|
@@ -5326,7 +6347,7 @@ The response for `Status::Published`, with two instance methods, looks like this
|
|
|
5326
6347
|
|
|
5327
6348
|
Each instance method, marked with `#[TsEnumMethod]` or included by `enums.auto_include_methods`, adds a top-level key that holds the method's value for this case. Each static method, marked with `#[TsEnumStaticMethod]` or included by `enums.auto_include_static_methods`, adds a top-level key that holds its return value.
|
|
5328
6349
|
|
|
5329
|
-
Each method key holds the same value as the published enum, as `json_encode()` writes it. A method that throws for the case, or returns a value `json_encode()` can't write, sends `null`. [Object and Array Values](https://tolki.abe.dev/ts/enums.html#object-and-array-values) shows how an object
|
|
6350
|
+
Each method key holds the same value as the published enum, as `json_encode()` writes it. A method that throws for the case, or returns a value `json_encode()` can't write, sends `null`. [Object and Array Values](https://tolki.abe.dev/ts/enums.html#object-and-array-values) shows how an object or an array becomes JSON.
|
|
5330
6351
|
|
|
5331
6352
|
The response therefore has the same keys as the object you get when you call `.from()` on the published enum with the same value.
|
|
5332
6353
|
|
|
@@ -5463,7 +6484,7 @@ When two enums share a class name, both imports get a namespace prefix, for the
|
|
|
5463
6484
|
|
|
5464
6485
|
## Excluding Content
|
|
5465
6486
|
|
|
5466
|
-
Add the `#[TsExclude]` attribute to keep a class out of the TypeScript output, or to leave out one of its methods, accessors, relations, or controller actions. It works on enums, models, resources, form requests, broadcast events, and controllers. It's a PHP attribute only. It has no config key, and there's nothing to set up in `@tolki/ts`.
|
|
6487
|
+
Add the `#[TsExclude]` attribute to keep a class out of the TypeScript output, or to leave out one of its methods, accessors, relations, or controller actions. It works on enums, models, resources, form requests, broadcast events, and controllers. On a class with a [composed type](https://tolki.abe.dev/ts/custom-types.html#composed-types), it also stops the class composing. It's a PHP attribute only. It has no config key, and there's nothing to set up in `@tolki/ts`.
|
|
5467
6488
|
|
|
5468
6489
|
### `#[TsExclude]` Attribute
|
|
5469
6490
|
|
|
@@ -5609,6 +6630,8 @@ export const ExcludableEnum = defineEnum({
|
|
|
5609
6630
|
|
|
5610
6631
|
export type ExcludableEnumType = "alpha" | "beta";
|
|
5611
6632
|
export type ExcludableEnumKind = "Alpha" | "Beta";
|
|
6633
|
+
|
|
6634
|
+
export type ExcludableEnum = ExcludableEnumType;
|
|
5612
6635
|
```
|
|
5613
6636
|
|
|
5614
6637
|
`overridden()` and `overriddenStatic()` have attributes that would include them whatever the auto-include settings, but `#[TsExclude]` removes them. `label()` and `secret()` are missing because auto-include is off. Turn on `enums.auto_include_methods`, and `label()` publishes while `secret()` stays out. See [Auto-Including All Enum Methods](https://tolki.abe.dev/ts/enums.html#auto-including-all-enum-methods) for which methods auto-include adds.
|
|
@@ -6557,18 +7580,21 @@ This page covers shared data, and the API resources that shared data and a route
|
|
|
6557
7580
|
With `inertia.enabled` on (the default), the package builds the file from your middleware:
|
|
6558
7581
|
|
|
6559
7582
|
- **Finding the middleware**: the package searches `inertia.inertia_middleware_path`, or `app_path()` when that isn't set, for a class that extends `Inertia\Middleware`. If it finds none, it writes no file. If your app has more than one such class, point `inertia.inertia_middleware_path` at the directory that holds the one you want.
|
|
6560
|
-
- **Reading `share()`**: every key's value is typed from your code, without handling a real request. A `share()` that a trait supplies is read too, and so is one that builds its array in a variable and returns it. A key that the variable gets on only some paths, such as inside an `if`, is optional.
|
|
6561
|
-
- **Parent middleware**: a `...parent::share($request)` spread and `array_merge(parent::share($request), [...])` are both read, all the way up your middleware's parent classes. A later key overrides an earlier one and keeps the earlier one's position, as PHP does.
|
|
7583
|
+
- **Reading `share()`**: every key's value is typed from your code, without handling a real request. A `share()` that a trait supplies is read too, even under an alias such as `use SharesProps { base as share; }`, and so is one that builds its array in a variable and returns it. A key that the variable gets on only some paths, such as inside an `if`, is optional.
|
|
7584
|
+
- **Parent middleware**: a `...parent::share($request)` spread and `array_merge(parent::share($request), [...])` are both read, all the way up your middleware's parent classes. A later key overrides an earlier one and keeps the earlier one's position, as PHP does. A parent's `#[TsCasts]` applies too, as [Type Resolution Priority](#type-resolution-priority) describes.
|
|
7585
|
+
- **Dotted keys**: Inertia unpacks a top-level dotted key into nested objects, so `'auth.name' => $request->user()?->name` publishes `auth: { name: string | null }`. When the array also holds an `auth` array, `name` is added to it.
|
|
6562
7586
|
- **Integer keys**: Inertia merges shared data and page props with `array_merge()`, which renumbers integer keys from `0`. A top-level `42 => …` key therefore publishes as `"0"`, and `ts:publish` warns that you probably meant a string key. Nested keys keep theirs.
|
|
6563
|
-
-
|
|
7587
|
+
- **The signed-in user**: `$request->user()` is typed through your live auth config, from `auth.defaults.guard` to that guard's provider to the provider's `model`. The prop becomes `User | null`, and the file imports the model's type for you. `auth()->user()`, `Auth::user()`, `request()->user()` and `Auth::guard()->user()` resolve the same way, and so does a read past any of them, such as `auth()->user()?->name`, which publishes `string | null`. `auth()->id()` and `Auth::id()` publish the user's key, as described below.
|
|
6564
7588
|
- **Request helpers**: `$request->url()`, `fullUrl()`, `path()`, `integer()`, `boolean()`, `string()`, `cookie()` and `hasCookie()` are typed from Laravel's own signatures.
|
|
6565
7589
|
- **`config()`**: `config('some.key')` with a literal key is typed from the live config value, since the package runs inside your booted app. A computed key stays `unknown`.
|
|
6566
7590
|
- **Value helpers**: `now()` and `today()` are typed as `string`, or `Date` under [`timestamps_as_date`](https://tolki.abe.dev/ts/models.html#timestamps-as-date-objects). `str($value)` is typed as `string`, and `str()` with no argument as `Record<string, never>`. `url($path)` is typed as `string` when the path can't be `null`, and stays `unknown` when it can or has no type. `collect([...])` and a bare array literal are both typed as the list or object the array encodes as, such as `string[]` for `['a', 'b']`. `+` on two arrays is typed as PHP's array union, where the left side's keys win.
|
|
6567
|
-
- **Closures and first-class callables**: Inertia calls a callable prop before it sends it, so closures and first-class callables, such as `fn () => $request->url()` and `now(...)`, are typed from what the call returns.
|
|
6568
|
-
- **Inertia v2 prop wrappers**: `Inertia::defer()`, `optional()`, `lazy()`, `always()`, `merge()` and `deepMerge()` type as the value they wrap
|
|
7591
|
+
- **Closures and first-class callables**: Inertia calls a callable prop before it sends it, so closures and first-class callables, such as `fn () => $request->url()` and `now(...)`, are typed from what the call returns. That includes one inside an array that a helper method builds.
|
|
7592
|
+
- **Inertia v2 prop wrappers**: `Inertia::defer()`, `optional()`, `lazy()`, `always()`, `merge()` and `deepMerge()` type as the value they wrap, and so does a prop class you construct, such as `new OptionalProp(fn () => …)`. The three a partial reload can leave out, `defer`, `optional` and `lazy`, make the key optional.
|
|
6569
7593
|
- **API resources**: a resource or resource collection is typed as the response Inertia sends for it, as [API Resources in Props](#api-resources-in-props) describes.
|
|
6570
7594
|
- **`EnumResource` props**: a prop that wraps an enum in `EnumResource`, such as `'role' => EnumResource::make(Role::Admin)`, becomes `AsEnum<typeof Role>` when `enums.use_tolki_package` is on (the default), the same as in [API Resources](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource). With it off, the key keeps the enum's type alias (`role: RoleType`). The change applies per key, so another key that reads the enum directly keeps `RoleType`.
|
|
7595
|
+
- **`EnumResource` ternaries and `null`**: each arm of a ternary is typed as Laravel sends it. Wrapping two different enums publishes `AsEnum<typeof Role> | AsEnum<typeof Status>`, and a wrap beside a bare case of the same enum publishes `AsEnum<typeof Status> | StatusType`. A wrap around an enum that may be `null` publishes `AsEnum<typeof Status> | never[]`, because Inertia sends `[]` for it, not `null`. Tell the two apart with `Array.isArray()`.
|
|
6571
7596
|
- **Enum cases**: a bare case, such as `'defaultStatus' => Status::Draft`, is typed as the enum's type alias (`defaultStatus: StatusType`), which matches the value Laravel sends for a backed enum. The file imports the alias for you.
|
|
7597
|
+
- **Classes with `#[TsType]`**: a value of a class that has or inherits a `#[TsType]` is typed as that type, with its import, in shared data and page props alike. See [Custom Types](https://tolki.abe.dev/ts/custom-types.html).
|
|
6572
7598
|
- **`errors`**: left out. `@inertiajs/core` already types `page.props.errors` as `Errors & ErrorBag`, and [`errorValueType`](#anatomy-of-the-generated-file) sharpens it. A `#[TsCasts]` or `@return` docblock entry named `errors` still adds one if you want it.
|
|
6573
7599
|
- **The output file**: the result is written to `inertia-config.d.ts`. Set `inertia.augmentation_filename` to change the name.
|
|
6574
7600
|
|
|
@@ -6576,9 +7602,11 @@ With `inertia.enabled` on (the default), the package builds the file from your m
|
|
|
6576
7602
|
|
|
6577
7603
|
When the package can't create an instance of the model, it reads the key type from the class, and publishes `unknown` if code works the key out. A `getAuthIdentifierName()` that works the column out in code, such as from config, publishes `unknown` too, and so does an override of `getAuthIdentifier()`, since only running your app shows which value the ID holds.
|
|
6578
7604
|
|
|
6579
|
-
|
|
7605
|
+
The signed-in user is typed from the default guard only, so a named guard, such as `auth('admin')->user()` or `Auth::guard('admin')->user()`, publishes `unknown`. When your guards' providers name more than one user model, a route's guard middleware can sign in either one, so `request()->user()`, `Auth::guard()->user()` and a read past `auth()->user()`, `Auth::user()` or `request()->user()` publish `unknown` too. `$request->user()`, a bare `auth()->user()` or `Auth::user()`, `auth()->id()` and `Auth::id()` keep the default guard's model. Type such a key with [`#[TsCasts]`](#type-resolution-priority).
|
|
7606
|
+
|
|
7607
|
+
In a route's [page props](https://tolki.abe.dev/ts/routing.html#inertia-integration), `getKey()` on a route-bound model publishes the model's key type with no `| null`, because Laravel binds only a saved row. With a `Post $post` action parameter, `'post_id' => $post->getKey()` publishes `post_id: number`. A relation read on the parameter is typed by the models it loads, so `'comments' => $post->comments` publishes `comments: Comment[]`.
|
|
6580
7608
|
|
|
6581
|
-
A
|
|
7609
|
+
A few mixes of `EnumResource` arms publish a type that doesn't match what Laravel sends. A wrap beside a bare case of another enum, as in `$cond ? EnumResource::make(Role::Admin) : Status::Draft`, publishes `RoleType | StatusType`, though the first arm sends the `Role` object. A nested ternary over the wraps of three enums can leave a type alias unimported, which fails your build with `TS2304`. Override such a key with a `#[TsCasts]` entry that has an `import`.
|
|
6582
7610
|
|
|
6583
7611
|
### Anatomy of the Generated File
|
|
6584
7612
|
|
|
@@ -6635,13 +7663,13 @@ export {};
|
|
|
6635
7663
|
|
|
6636
7664
|
Each part of the file does one job:
|
|
6637
7665
|
|
|
6638
|
-
- **`import type { User } from "./app/models";`**: every model, resource or enum that a prop type names gets an import at the top, with a path relative to the output root. An `EnumResource` prop is the exception under the default `enums.use_tolki_package`. It renders as `AsEnum<typeof Role>`, so the enum's const is imported as a value (`import { Role } from './app/enums';`), under an `import { type AsEnum } from '@tolki/ts';` line, and both come before the `import type` lines. Imports from an `import` key in `#[TsCasts]` join the `import type` lines.
|
|
7666
|
+
- **`import type { User } from "./app/models";`**: every model, resource or enum that a prop type names gets an import at the top, with a path relative to the output root. An `EnumResource` prop is the exception under the default `enums.use_tolki_package`. It renders as `AsEnum<typeof Role>`, so the enum's const is imported as a value (`import { Role } from './app/enums';`), under an `import { type AsEnum } from '@tolki/ts';` line, and both come before the `import type` lines. Imports from an `import` key in `#[TsCasts]` join the `import type` lines. Two classes that share a name, such as `App\Enums\Status` and `App\Crm\Enums\Status`, are imported under aliases, as in `StatusType as CrmStatusType`.
|
|
6639
7667
|
- **`declare global { namespace Inertia { type SharedData = ...; } }`**: makes `Inertia.SharedData` available by name in any `.ts` file in your project. That includes the generated route files, which combine it with each page's props, as [Inertia Integration](https://tolki.abe.dev/ts/routing.html#inertia-integration) shows.
|
|
6640
7668
|
- **`declare module '@inertiajs/core' { ... }`**: augments Inertia's own `InertiaConfig`, so `usePage().props` is typed across your frontend without you writing the augmentation.
|
|
6641
7669
|
- **`errorValueType: string[]`**: added only when the middleware sets `protected $withAllErrors = true;`. It matches the shape Inertia uses for its validation errors in that mode.
|
|
6642
7670
|
- **`export {};`**: TypeScript accepts a `declare global` block only in a module, a file with at least one top-level `import` or `export`. This line makes the file a module even when it has no imports.
|
|
6643
7671
|
|
|
6644
|
-
The file imports only the names its types use. A key you override with `#[TsCasts]` drops the
|
|
7672
|
+
The file imports only the names its types use. A key you override with `#[TsCasts]` drops the imports its inferred type needed, but keeps the import of a class the override names and the key's value holds. `'owner' => 'User | null'` over `$request->user()` still imports `User`, with no `import` key.
|
|
6645
7673
|
|
|
6646
7674
|
A key that isn't a plain identifier, such as `'can-edit'` or `42`, is quoted, as in `"can-edit": boolean`. Route files quote a page prop's key the same way.
|
|
6647
7675
|
|
|
@@ -6651,8 +7679,8 @@ A value the package can't read stays `unknown`. `'flash' => ['success' => fn ()
|
|
|
6651
7679
|
|
|
6652
7680
|
Each key from `share()` takes its type from the first of these that covers it:
|
|
6653
7681
|
|
|
6654
|
-
1. **`#[TsCasts]`** on the middleware class or on its `share()` method. When both name a key, the method's entry wins, even when the two spell an index signature's name differently. It's the same attribute [models](https://tolki.abe.dev/ts/models.html#tscasts), [API resources](https://tolki.abe.dev/ts/api-resources.html#overriding-property-types-with-tscasts) and [broadcast events](https://tolki.abe.dev/ts/broadcast-events.html#overriding-property-types-with-tscasts) use.
|
|
6655
|
-
2. **A `@return array{...}` docblock** on `share()`. You write the shape by hand, for a key the package can't infer, such as a method call whose return type says nothing. A `key?:` entry makes that key optional.
|
|
7682
|
+
1. **`#[TsCasts]`** on the middleware class or on its `share()` method. When both name a key, the method's entry wins, even when the two spell an index signature's name differently. A parent middleware's entries apply too when your middleware inherits the parent's `share()` or reads it through `parent::share()`, and your class's entries win over the parent's. It's the same attribute [models](https://tolki.abe.dev/ts/models.html#tscasts), [API resources](https://tolki.abe.dev/ts/api-resources.html#overriding-property-types-with-tscasts) and [broadcast events](https://tolki.abe.dev/ts/broadcast-events.html#overriding-property-types-with-tscasts) use.
|
|
7683
|
+
2. **A `@return array{...}` docblock** on `share()`. You write the shape by hand, for a key the package can't infer, such as a method call whose return type says nothing. A `key?:` entry makes that key optional. A model or enum that a top-level key names, as in `owner: User`, is imported for you.
|
|
6656
7684
|
3. **Inference from your code**, the default. It covers plain values, nested arrays, conditionals, closures, spreads, `array_merge()`, `config()`, the request and auth helpers, and Inertia's prop wrappers.
|
|
6657
7685
|
|
|
6658
7686
|
A key that `#[TsCasts]` or the docblock names but `share()` doesn't return is added to the type.
|
|
@@ -6685,7 +7713,7 @@ Here `appName` takes its type from `#[TsCasts]` and `flash` takes its type from
|
|
|
6685
7713
|
|
|
6686
7714
|
### API Resources in Props
|
|
6687
7715
|
|
|
6688
|
-
Inertia sends an API resource prop as the resource's whole response, the same JSON a route that returns the resource sends. That holds at any depth of a route's page props and in `share()`,
|
|
7716
|
+
Inertia sends an API resource prop as the resource's whole response, the same JSON a route that returns the resource sends. That holds at any depth of a route's page props and in `share()`, including props that a helper method or another class's method builds, as in `Inertia::render('Posts/Show', $this->props->build())`. Each prop publishes that response:
|
|
6689
7717
|
|
|
6690
7718
|
```php
|
|
6691
7719
|
return Inertia::render('Posts/Show', [
|
|
@@ -6711,10 +7739,34 @@ Each kind of prop follows its own rule:
|
|
|
6711
7739
|
- **`Resource::collection()`** publishes `AnonymousResourceCollection<CommentResource>` from `@tolki/types`, which is `{ data: CommentResource[] }`.
|
|
6712
7740
|
- **A named collection** publishes its own interface, which already holds its wrap key. One whose `toArray()` returns no wrap key publishes `{ data: TagCollection }`, because Laravel nests that body under `data`.
|
|
6713
7741
|
- **`->toResourceCollection()`** with no argument publishes the collection Laravel guesses. Over an empty collection, Laravel skips the guess and sends `{ data: [] }`, so the prop also publishes that empty response, such as `UserCollection | { data: never[] }` or, over `paginate()`, `| JsonResourcePaginator<never>`. A guessed collection whose response is only its `data` list already fits it and gets no extra type.
|
|
7742
|
+
- **Keys beside `data`**: the keys that a resource's `with()` method or an `->additional([...])` call adds are published beside the body. A single resource merges them into its object, as in `{ data: PostResource; meta: { total: number } }`, and any other response is intersected with them, as in `AnonymousResourceCollection<CommentResource> & { meta: { total: number } }`. A `with()` key that a `when()` call may leave out arrives as `[]`, so it publishes `T | never[]`.
|
|
7743
|
+
- **A resolved resource**, from `->resolve()`, publishes the resource's own type, with no `data` key. Inertia still sends each API resource inside the resolved body as a response, so a key that holds one publishes that response, as the example below shows. `Resource::collection(...)->resolve()` publishes a list of the same.
|
|
7744
|
+
|
|
7745
|
+
Here `PostCardResource` returns `'author' => UserCardResource::make($this->author)` among its keys:
|
|
7746
|
+
|
|
7747
|
+
```php
|
|
7748
|
+
return Inertia::render('Posts/Show', [
|
|
7749
|
+
'post' => PostResource::make($post)->additional([
|
|
7750
|
+
'meta' => ['total' => $post->comments()->count()],
|
|
7751
|
+
]),
|
|
7752
|
+
'card' => PostCardResource::make($post)->resolve(),
|
|
7753
|
+
]);
|
|
7754
|
+
```
|
|
6714
7755
|
|
|
6715
|
-
|
|
7756
|
+
Both props publish what Inertia sends:
|
|
6716
7757
|
|
|
6717
|
-
|
|
7758
|
+
```typescript
|
|
7759
|
+
export type ShowPageProps = Inertia.SharedData & {
|
|
7760
|
+
post: { data: PostResource; meta: { total: number } };
|
|
7761
|
+
card: Omit<PostCardResource, "author"> & {
|
|
7762
|
+
author: { data: UserCardResource };
|
|
7763
|
+
};
|
|
7764
|
+
};
|
|
7765
|
+
```
|
|
7766
|
+
|
|
7767
|
+
After `->resolve()`, a resource collection class with its own `toArray()` publishes its items bare, though Inertia sends each one under `data`. Pass the collection itself, or type the prop with [`#[TsCasts]`](https://tolki.abe.dev/ts/routing.html#overriding-props-with-tscasts).
|
|
7768
|
+
|
|
7769
|
+
The wrap key is the one your app sets by the time `ts:publish` runs, as [The Wrap Key Your App Sets](https://tolki.abe.dev/ts/api-resources.html#the-wrap-key-your-app-sets) describes. After `JsonResource::withoutWrapping()`, a single resource publishes the bare `PostResource`, and `Resource::collection()` over items that aren't paginated publishes `CommentResource[]`. Over a paginator, Laravel keeps the `data` key. Keys from `with()` or `additional()` also make Laravel nest the resource under `data`, and the prop publishes it that way. After `JsonResource::wrap('items')`, a single resource publishes `{ items: PostResource }`.
|
|
6718
7770
|
|
|
6719
7771
|
#### JSON:API Resources in Props
|
|
6720
7772
|
|
|
@@ -6789,7 +7841,7 @@ export type IndexPageProps = Inertia.SharedData & {
|
|
|
6789
7841
|
};
|
|
6790
7842
|
```
|
|
6791
7843
|
|
|
6792
|
-
`paginate()`, `simplePaginate()`, and `cursorPaginate()` are all recognized, in the `new SomeCollection(...)`, `SomeResource::collection(...)`, and `->toResourceCollection()` forms.
|
|
7844
|
+
`paginate()`, `simplePaginate()`, and `cursorPaginate()` are all recognized, in the `new SomeCollection(...)`, `SomeResource::collection(...)`, and `->toResourceCollection()` forms. The paginator can also come from a query builder held in a variable, or from a controller method or an injected service's method, typed from the method's return type or its body. A call that hands back the same paginator, such as `withQueryString()`, `appends()` or `onEachSide()`, keeps its kind.
|
|
6793
7845
|
|
|
6794
7846
|
Each paginator sends its own `meta` block, so each gets its own type from `@tolki/types`. A named collection adds the pagination type to its own interface. An anonymous collection, from `SomeResource::collection(...)`, publishes the paginator's whole response, and so does a collection with `$wrap = null`, because Laravel sends it under `data` over a paginator. In this list, the named form comes first, and `R` is the collected resource:
|
|
6795
7847
|
|
|
@@ -6799,17 +7851,16 @@ Each paginator sends its own `meta` block, so each gets its own type from `@tolk
|
|
|
6799
7851
|
|
|
6800
7852
|
A prop that can hold more than one paginator kind, such as a ternary over `paginate()` and `simplePaginate()`, publishes `TeamCollection & (ResourceSimplePagination | ResourcePagination)`. One that can hold a plain collection or a paginator publishes both shapes, `TeamCollection | (TeamCollection & ResourcePagination)`. A collection that `share()` returns is typed the same way.
|
|
6801
7853
|
|
|
6802
|
-
When the package
|
|
7854
|
+
When the package can't tell which paginator a payload holds, the prop gets the collection's type without the pagination part, a wrong type rather than a missing one. That happens with a method declared to return the `Paginator` contract, which more than one paginator kind implements, or with one that has no return type and a body the package can't read:
|
|
6803
7855
|
|
|
6804
7856
|
```php
|
|
6805
|
-
|
|
6806
|
-
|
|
7857
|
+
// page() is declared to return the Paginator contract
|
|
6807
7858
|
return Inertia::render('Posts/Index', [
|
|
6808
|
-
'posts' => new PostCollection($
|
|
7859
|
+
'posts' => new PostCollection($this->posts->page()),
|
|
6809
7860
|
]);
|
|
6810
7861
|
```
|
|
6811
7862
|
|
|
6812
|
-
Here `posts` types as `PostCollection`, without `& ResourcePagination
|
|
7863
|
+
Here `posts` types as `PostCollection`, without `& ResourcePagination`. A paginator passed without a resource is typed only from a query chain that starts at a model, or from a method that returns one. From a query builder held in a variable, it publishes `unknown`. Declare the paginator class the method returns, such as `LengthAwarePaginator`, build the paginator in the props, or type the prop with [`#[TsCasts]`](https://tolki.abe.dev/ts/routing.html#overriding-props-with-tscasts).
|
|
6813
7864
|
|
|
6814
7865
|
### Output Location
|
|
6815
7866
|
|
|
@@ -6825,7 +7876,7 @@ The [Configuration Reference](https://tolki.abe.dev/ts/configuration-reference.h
|
|
|
6825
7876
|
|
|
6826
7877
|
## Modular Publishing
|
|
6827
7878
|
|
|
6828
|
-
The package writes every TypeScript file into a directory tree that mirrors your PHP namespaces. There's no flat-output mode, and no setting to turn this off. Modular and domain-driven apps, such as those built with [InterNACHI/modular](https://github.com/InterNACHI/modular), keep each module's types together, and a single-namespace app gets one `app/` tree. Models, enums, resources, form requests, broadcast events, and
|
|
7879
|
+
The package writes every TypeScript file into a directory tree that mirrors your PHP namespaces. There's no flat-output mode, and no setting to turn this off. Modular and domain-driven apps, such as those built with [InterNACHI/modular](https://github.com/InterNACHI/modular), keep each module's types together, and a single-namespace app gets one `app/` tree. Models, enums, resources, form requests, broadcast events, routes, and [composed types](https://tolki.abe.dev/ts/custom-types.html#composed-types) all follow the same rule.
|
|
6829
7880
|
|
|
6830
7881
|
### Output Structure
|
|
6831
7882
|
|
|
@@ -7001,7 +8052,7 @@ import type { Invoice } from "@data/accounting/models";
|
|
|
7001
8052
|
import type { InvoiceStatusType } from "@data/accounting/enums";
|
|
7002
8053
|
```
|
|
7003
8054
|
|
|
7004
|
-
Models, enums, resources, form requests, broadcast events, and routes each write their own barrels. A route barrel re-exports each controller's default export by name, such as `export { default as PostController } from './post-controller';`, rather than using `export *`. That keeps two controllers with a method of the same name from clashing.
|
|
8055
|
+
Models, enums, resources, form requests, broadcast events, and routes each write their own barrels, and composed types add their modules to their namespace's barrel. A route barrel re-exports each controller's default export by name, such as `export { default as PostController } from './post-controller';`, rather than using `export *`. That keeps two controllers with a method of the same name from clashing.
|
|
7005
8056
|
|
|
7006
8057
|
`ts:publish --preview=true` prints each barrel's contents under its own label, such as `Model Barrel Files:` or `Enum Barrel Files:`, next to the per-class files. A verbose run, `ts:publish -v`, lists each barrel file's path in its Extras table.
|
|
7007
8058
|
|
|
@@ -7520,11 +8571,12 @@ The package reads the props argument as an expression, not only as an array lite
|
|
|
7520
8571
|
public function show(Post $post, Request $request): Response
|
|
7521
8572
|
{
|
|
7522
8573
|
return Inertia::render('Posts/Show', [
|
|
7523
|
-
'post' => $post,
|
|
8574
|
+
'post' => $post->load('author:id,name'),
|
|
7524
8575
|
'comments' => Comment::query()->latest()->get(),
|
|
7525
8576
|
'author' => $request->user(),
|
|
8577
|
+
'viewer' => auth()->user()?->name,
|
|
7526
8578
|
'page' => $request->integer('page'),
|
|
7527
|
-
'related' => Post::query()->paginate(10),
|
|
8579
|
+
'related' => Post::query()->paginate(10)->withQueryString(),
|
|
7528
8580
|
'tally' => Inertia::defer(fn () => Comment::query()->count()),
|
|
7529
8581
|
]);
|
|
7530
8582
|
}
|
|
@@ -7534,32 +8586,54 @@ This generates:
|
|
|
7534
8586
|
|
|
7535
8587
|
```typescript
|
|
7536
8588
|
export type ShowPageProps = Inertia.SharedData & {
|
|
7537
|
-
post: Post;
|
|
8589
|
+
post: Post & { author: Pick<User, "id" | "name"> };
|
|
7538
8590
|
comments: Comment[];
|
|
7539
8591
|
author: User | null;
|
|
8592
|
+
viewer: string | null;
|
|
7540
8593
|
page: number;
|
|
7541
8594
|
related: LengthAwarePaginator<Post>;
|
|
7542
8595
|
tally?: number;
|
|
7543
8596
|
};
|
|
7544
8597
|
```
|
|
7545
8598
|
|
|
7546
|
-
|
|
8599
|
+
Eloquent finders and collections are typed step by step from the model the chain starts at:
|
|
7547
8600
|
|
|
7548
|
-
|
|
7549
|
-
|
|
7550
|
-
|
|
7551
|
-
|
|
8601
|
+
| Call | Type |
|
|
8602
|
+
| ---------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
|
|
8603
|
+
| `find()`, `first()`, `firstWhere()` | `Model \| null` |
|
|
8604
|
+
| `findOrFail()`, `firstOrFail()`, `sole()`, `create()`, `make()`, `firstOrCreate()`, `firstOrNew()`, `updateOrCreate()` | `Model` |
|
|
8605
|
+
| `all()`, `get()`, `cursor()`, `findMany()`, and `find()` with a list of keys | `Model[]` |
|
|
8606
|
+
| `pluck('title')` | A list of the column's type |
|
|
8607
|
+
| `value('title')` | The column's type, or `null` |
|
|
8608
|
+
| `count()` | `number` |
|
|
8609
|
+
| `exists()` | `boolean` |
|
|
8610
|
+
|
|
8611
|
+
A relation step moves the chain to the related model, so `Post::find(1)->comments()->get()` is `Comment[]`. A read past a finder is typed too, so `Post::find(1)?->title` is `string | null`.
|
|
8612
|
+
|
|
8613
|
+
These expressions are typed too:
|
|
8614
|
+
|
|
8615
|
+
- **Paginators**: `paginate()`, `simplePaginate()` and `cursorPaginate()` are `LengthAwarePaginator<Model>`, `SimplePaginator<Model>` and `CursorPaginator<Model>`, imported from `@tolki/types`. A call that hands back the same paginator, such as `withQueryString()` or `appends()`, keeps that type, and `through()` types the items as its callback returns them.
|
|
8616
|
+
- **Route-bound model parameters**: a `Post $post` parameter is `Post` wherever a prop uses it, and a relation read on it is typed by the models the relation loads, so `$post->author` is `User` and `$post->comments` is `Comment[]`.
|
|
8617
|
+
- **`load()` and `loadMissing()`**: the model with the relations the call loads, such as `Post & { author: User }`, or a list of that on a collection. A column list publishes a `Pick`, as the example shows, and a dotted path nests, so `load('author.posts')` is `Post & { author: User & { posts: Post[] } }`. A to-one relation adds `| null` where a closure may filter it out, or where a column list leaves out the key Laravel matches it by. Only the value the call returns carries the relations, so call `load()` inside the prop: `$post->load('author');` on its own line, followed by `'post' => $post`, publishes `Post`.
|
|
8618
|
+
- **PHP enums**: a prop holding an enum is the enum's `{Name}Type` alias, imported from the generated [enums](https://tolki.abe.dev/ts/enums.html). That includes a bare case, such as `'status' => Status::Active`. A rename with [`#[TsEnum]`](https://tolki.abe.dev/ts/enums.html#tsenum) carries over, so `#[TsEnum(name: 'Size')] enum ShirtSize` gives you `size: SizeType`. Two enums with the same class name in different namespaces are imported under aliases, such as `StatusType as CrmStatusType`. An `EnumResource` prop publishes `AsEnum<typeof Status>`, as it does in [shared data](https://tolki.abe.dev/ts/inertia.html#how-the-augmentation-file-is-generated).
|
|
8619
|
+
- **The signed-in user**: `$request->user()`, `auth()->user()`, `Auth::user()` and `request()->user()`, and reads past them such as `auth()->user()?->name`, typed through your `auth` config the same way [shared data](https://tolki.abe.dev/ts/inertia.html#how-the-augmentation-file-is-generated) is. A named guard, or guards that name more than one user model, can leave some of these `unknown`, as that page describes. `Request` reads such as `integer()`, `boolean()`, `string()` and `url()` are typed too.
|
|
7552
8620
|
- **`compact()` and `array_merge()`**: passed as the whole props argument, as in `Inertia::render('Posts/Show', compact('post', 'comments'))` or `array_merge($base, [...])`, each types the same as the array literal it builds.
|
|
7553
|
-
- **Inertia v2 prop wrappers**: `defer()`, `optional()` and `lazy()` type as the value they wrap and make the key optional, since a partial reload can leave it out. `always()`, `merge()` and `deepMerge()` type as the value they wrap.
|
|
7554
|
-
- **API resources and resource collections**, typed as the response Inertia sends for each, such as `{ data: PostResource }` for a single resource and `JsonResourceSimplePaginator<PostResource>` over `simplePaginate()`, including a `#[PreserveKeys]` collection's keyed `data` member. See [API Resources in Props](https://tolki.abe.dev/ts/inertia.html#api-resources-in-props).
|
|
7555
|
-
- **A props array assigned from a ternary
|
|
7556
|
-
- **
|
|
8621
|
+
- **Inertia v2 prop wrappers**: `defer()`, `optional()` and `lazy()` type as the value they wrap and make the key optional, since a partial reload can leave it out. `always()`, `merge()` and `deepMerge()` type as the value they wrap. A prop class you construct, such as `new OptionalProp(fn () => …)`, types the same as its factory.
|
|
8622
|
+
- **API resources and resource collections**, typed as the response Inertia sends for each, such as `{ data: PostResource }` for a single resource and `JsonResourceSimplePaginator<PostResource>` over `simplePaginate()`, including a `#[PreserveKeys]` collection's keyed `data` member, the keys `with()` and `additional()` add, and the resources nested in a resource you call `->resolve()` on. See [API Resources in Props](https://tolki.abe.dev/ts/inertia.html#api-resources-in-props).
|
|
8623
|
+
- **A props array in a local variable**, typed from what your code writes to it before the render call. The local can be assigned from a ternary, set one key at a time, assigned in each arm of an `if`, or built with `$base + [...]`. A key written after the render call isn't published, because the call has already copied the array, and keys a loop writes under an interpolated name publish an index signature.
|
|
8624
|
+
- **Props a helper builds**: props built whole by a controller helper method or by a method on an injected service, as in `Inertia::render('Posts/Show', $this->service->build())`, are typed the same way, closures and API resources included.
|
|
8625
|
+
- **Closures and first-class callables**: Inertia calls a callable prop, so `fn () => $this->label()` and `$this->label(...)` are both typed from what the call returns.
|
|
8626
|
+
|
|
8627
|
+
A prop the package can't read is typed `unknown`, and the run carries on. Use [`#[TsCasts]`](#overriding-props-with-tscasts) to set its type. A few shapes the package doesn't follow:
|
|
7557
8628
|
|
|
7558
|
-
|
|
8629
|
+
- A props local that a `+=` writes, or one written inside a `switch`, a `try`, or a loop that exits through `continue` or `break`, publishes none of its keys, so the page's type is only `Inertia.SharedData`. Build the props as an array literal instead.
|
|
8630
|
+
- A first-class callable that a constructor stores in a property, as in `$this->stamp = now(...)`, publishes `Record<string, never>`, and `ts:publish` warns, though Inertia calls it and sends what it returns. Set that prop's type with `#[TsCasts]`.
|
|
7559
8631
|
|
|
7560
|
-
|
|
8632
|
+
Inertia unpacks a top-level dotted key into nested objects, so `'filters.page' => $request->integer('page')` publishes `filters: { page: number }`. When the props also hold a `filters` array, `page` is added to it.
|
|
7561
8633
|
|
|
7562
|
-
|
|
8634
|
+
A page key with the same name as a shared-data key publishes both types intersected, though Inertia sends only the page's value. Give page keys names that shared data doesn't use.
|
|
8635
|
+
|
|
8636
|
+
Inertia merges shared data and page props with `array_merge()`, which renumbers integer keys from `0`. A top-level `42 => …` key therefore publishes as `"0"`, and `ts:publish` warns that you probably meant a string key. A render call that can send one of several arrays, such as the arms of a ternary, numbers each array on its own. Nested keys keep theirs.
|
|
7563
8637
|
|
|
7564
8638
|
Sometimes the package can't analyze an action at all, for example because a class the action depends on fails to load. That route then publishes as a plain helper with no page-props type, and `ts:publish` names the action in a warning after the run. The rest of the run still finishes.
|
|
7565
8639
|
|
|
@@ -7597,11 +8671,14 @@ export type IndexPageProps = Inertia.SharedData & {
|
|
|
7597
8671
|
};
|
|
7598
8672
|
```
|
|
7599
8673
|
|
|
8674
|
+
An entry with no `import` key that names a class the prop's value holds, such as `'post' => 'Post | null'` over a route-bound `Post`, imports that class for you.
|
|
8675
|
+
|
|
7600
8676
|
### Inertia UI Table Props
|
|
7601
8677
|
|
|
7602
8678
|
A route that renders an [Inertia UI Table](https://inertiaui.com/) gets a typed page prop. The package reads the table's model from the table class itself, and never creates the table or calls its `toArray()`:
|
|
7603
8679
|
|
|
7604
8680
|
```php
|
|
8681
|
+
use App\Models\Post;
|
|
7605
8682
|
use App\Tables\PostTable;
|
|
7606
8683
|
use Inertia\Inertia;
|
|
7607
8684
|
|
|
@@ -7609,6 +8686,7 @@ public function index()
|
|
|
7609
8686
|
{
|
|
7610
8687
|
return Inertia::render('Posts/Index', [
|
|
7611
8688
|
'posts' => PostTable::make()->defaultSort('-id'),
|
|
8689
|
+
'total' => Post::query()->count(),
|
|
7612
8690
|
]);
|
|
7613
8691
|
}
|
|
7614
8692
|
```
|
|
@@ -7621,16 +8699,18 @@ import type { Post } from "../models";
|
|
|
7621
8699
|
|
|
7622
8700
|
export type IndexPageProps = Inertia.SharedData & {
|
|
7623
8701
|
posts: TableResource<Post>;
|
|
8702
|
+
total: number;
|
|
7624
8703
|
};
|
|
7625
8704
|
```
|
|
7626
8705
|
|
|
8706
|
+
A table is one prop like any other: the render call's other props keep their types, and the action's [`#[TsCasts]`](#overriding-props-with-tscasts) applies. `new PostTable`, a table held in a local variable, one in props a service method builds, and one in [shared data](https://tolki.abe.dev/ts/inertia.html) are typed the same way.
|
|
8707
|
+
|
|
7627
8708
|
`TableResource` is imported from whichever Inertia UI Table package your `package.json` lists, `@inertiaui/table-vue` or `@inertiaui/table-react`. If neither is listed, the import uses `@inertiaui/table-vue`. To force a package, or to use an alias, set `inertia.ui_table_package` in `config/ts-publish.php`.
|
|
7628
8709
|
|
|
7629
|
-
The package finds a table's model in
|
|
8710
|
+
The package finds a table's model in either of these places:
|
|
7630
8711
|
|
|
7631
8712
|
- A `$resource` property default, as in `protected ?string $resource = Post::class;`.
|
|
7632
8713
|
- A `query(): Builder` method that returns `Post::query()`, `Post::class`, or a query chain that starts at the model.
|
|
7633
|
-
- A service method: when the controller passes `$this->tables->index($request)`, the array that method returns can hold table props.
|
|
7634
8714
|
|
|
7635
8715
|
A table whose model exists only at runtime, for example one set in its constructor, gets no table type. Use [`#[TsCasts]`](#overriding-props-with-tscasts) on the controller method to type its props.
|
|
7636
8716
|
|
|
@@ -7971,6 +9051,7 @@ Each stage has a config key named `{feature}.{stage}_class`, such as `models.col
|
|
|
7971
9051
|
| `form_requests` | `FormRequestsCollector` | `FormRequestGenerator` | `FormRequestTransformer` | `FormRequestWriter` |
|
|
7972
9052
|
| `broadcast_channels` | `BroadcastChannelsCollector` | none | none | `BroadcastChannelsWriter` |
|
|
7973
9053
|
| `broadcast_events` | `BroadcastEventsCollector` | `BroadcastEventGenerator` | `BroadcastEventTransformer` | `BroadcastEventWriter` |
|
|
9054
|
+
| `class_types` | `ClassTypesCollector` | `ClassTypeGenerator` | `ClassTypeTransformer` | `ClassTypeWriter` |
|
|
7974
9055
|
|
|
7975
9056
|
The classes live in the `AbeTwoThree\LaravelTsPublish\Collectors`, `Generators`, `Transformers`, and `Writers` namespaces.
|
|
7976
9057
|
|
|
@@ -8181,6 +9262,7 @@ To use a template with a different name, point the feature's template key at it.
|
|
|
8181
9262
|
| `broadcast_events.template` | `laravel-ts-publish::broadcast-event` |
|
|
8182
9263
|
| `broadcast_events.index_template` | `laravel-ts-publish::broadcast-events-index` |
|
|
8183
9264
|
| `broadcast_events.echo_augmentation.template` | `laravel-ts-publish::echo-broadcast-events` |
|
|
9265
|
+
| `class_types.template` | `laravel-ts-publish::class-type` |
|
|
8184
9266
|
| `globals.template` | `laravel-ts-publish::globals` |
|
|
8185
9267
|
|
|
8186
9268
|
Inertia's `inertia-config.blade.php` and Vite env's `vite-env.blade.php` have no template key. Edit your published copies to change them.
|
|
@@ -8195,9 +9277,9 @@ To change what `ts:publish` itself does, replace one of its stages instead. See
|
|
|
8195
9277
|
|
|
8196
9278
|
### Analyzing a Method
|
|
8197
9279
|
|
|
8198
|
-
`analyze()` reads what a method returns: nested arrays, conditionals, closures, and method calls. It works on any class, whether or not it's a resource. A property read or a method call is typed from the class of the value you call it on, such as `$this->author->name` or a local variable.
|
|
9280
|
+
`analyze()` reads what a method returns: nested arrays, conditionals, closures, and method calls. It works on any class, whether or not it's a resource. A property read or a method call is typed from the class of the value you call it on, such as `$this->author->name` or a local variable. A plain value object gets the same types a resource does for enum `->value` and `->name` reads, `(object)` and `(array)` casts, helpers that return the array you pass them, and an inherited or trait method.
|
|
8199
9281
|
|
|
8200
|
-
Laravel's conditional methods, such as `$this->when()` and `$this->whenLoaded()`, belong to `JsonResource`, so `analyze()` reads them that way only on a resource. On any other class, `$this->when()` is that class's own method. Laravel's `Conditionable::when()`, which events and other classes can use,
|
|
9282
|
+
Laravel's conditional methods, such as `$this->when()` and `$this->whenLoaded()`, belong to `JsonResource`, so `analyze()` reads them that way only on a resource. On any other class, `$this->when()` is that class's own method. Laravel's `Conditionable::when()` and `unless()`, which events and other classes can use, return the callback's result, the default's, or the object itself, so the key is always sent. `analyze()` types the key that way, required, as a publish does, and a resource built around the call, such as `UserResource::make($this->when(…))`, comes back required too. See [`when()` and `unless()` From `Conditionable`](https://tolki.abe.dev/ts/broadcast-events.html#when-and-unless-from-conditionable).
|
|
8201
9283
|
|
|
8202
9284
|
This example analyzes a service class's `toPayload()` method:
|
|
8203
9285
|
|
|
@@ -8322,9 +9404,9 @@ The difference can also run the other way. Where a key the method returns can't
|
|
|
8322
9404
|
|
|
8323
9405
|
Outside those cases, `analyze()` runs the same inference that resources, broadcast events, model metadata, Inertia page props, and Inertia shared data publish from. What each of those features adds on top is on its own page, linked above.
|
|
8324
9406
|
|
|
8325
|
-
`analyze()` and `ts:publish` both type the patterns these docs describe
|
|
9407
|
+
`analyze()` and `ts:publish` both type the patterns these docs describe, including [a local you write more than once](https://tolki.abe.dev/ts/api-resources.html#local-variables-and-narrowing). Anything else, such as an expression neither can follow or a local that a reference can write, comes back `unknown` rather than a guess.
|
|
8326
9408
|
|
|
8327
|
-
Two cases don't widen to `unknown`. [A conditional's default that can't be typed](https://tolki.abe.dev/ts/api-resources.html#passing-a-default-argument) leaves the value's own type in place. [A
|
|
9409
|
+
Two cases don't widen to `unknown`. [A conditional's default that can't be typed](https://tolki.abe.dev/ts/api-resources.html#passing-a-default-argument) leaves the value's own type in place. [A union member that can't be typed is left out](https://tolki.abe.dev/ts/api-resources.html#values-left-out-of-a-union), whether it's a ternary or `?:` arm or a value that a parameter's writes join. So `$cond ? $untypable : null` publishes `null`.
|
|
8328
9410
|
|
|
8329
9411
|
### Configuration Reference
|
|
8330
9412
|
|
|
@@ -8548,6 +9630,22 @@ See [Collected Files Manifest](https://tolki.abe.dev/ts/publishing.html#collecte
|
|
|
8548
9630
|
| `broadcast_events.echo_augmentation.output_directory` | `string` | `''` | Custom output directory for the Echo augmentation file. Empty uses `broadcast_events.output_directory`, then `output_directory` |
|
|
8549
9631
|
| `broadcast_events.echo_augmentation.writer_class` | `string` | `BroadcastEventsEchoWriter` | Writes the Echo augmentation file |
|
|
8550
9632
|
|
|
9633
|
+
### Class Types (`class_types.*`)
|
|
9634
|
+
|
|
9635
|
+
See [Custom Types](https://tolki.abe.dev/ts/custom-types.html#configuration) for which classes compose and when the package writes their modules. A config file published before class types existed has no `class_types` block, and every key then takes its default.
|
|
9636
|
+
|
|
9637
|
+
| Config Key | Type | Default | Description |
|
|
9638
|
+
| ------------------------------------ | -------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
9639
|
+
| `class_types.enabled` | `bool` | `true` | Compose the `#[TsType]` types a class inherits into one `{Basename}Type` interface. When `false`, each value publishes its class's nearest type |
|
|
9640
|
+
| `class_types.template` | `string` | `laravel-ts-publish::class-type` | Blade template for each composed type's module |
|
|
9641
|
+
| `class_types.additional_directories` | `array` | `[]` | Directories to scan for composed classes, whose modules are written even when no value uses them. No directory is scanned by default |
|
|
9642
|
+
| `class_types.included` | `array` | `[]` | Only these classes compose (empty = all) |
|
|
9643
|
+
| `class_types.excluded` | `array` | `[]` | These classes never compose |
|
|
9644
|
+
| `class_types.collector_class` | `string` | `ClassTypesCollector` | Discovers composed classes in `additional_directories` |
|
|
9645
|
+
| `class_types.generator_class` | `string` | `ClassTypeGenerator` | Orchestrates transforming and writing |
|
|
9646
|
+
| `class_types.transformer_class` | `string` | `ClassTypeTransformer` | Converts a composed class into TypeScript data |
|
|
9647
|
+
| `class_types.writer_class` | `string` | `ClassTypeWriter` | Writes each composed type's module |
|
|
9648
|
+
|
|
8551
9649
|
### Inertia (`inertia.*`)
|
|
8552
9650
|
|
|
8553
9651
|
| Config Key | Type | Default | Description |
|