<?php

namespace Dedi\SyliusTheme\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class ArrayManipulationExtension extends AbstractExtension
{
    public function getFilters()
    {
        return [
            new TwigFilter('unset_nested_key', [$this, 'unsetNestedKey']),
            new TwigFilter('unset_nested_value', [$this, 'unsetNestedValue']),
        ];
    }

    public function unsetNestedKey(array $array, array $keys): array
    {
        $this->deleteArrayKey($array, $keys);

        return $array;
    }

    private function deleteArrayKey(array &$array, array $keys): void
    {
        if (count($keys) === 1) {
            unset($array[$keys[0]]);
        } else {
            $key = array_shift($keys);
            $this->deleteArrayKey($array[$key], $keys);
        }
    }

    public function unsetNestedValue(array $array, array $keys, $value): array
    {
        $this->deleteArrayValue($array, $keys, $value);

        return $array;
    }

    private function deleteArrayValue(array &$array, array $keys, $value): void
    {
        if (count($keys) !== 0) {
            $key = array_shift($keys);
            $this->deleteArrayValue($array[$key], $keys, $value);

            return;
        }

        if (($key = array_search($value, $array, true)) !== false) {
            unset($array[$key]);
        }
    }
}
