<?php

namespace GriffinForms\Traits;

trait MaybeDecode
{
    /**
     * Safely decode a database field that may be JSON-encoded or PHP-serialized.
     *
     * @param mixed $value The value to decode.
     * @return mixed Decoded array if possible, otherwise the original value.
     */
    protected function maybeDecode($value)
    {
        if (is_string($value)) {
            $decoded = json_decode($value, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                return $decoded;
            }
            $unserialized = maybe_unserialize($value);
            if (is_array($unserialized)) {
                return $unserialized;
            }
        }
        return $value;
    }
}