<?php

declare(strict_types=1);

namespace SiteFort\Includes;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Parses legacy serialized data without instantiating classes.
 */
final class SafeUnserializer {
	/**
	 * Behaves like maybe_unserialize(), but serialized objects are not hydrated.
	 *
	 * @param mixed $value Raw value from the database or request context.
	 * @return mixed
	 */
	public static function maybe_unserialize_without_objects( $value ) {
		if ( ! is_string( $value ) ) {
			return $value;
		}

		$trimmed = trim( $value );
		if ( ! function_exists( 'is_serialized' ) || ! is_serialized( $trimmed ) ) {
			return $value;
		}

		$parsed = @unserialize( $trimmed, [ 'allowed_classes' => false ] );
		if ( false === $parsed && $trimmed !== 'b:0;' ) {
			return $value;
		}

		return $parsed;
	}
}
