Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
RemoveSpecialCharacters
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
2 / 2
5
100.00% covered (success)
100.00%
1 / 1
 get
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 set
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3declare(strict_types=1);
4
5namespace DevToolbelt\LaravelEloquentPlus\Casts;
6
7use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
8use Illuminate\Database\Eloquent\Model;
9
10/**
11 * Cast that removes special characters from a string.
12 *
13 * Keeps only alphanumeric characters (a-z, A-Z, 0-9) and whitespace.
14 * Useful for sanitizing user input for fields that should not contain
15 * special characters like punctuation or symbols.
16 *
17 * Usage in model:
18 * ```php
19 * protected $casts = [
20 *     'username' => RemoveSpecialCharacters::class,
21 *     'slug' => RemoveSpecialCharacters::class,
22 * ];
23 * ```
24 *
25 * Example:
26 * - Input: "Hello, World!" → Output: "Hello World"
27 * - Input: "user@name#123" → Output: "username123"
28 * - Input: "Test (value)" → Output: "Test value"
29 *
30 * @package DevToolbelt\LaravelEloquentPlus\Casts
31 */
32final readonly class RemoveSpecialCharacters implements CastsAttributes
33{
34    /**
35     * Transform the attribute from the underlying model values.
36     *
37     * Returns the value as stored in the database.
38     *
39     * @param Model $model
40     * @param string $key
41     * @param mixed $value
42     * @param array<string, mixed> $attributes
43     * @return string|null
44     */
45    public function get(Model $model, string $key, mixed $value, array $attributes): ?string
46    {
47        return $value;
48    }
49
50    /**
51     * Transform the attribute to its underlying model values.
52     *
53     * Removes all special characters, keeping only alphanumeric and whitespace.
54     *
55     * @param Model $model
56     * @param string $key
57     * @param mixed $value
58     * @param array<string, mixed> $attributes
59     * @return string|null
60     */
61    public function set(Model $model, string $key, mixed $value, array $attributes): ?string
62    {
63        if ($value === null || $value === '') {
64            return $value === '' ? null : $value;
65        }
66
67        return preg_replace('/[^a-zA-Z0-9\s]/', '', (string) $value);
68    }
69}