<?php

declare(strict_types=1);

namespace FiloBlu\Esb\Core\Expression;

use Magento\Framework\DataObject;

use function is_string;

/**
 * Class VariableExpander
 * @package FiloBlu\Esb\Core\Expression
 */
class VariableExpander implements VariableExpanderInterface
{

    /**
     * @param array|mixed|string|null $value
     * @param DataObject $data
     * @return array|mixed|string|null
     */
    public function expand($value, DataObject $data)
    {
        if (!is_string($value)) {
            return $value;
        }

        $matches = [];
        $occurrences = preg_match_all('/{(.*?)}/', $value, $matches);

        if ($occurrences === false || $occurrences === 0) {
            return $value;
        }

        if ($occurrences === 1 && $value === $matches[0][0]) {
            return $data->getDataByPath($matches[1][0]);
        }

        foreach ($matches[1] as $match) {
            $valueToReplace = $data->getDataByPath($match);

            // Scalar variables are those containing an int, float, string or bool.
            // Types array, object, resource and null are not scalar.
            if (!is_scalar($valueToReplace)) {
                $valueToReplace = '';
            }

            $value = str_replace(sprintf('{%s}', $match), $valueToReplace, $value);
        }

        return $value;
    }
}
