<?php declare(strict_types=1);

namespace Newland\Toubiz\Search\Neos\Utility;

use Neos\Utility\Arrays;

class ArrayUtility
{
    public static function arrayRecursiveDiff(array $inputA, array $inputB): array
    {
        // array_filter removes empty values (e.g. empty strings, null, empty arrays, ...)
        $flatA = array_filter(static::dot($inputA));
        $flatB = array_filter(static::dot($inputB));
        $flatDiff = array_merge(array_diff($flatA, $flatB), array_diff($flatB, $flatA));

        $deepDiff = [];
        foreach ($flatDiff as $path => $value) {
            $deepDiff = Arrays::setValueByPath($deepDiff, (string) $path, $value);
        }

        return (array) $deepDiff;
    }

    /**
     * Flatten a multi-dimensional associative array with dots.
     *
     * @see https://github.com/illuminate/support/blob/master/Arr.php#L109
     */
    public static function dot(array $array, string $prepend = ''): array
    {
        $results = [];

        foreach ($array as $key => $value) {
            if (is_array($value) && !empty($value)) {
                $results = array_merge($results, static::dot($value, $prepend . $key . '.'));
            } else {
                $results[$prepend . $key] = $value;
            }
        }

        return $results;
    }

    public static function emptyExplode(string $delimiter, string $input): array
    {
        $values = explode($delimiter, $input) ?: [];
        array_walk(
            $values,
            static function (string &$value) {
                $value = trim($value);
            }
        );
        return array_values(
            array_filter(
                $values,
                static function ($value) {
                    return !empty(trim($value));
                }
            )
        );
    }
}
