38 lines
1.1 KiB
PHP
38 lines
1.1 KiB
PHP
<?php
|
|
|
|
namespace App\Casts;
|
|
|
|
use App\Services\Encryption\TenantEnvelopeEncryption;
|
|
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use RuntimeException;
|
|
|
|
class TenantEncrypted implements CastsAttributes
|
|
{
|
|
public function get(Model $model, string $key, mixed $value, array $attributes): ?string
|
|
{
|
|
if ($value === null) {
|
|
return null;
|
|
}
|
|
$tenantId = (int) ($attributes['tenant_id'] ?? 0);
|
|
if ($tenantId < 1) {
|
|
throw new RuntimeException('TENANT_CONTEXT_REQUIRED_FOR_DECRYPTION');
|
|
}
|
|
|
|
return app(TenantEnvelopeEncryption::class)->decrypt($tenantId, $value);
|
|
}
|
|
|
|
public function set(Model $model, string $key, mixed $value, array $attributes): ?string
|
|
{
|
|
if ($value === null) {
|
|
return null;
|
|
}
|
|
$tenantId = (int) ($attributes['tenant_id'] ?? $model->getAttribute('tenant_id'));
|
|
if ($tenantId < 1) {
|
|
throw new RuntimeException('TENANT_CONTEXT_REQUIRED_FOR_ENCRYPTION');
|
|
}
|
|
|
|
return app(TenantEnvelopeEncryption::class)->encrypt($tenantId, $value);
|
|
}
|
|
}
|