<?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\MagentoProject;
use Magento\Mray\Index\Scanner\Tuner;
use Magento\Mray\Package\AbstractTree\ScannerSubject;
use Magento\Mray\Parse\Xml\XMLStringToAssocArray;
use Magento\Mray\Model\Xml\GetXmlFileContent;

class ProjectRootDbSchemaNodeSetter implements Tuner
{
    /**
     * @var GetXmlFileContent
     */
    private $getDbSchemaXmlFileContent;

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

    /**
     * @inheritDoc
     */
    public function tune(ScannerSubject $subject, array $packages): array
    {
        foreach ($packages as $package) {
            if ($package instanceof MagentoProject && $package->attributes['path']) {
                $dbSchemaXmlFileContent = $this->getDbSchemaXmlFileContent->execute(
                    $package->attributes['path'] .'/app',
                    'db_schema.xml'
                );
                if (count($dbSchemaXmlFileContent) !== 1) {
                    return $packages;
                }
                $package->attributes['dbSchema'][$package->attributes['path']] =
                    current($dbSchemaXmlFileContent);
            }
        }
        return $packages;
    }
}
