<?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;
use Magento\Mray\Parse\Xml\DbSchemaUsageCases\DbSchemaTable;

class GetDbSchemaUsageCases
{

    /**
     * @var XMLStringToAssocArray
     */
    private $xmlToArray;

    /**
     * @param string $content
     * @param string $path
     * @param string $version
     * @return UsageCase[]
     */
    public function execute(string $content, string $path, string $version): array
    {
        $xml = simplexml_load_string($content);
        $usageCases = [];
        foreach ($this->getTablesArray($content) as $tableName => $tableData) {
            $tableUsageCases = (new DbSchemaTable(
                $tableName,
                $tableData,
                $xml,
                $path,
                $version
            ))->getUsageCases();
            foreach ($tableUsageCases as $what => $tableUsageCase) {
                $usageCases[$what] = $tableUsageCase;
            }
        }
        return $usageCases;
    }

    /**
     * @param string $content
     * @return array
     */
    private function getTablesArray(string $content): array
    {
        if (!$this->xmlToArray) {
            $this->xmlToArray = new XMLStringToAssocArray();
        }
        return $this->xmlToArray->execute($content);
    }
}
