<?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\Model\Xml;

use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RegexIterator;
use RecursiveRegexIterator;

class GetXmlFileContent
{
    /**
     * @var
     */
    public const ETC_PATH = '/etc/';

    /**
     * @param string $modulePath
     * @param string $pattern
     * @param bool $recursive
     * @return array
     */
    public function execute(string $modulePath, string $pattern, bool $recursive = false): array
    {
        if (!is_dir($modulePath . GetXmlFileContent::ETC_PATH)) {
            return [];
        }
        
        if (!$recursive) {
            $dbSchemaFilePath = $modulePath  . GetXmlFileContent::ETC_PATH . $pattern;
            if (!is_readable($dbSchemaFilePath)) {
                return [];
            }
            return [$dbSchemaFilePath => file_get_contents($dbSchemaFilePath)];
        }
        
        $files = [];
        foreach ($this->getXmlFilesIterator($modulePath, $pattern) as $file) {
            if (!isset($file[0])) {
                continue;
            }
            $files[$file[0]] = file_get_contents($file[0]);
        }
        return $files;
    }

    /**
     * @param string $modulePath
     * @param string $pattern
     * @return RegexIterator
     */
    private function getXmlFilesIterator(string $modulePath, string $pattern): RegexIterator
    {
        return new RegexIterator(
            new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator(
                    $modulePath . GetXmlFileContent::ETC_PATH,
                    RecursiveDirectoryIterator::SKIP_DOTS
                ),
                RecursiveIteratorIterator::SELF_FIRST
            ),
            $pattern,
            RecursiveRegexIterator::GET_MATCH
        );
    }
}
