<?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\Index\Scanner\Tuner;

use Magento\Mray\Package\AbstractTree\Component\MagentoModule;
use Magento\Mray\Index\Scanner\Tuner;
use Magento\Mray\Package\AbstractTree\ScannerSubject;
use Magento\Mray\Parse\Xml\GetDiXmlDeclarations;
use Magento\Mray\Model\Xml\GetXmlFileContent;

class DiXmlNodeSetter implements Tuner
{
    /**
     * @var GetDiXmlDeclarations
     */
    private $diXmlDeclarationsParser;

    /**
     * @var GetXmlFileContent
     */
    private $diXmlFileContentLoader;

    /**
     *
     */
    public function __construct()
    {
        $this->diXmlDeclarationsParser = new GetDiXmlDeclarations();
        $this->diXmlFileContentLoader = new GetXmlFileContent();
    }

    /**
     * @inheritDoc
     */
    public function tune(ScannerSubject $subject, array $packages): array
    {
        foreach ($packages as $package) {
            if (!$package instanceof MagentoModule || !isset($package->attributes['path'])) {
                continue;
            }
            foreach ($this->diXmlFileContentLoader->execute(
                $package->attributes['path'],
                '/^.+\/di.xml$/i',
                true
            ) as $path => $content) {
                $usageCases = $this->diXmlDeclarationsParser->execute($content);
                foreach ($usageCases as $case) {
                    $case->setLocationContext(['file' => $path]);
                }
                $package->attributes['diXmlDeclarations'][$path] = $usageCases;
            }
        }
        return $packages;
    }
}
