<?php

declare(strict_types=1);

namespace CliqThemes\StoreLocator\Support;

defined('ABSPATH') || exit;

/**
 * Decoding for values read back out of the plugin's own tables.
 */
final class StoredValue
{
    /**
     * `maybe_unserialize()` without allowing objects.
     *
     * Custom-field values are scalars and arrays of scalars, so a serialized
     * object in one of these columns is malformed input rather than data.
     * Refusing to instantiate it closes the __wakeup/__destruct route out of
     * unserialize() on a path that answers unauthenticated requests.
     *
     * @param mixed $value
     *
     * @return mixed the decoded value, or the original string when it is not
     *               serialized or does not decode
     */
    public static function decode($value)
    {
        if (! is_string($value) || ! is_serialized($value)) {
            return $value;
        }

        $decoded = @unserialize($value, ['allowed_classes' => false]);

        // `false` is what a malformed payload returns, and also what `b:0;`
        // legitimately decodes to — hence the second test.
        return $decoded === false && $value !== 'b:0;' ? $value : $decoded;
    }
}
