<?php
/**
 * Checks that the open tag is defined correctly.
 *
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @copyright 2006-2023 Squiz Pty Ltd (ABN 77 084 670 600)
 * @copyright 2023 PHPCSStandards and contributors
 * @license   https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/HEAD/licence.txt BSD Licence
 */

namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Files;

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;

class OpenTagSniff implements Sniff
{


    /**
     * Returns an array of tokens this test wants to listen for.
     *
     * @return array<int|string>
     */
    public function register()
    {
        return [T_OPEN_TAG];
    }


    /**
     * Processes this sniff when one of its tokens is encountered.
     *
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
     * @param int                         $stackPtr  The position of the current
     *                                               token in the stack.
     *
     * @return int
     */
    public function process(File $phpcsFile, int $stackPtr)
    {
        if ($stackPtr !== 0) {
            // This rule only applies if the open tag is on the first line of the file.
            return $phpcsFile->numTokens;
        }

        $tokens = $phpcsFile->getTokens();
        $next   = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
        if ($next === false) {
            // Empty file.
            return $phpcsFile->numTokens;
        }

        if ($tokens[$next]['line'] !== $tokens[$stackPtr]['line']) {
            // Tag is on a line by itself.
            return $phpcsFile->numTokens;
        }

        $hasInlineHTML = $phpcsFile->findNext(T_INLINE_HTML, 0);
        if ($hasInlineHTML !== false) {
            // This rule only applies to PHP-only files.
            return $phpcsFile->numTokens;
        }

        $error = 'Opening PHP tag must be on a line by itself';
        $fix   = $phpcsFile->addFixableError($error, $stackPtr, 'NotAlone');
        if ($fix === true) {
            $phpcsFile->fixer->beginChangeset();

            // Remove whitespace between the open tag and the next non-empty token.
            for ($i = ($stackPtr + 1); $i < $next; $i++) {
                $phpcsFile->fixer->replaceToken($i, '');
            }

            $phpcsFile->fixer->addNewline($stackPtr);
            $phpcsFile->fixer->endChangeset();
        }

        return $phpcsFile->numTokens;
    }
}
