<?php
/**
 * Copyright 2022 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it.
 */
declare(strict_types=1);

namespace Magento\Mray\Parse\Xml;

class XMLStringToAssocArray
{
    /**
     * @param string $content
     * @return array
     */
    public function execute(string $content): array
    {
        $contentWithoutNamespaces = str_replace('xsi:', '', $content);
        $simpleXml = simplexml_load_string($contentWithoutNamespaces);
        $array = json_decode(json_encode($simpleXml), true);

        if (!isset($array['table'])) {
            return [];
        }

        return $this->formatArray($array['table']);
    }

    /**
     * @param array $array
     * @return array
     */
    private function formatArray(array $array): array
    {
        if (isset($array['@attributes'])) {
            $array = [$array];
        }

        $result = [];

        foreach ($array as $key => $item) {
            $name = $item['@attributes']['name'] ?? $item['@attributes']['referenceId'] ?? $key;
            $result[$name] = $this->formatItem($item);
        }

        return $result;
    }

    /**
     * @param array $item
     * @return array
     */
    private function formatItem(array $item): array
    {
        $result = $item['@attributes'] ?? [];

        foreach ($item as $key => $value) {
            if ($key === '@attributes') {
                continue;
            }
            $result[$key] = $this->formatArray($value);
        }

        return $result;
    }
}
