Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
4 / 4 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| OnlyNumbers | |
100.00% |
4 / 4 |
|
100.00% |
2 / 2 |
5 | |
100.00% |
1 / 1 |
| get | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| set | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
4 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace DevToolbelt\LaravelEloquentPlus\Casts; |
| 6 | |
| 7 | use Illuminate\Contracts\Database\Eloquent\CastsAttributes; |
| 8 | use Illuminate\Database\Eloquent\Model; |
| 9 | |
| 10 | /** |
| 11 | * Cast that removes all non-numeric characters from a string. |
| 12 | * |
| 13 | * Useful for fields like phone numbers, CPF, CNPJ, ZIP codes, etc. |
| 14 | * where you want to store only the numeric digits. |
| 15 | * |
| 16 | * Usage in model: |
| 17 | * ```php |
| 18 | * protected $casts = [ |
| 19 | * 'phone' => OnlyNumbers::class, |
| 20 | * 'cpf' => OnlyNumbers::class, |
| 21 | * 'zip_code' => OnlyNumbers::class, |
| 22 | * ]; |
| 23 | * ``` |
| 24 | * |
| 25 | * Example: |
| 26 | * - Input: "(11) 99999-9999" → Output: "11999999999" |
| 27 | * - Input: "123.456.789-00" → Output: "12345678900" |
| 28 | * |
| 29 | * @package DevToolbelt\LaravelEloquentPlus\Casts |
| 30 | */ |
| 31 | final readonly class OnlyNumbers implements CastsAttributes |
| 32 | { |
| 33 | /** |
| 34 | * Transform the attribute from the underlying model values. |
| 35 | * |
| 36 | * Returns the value as stored in the database. |
| 37 | * |
| 38 | * @param Model $model |
| 39 | * @param string $key |
| 40 | * @param mixed $value |
| 41 | * @param array<string, mixed> $attributes |
| 42 | * @return string|null |
| 43 | */ |
| 44 | public function get(Model $model, string $key, mixed $value, array $attributes): ?string |
| 45 | { |
| 46 | return $value; |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Transform the attribute to its underlying model values. |
| 51 | * |
| 52 | * Removes all non-numeric characters from the value. |
| 53 | * |
| 54 | * @param Model $model |
| 55 | * @param string $key |
| 56 | * @param mixed $value |
| 57 | * @param array<string, mixed> $attributes |
| 58 | * @return string|null |
| 59 | */ |
| 60 | public function set(Model $model, string $key, mixed $value, array $attributes): ?string |
| 61 | { |
| 62 | if ($value === null || $value === '') { |
| 63 | return $value === '' ? null : $value; |
| 64 | } |
| 65 | |
| 66 | return preg_replace('/\D/', '', (string) $value); |
| 67 | } |
| 68 | } |