<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Facades\Crypt;

class OptionalEncrypted implements CastsAttributes
{
    /**
     * @return mixed
     */
    public function get($model, string $key, $value, array $attributes)
    {
        if (! config('encryption.enabled') || is_null($value)) {
            return $value;
        }

        try {
            return Crypt::decryptString($value);
        } catch (\Exception) {
            return null;
        }
    }

    /**
     * @return mixed
     */
    public function set($model, string $key, $value, array $attributes)
    {
        if (! config('encryption.enabled') || is_null($value)) {
            return $value;
        }

        return Crypt::encryptString($value);
    }
}
