<?php
/**
 * Copyright © 2019 Filoblu S.r.l. All rights reserved.
 */

namespace FiloBlu\Rma\Api\Model\Config;

use DOMDocument;
use DOMElement;
use DOMNode;
use DOMNodeList;
use InvalidArgumentException;
use Magento\Framework\Config\ConverterInterface;

/**
 *
 */
class Converter implements ConverterInterface
{
    /**
     * Converting data to array type
     *
     * @param mixed $source
     * @return array
     * @throws InvalidArgumentException
     */
    public function convert($source)
    {
        $output = [];
        if (!$source instanceof DOMDocument) {
            return $output;
        }

        /** @var DOMNodeList $sections*/
        $items = $source->getElementsByTagName('rma_reason');

        /** @var DOMElement $section */
        foreach ($items as $item) {

            $children = [];

            foreach ($item->childNodes as $child) {

                if ($child->nodeType != XML_ELEMENT_NODE) {
                    continue;
                }

                $children [$child->tagName] = $child->nodeValue;
            }

            $output[] = $children;
        }

        return $output;
    }


    /**
     * TODO: ?? this method is not used. Remove??
     * Get attribute value
     *
     * @param DOMNode $node
     * @param string $attributeName
     * @param string|null $defaultValue
     * @return null|string
     */
    protected function _getAttributeValue(DOMNode $node, $attributeName, $defaultValue = null)
    {
        $attributeNode = $node->attributes->getNamedItem($attributeName);
        $output = $defaultValue;
        if ($attributeNode) {
            $output = $attributeNode->nodeValue;
        }
        return $output;
    }

}

