<?php
/**
 * PHP obfuscation detector.
 *
 * @package LocalGuardScanner
 */

namespace LocalGuardScanner\Detection\Php;

use LocalGuardScanner\Domain\Detection\Evidence;
use LocalGuardScanner\Domain\Detection\MalwareHeuristicDetector;
use LocalGuardScanner\Domain\Detection\ScannableObject;

/**
 * Reports strong obfuscation as a supporting, non-decisive signal.
 */
final class ObfuscationDetector implements MalwareHeuristicDetector {
	/** @return string */
	public function id() {
		return 'php.obfuscation';
	}

	/** @inheritDoc */
	public function inspect( ScannableObject $scanned_object ) {
		$attributes = $scanned_object->attributes();
		$content    = isset( $attributes['content'] ) && is_string( $attributes['content'] ) ? $attributes['content'] : '';
		if ( 'file' !== $scanned_object->type() || ! PhpSource::has_open_tag( $content ) ) {
			return array();
		}
		$evidence = array();
		if ( preg_match( '/[A-Za-z0-9+\/=]{400,}/', $content ) ) {
			$evidence[] = new Evidence( 'php.long_encoded_payload', 34, 70, 'long_encoded_payload', 'encoded-string>400' );
		}
		if ( preg_match_all( '/\bchr\s*\(/i', $content ) >= 12 ) {
			$evidence[] = new Evidence( 'php.chr_construction', 32, 74, 'repeated_character_construction', 'chr-calls>=12' );
		}
		return $evidence;
	}
}
