<?php declare( strict_types=1 );

namespace FernleafSystems\Wordpress\Plugin\Shield\Scans\Afs\Scans;

use FernleafSystems\Wordpress\Plugin\Shield\Scans\Afs\Exceptions;
use FernleafSystems\Wordpress\Plugin\Shield\Scans\Afs\Malware\Constants;
use FernleafSystems\Wordpress\Plugin\Shield\Scans\Afs\ScanActionVO;

class MalwareFile extends BaseScan {

	/**
	 * @throws Exceptions\MalwareFileException
	 * @throws \InvalidArgumentException
	 */
	protected function runScan() :bool {
		/** @var ScanActionVO $action */
		$action = $this->getScanActionVO();

		$searcher = ( new LocateNeedles() )->setPath( $this->pathFull );

		foreach ( $action->patterns_raw as $signature ) {
			if ( $searcher->raw( $signature ) ) {
				throw new Exceptions\MalwareFileException(
					$this->pathFull,
					[
						'mal_sig' => $signature,
					]
				);
			}
		}

		foreach ( $action->patterns_iraw as $signature ) {
			if ( $searcher->iRaw( $signature ) ) {
				throw new Exceptions\MalwareFileException(
					$this->pathFull,
					[
						'mal_sig' => $signature,
					]
				);
			}
		}

		foreach ( $action->patterns_regex as $signature ) {
			if ( $searcher->regex( $signature ) ) {
				throw new Exceptions\MalwareFileException(
					$this->pathFull,
					[
						'mal_sig' => $signature,
					]
				);
			}
		}

		foreach ( \array_merge( $action->patterns_keywords, $action->patterns_functions ) as $signature ) {
			if ( $searcher->raw( $signature ) ) {
				throw new Exceptions\MalwareFileException(
					$this->pathFull,
					[
						'mal_sig' => $signature,
					]
				);
			}
		}

		return true;
	}

	protected function getSupportedFileExtensions() :array {
		return [ 'php', 'php5', 'php7', 'ico', 'mo' ];
	}

	protected function getPathExcludes() :array {
		return Constants::MALWARE_NOISE_REGEX;
	}
}