|
| 1 | +--- |
| 2 | +sidebarDepth: 1 |
| 3 | +--- |
| 4 | + |
| 5 | +# #[Cast] |
| 6 | + |
| 7 | +**Stage:** `TRANSFORM` (2) |
| 8 | + |
| 9 | +Casts the payload value to a specific type using the Payload's `as*` methods. |
| 10 | + |
| 11 | +--- |
| 12 | + |
| 13 | +## Parameters |
| 14 | + |
| 15 | +| Parameter | Type | Required | Description | |
| 16 | +| --------- | -------- | -------- | ---------------------------------------------------- | |
| 17 | +| `$type` | `string` | ✅ | The target type name (maps to `Payload::as{Type}()`) | |
| 18 | + |
| 19 | +--- |
| 20 | + |
| 21 | +## Supported Types |
| 22 | + |
| 23 | +| Type | Maps To | Description | |
| 24 | +| --------- | ----------------------- | ------------------------------------ | |
| 25 | +| `int` | `$payload->asInt()` | Cast to integer | |
| 26 | +| `boolean` | `$payload->asBoolean()` | Cast to boolean | |
| 27 | +| `array` | `$payload->asArray()` | Decode JSON or return existing array | |
| 28 | +| `carbon` | `$payload->asCarbon()` | Parse to Carbon date instance | |
| 29 | +| `slug` | `$payload->asSlug()` | Convert to URL-friendly slug | |
| 30 | +| `like` | `$payload->asLike()` | Wrap with `%` for LIKE queries | |
| 31 | + |
| 32 | +--- |
| 33 | + |
| 34 | +## Usage |
| 35 | + |
| 36 | +### Cast to Integer |
| 37 | + |
| 38 | +```php |
| 39 | +use Kettasoft\Filterable\Engines\Foundation\Attributes\Annotations\Cast; |
| 40 | + |
| 41 | +#[Cast('int')] |
| 42 | +protected function views(Payload $payload) |
| 43 | +{ |
| 44 | + // "42" → 42 |
| 45 | + return $this->builder->where('views', '>=', $payload->value); |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +### Cast to Boolean |
| 50 | + |
| 51 | +```php |
| 52 | +#[Cast('boolean')] |
| 53 | +protected function isFeatured(Payload $payload) |
| 54 | +{ |
| 55 | + // "true" → true, "false" → false |
| 56 | + return $this->builder->where('is_featured', $payload->value); |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | +### Cast to Array (from JSON) |
| 61 | + |
| 62 | +```php |
| 63 | +#[Cast('array')] |
| 64 | +protected function tags(Payload $payload) |
| 65 | +{ |
| 66 | + // '["php","laravel"]' → ['php', 'laravel'] |
| 67 | + $tags = $payload->value; |
| 68 | + return $this->builder->whereIn('tag', $tags); |
| 69 | +} |
| 70 | +``` |
| 71 | + |
| 72 | +--- |
| 73 | + |
| 74 | +## Behavior |
| 75 | + |
| 76 | +| Scenario | Result | |
| 77 | +| -------------------------- | ------------------------------- | |
| 78 | +| Cast type is supported | Value is cast and returned | |
| 79 | +| Cast type is not supported | `StrictnessException` is thrown | |
| 80 | +| Cast fails (invalid value) | `StrictnessException` is thrown | |
0 commit comments