<?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 GetDiXmlFileContents
{
    /**
     * @var
     */
    private const ETC_PATH = '/etc/';

    /**
     * @param string $modulePath
     * @return array
     */
    public function execute(string $modulePath): array
    {
        if (!is_dir($modulePath . GetDiXmlFileContents::ETC_PATH)) {
            return [];
        }
        $files = [];
        foreach ($this->getDiXmlFilesIterator($modulePath . GetDiXmlFileContents::ETC_PATH) as $file) {
            if (!isset($file[0])) {
                continue;
            }
            $files[$file[0]] = file_get_contents($file[0]);
        }
        return $files;
    }

    /**
     * @param string $moduleEtcPath
     * @return RegexIterator
     */
    private function getDiXmlFilesIterator(string $moduleEtcPath): RegexIterator
    {
        return new RegexIterator(
            new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($moduleEtcPath, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ),
            '/^.+\/di.xml$/i',
            RecursiveRegexIterator::GET_MATCH
        );
    }
}
