<?php
/**
 * Copyright 2020 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 Sut\Domain\PhpCs;

use Sut\Domain\Issue\DTO\Issue;
use Sut\Domain\Issue\Converter\GetFromPhpCsJson as IssueConverter;
use Sut\Infrastructure\Cmd\CmdService;

class GetPhpCsIssues
{
    private const RULESET_PATH = '/vendor/magento/magento-coding-standard/Magento2/ruleset.xml';
    private const PHPCS_CMD = "/vendor/bin/phpcs --standard='%s' %s -s --report=json";

    /**
     * @var CmdService
     */
    private $cmdService;

    /**
     * @var IssueConverter
     */
    private $issueConverter;

    /**
     * @var string
     */
    private $projectRoot;

    /**
     * @var string
     */
    private $rulesetPath;

    /**
     * @param CmdService $cmdService
     * @param IssueConverter $issueConverter
     * @param string $projectRoot
     * @param string|null $rulesetPath
     */
    public function __construct(
        CmdService $cmdService,
        IssueConverter $issueConverter,
        string $projectRoot,
        string $rulesetPath = null
    ) {
        $this->cmdService = $cmdService;
        $this->issueConverter = $issueConverter;
        $this->projectRoot = $projectRoot;
        $this->rulesetPath = $rulesetPath ?? self::RULESET_PATH;
    }

    /**
     * @param string $path
     * @return Issue[]
     */
    public function execute(string $path): array
    {
        $phpCsJson = $this->cmdService->execCommand(
            sprintf(
                $this->projectRoot . self::PHPCS_CMD,
                $this->projectRoot . $this->rulesetPath,
                $path
            )
        );

        if (!isset($phpCsJson->getOutput()[0]) || !$phpCsJson->getOutput()[0]) {
            return [];
        }

        return $this->issueConverter->execute($phpCsJson->getOutput()[0]);
    }
}
