<?php
if ( ! class_exists( 'PHP_CodeSniffer\Files\File' ) ) {
	return;
}

class Aegisify_Sniffs_Security_UnsafeEvalIncludeSniff implements PHP_CodeSniffer\Sniffs\Sniff {

	public function register() {
		$tokens = array( T_STRING );
		if ( defined( 'T_EVAL' ) ) {
			$tokens[] = T_EVAL;
		}
		if ( defined( 'T_INCLUDE' ) ) {
			$tokens[] = T_INCLUDE;
		}
		if ( defined( 'T_INCLUDE_ONCE' ) ) {
			$tokens[] = T_INCLUDE_ONCE;
		}
		if ( defined( 'T_REQUIRE' ) ) {
			$tokens[] = T_REQUIRE;
		}
		if ( defined( 'T_REQUIRE_ONCE' ) ) {
			$tokens[] = T_REQUIRE_ONCE;
		}
		return $tokens;
	}

	public function process( PHP_CodeSniffer\Files\File $phpcsFile, $stackPtr ) {
		if ( 'php' !== strtolower( pathinfo( $phpcsFile->getFilename(), PATHINFO_EXTENSION ) ) ) {
			return;
		}
		$tokens  = $phpcsFile->getTokens();
		$content = strtolower( $tokens[ $stackPtr ]['content'] );
		$dangerous = array( 'eval', 'include', 'include_once', 'require', 'require_once', 'unserialize' );
		if ( ! in_array( $content, $dangerous, true ) ) {
			return;
		}
		$message = 'Potential dangerous PHP sink detected (%s). Review trust boundaries and avoid executing or including untrusted input.';
		$phpcsFile->addError( $message, $stackPtr, 'UnsafeEvalInclude', array( $content ) );
	}
}
