|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Tonysm\RichTextLaravel; |
| 4 | + |
| 5 | +use Illuminate\Support\Facades\Crypt; |
| 6 | + |
| 7 | +class RichTextLaravel |
| 8 | +{ |
| 9 | + /** |
| 10 | + * The handler responsible for encrypting the rich text attributes. |
| 11 | + * |
| 12 | + * @var callable |
| 13 | + */ |
| 14 | + protected static $encryptHandler; |
| 15 | + |
| 16 | + /** |
| 17 | + * The handle responsible for decrypting the rich text attributes. |
| 18 | + * |
| 19 | + * @var callable |
| 20 | + */ |
| 21 | + protected static $decryptHandler; |
| 22 | + |
| 23 | + /** |
| 24 | + * Override the way the package handles encryption. |
| 25 | + */ |
| 26 | + public static function encryptUsing($encryption, $decryption): void |
| 27 | + { |
| 28 | + static::$encryptHandler = $encryption; |
| 29 | + static::$decryptHandler = $decryption; |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Configures the Rich Text Laravel package to store encrypted data as string, |
| 34 | + * instead of using Laravel's default encryption mode, which serializes the |
| 35 | + * content before encrypting it. |
| 36 | + */ |
| 37 | + public static function encryptAsString(): void |
| 38 | + { |
| 39 | + static::$encryptHandler = fn ($value) => Crypt::encryptString($value); |
| 40 | + static::$decryptHandler = fn ($value) => ($value ? Crypt::decryptString($value) : $value); |
| 41 | + } |
| 42 | + |
| 43 | + public static function clearEncryptionHandlers(): void |
| 44 | + { |
| 45 | + static::encryptUsing(null, null); |
| 46 | + } |
| 47 | + |
| 48 | + public static function encrypt($value, $model, $key): string |
| 49 | + { |
| 50 | + $encrypt = static::$encryptHandler ??= fn ($value) => Crypt::encrypt($value); |
| 51 | + |
| 52 | + return call_user_func($encrypt, $value, $model, $key); |
| 53 | + } |
| 54 | + |
| 55 | + public static function decrypt($value, $model, $key): ?string |
| 56 | + { |
| 57 | + $decrypt = static::$decryptHandler ??= fn ($value) => Crypt::decrypt($value); |
| 58 | + |
| 59 | + return $value ? call_user_func($decrypt, $value, $model, $key) : $value; |
| 60 | + } |
| 61 | +} |
0 commit comments