<?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;

use Magento\Mray\CodeStructuralElement\Php\Usage\UsageCase;

class GetDiXmlDeclarations
{
    private const USAGE_TYPES = [
        'plugin-type' => '//plugin/@type',
        'preference-type' => '//preference/@type',
        'preference-for' => '//preference/@for',
        'type-name' => '//type/@name',
        'virtual-type-base' => '//virtualType/@type',
        'virtual-type-name' => '//virtualType/@name',
    ];

    /**
     * @param string $content
     * @return UsageCase[]
     */
    public function execute(string $content): array
    {
        $simpleXml = simplexml_load_string($content);

        $usageCases = [];
        foreach (self::USAGE_TYPES as $type => $xpath) {
            foreach ($simpleXml->xpath($xpath) as $result) {
                $lineNumber = $this->getLineNumber($result);
                $usageCases[] = new UsageCase(
                    (string) $result,
                    $type,
                    [
                        'position' => [
                            'startLine' => $lineNumber,
                            'endLine' => $lineNumber
                        ]
                    ]
                );
            }
        }

        return $usageCases;
    }

    /**
     * @param \SimpleXMLElement $result
     * @return int
     */
    private function getLineNumber(\SimpleXMLElement $result): int
    {
        $domElement = dom_import_simplexml($result);

        return $domElement ? $domElement->getLineNo() : 1;
    }
}
