<?php
namespace App\Casts;
use App\Support\Security\EnvelopeEncryption; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Database\Eloquent\Model; use InvalidArgumentException;
final class EncryptedEnvelope implements CastsAttributes { public function get(Model $model,string $key,mixed $value,array $attributes): ?string { if($value===null||$value==='') return null; $payload=json_decode((string)$value,true,512,JSON_THROW_ON_ERROR); return app(EnvelopeEncryption::class)->decrypt($payload,['model'=>$model::class,'attribute'=>$key,'id'=>(string)($model->getKey()??'new')]); } public function set(Model $model,string $key,mixed $value,array $attributes): ?string { if($value===null||$value==='') return null; if(!is_string($value)) throw new InvalidArgumentException('Encrypted values must be strings.'); return json_encode(app(EnvelopeEncryption::class)->encrypt($value,['model'=>$model::class,'attribute'=>$key,'id'=>(string)($model->getKey()??'new')]),JSON_THROW_ON_ERROR); } }
