<?php
/**
 * Known marker detector.
 *
 * @package LocalGuardScanner
 */

namespace LocalGuardScanner\Detection\File;

use LocalGuardScanner\Detection\Rules\Rule;
use LocalGuardScanner\Detection\Rules\RuleSet;
use LocalGuardScanner\Domain\Detection\Evidence;
use LocalGuardScanner\Domain\Detection\MalwareHeuristicDetector;
use LocalGuardScanner\Domain\Detection\ScannableObject;

/**
 * Searches exact high-confidence markers supplied by signed rules.
 */
final class SignatureDetector implements MalwareHeuristicDetector {
	/** @var Rule[] */
	private $rules;

	/** @param RuleSet $rules Signed rules. */
	public function __construct( RuleSet $rules ) {
		$this->rules = $rules->of_type( 'marker' );
	}

	/** @return string */
	public function id() {
		return 'file.signatures';
	}

	/** @inheritDoc */
	public function inspect( ScannableObject $scanned_object ) {
		$attributes = $scanned_object->attributes();
		$content    = isset( $attributes['content'] ) && is_string( $attributes['content'] ) ? $attributes['content'] : '';
		if ( '' === $content ) {
			return array();
		}
		$evidence = array();
		foreach ( $this->rules as $rule ) {
			$data    = $rule->data();
			$markers = isset( $data['markers'] ) && is_array( $data['markers'] ) ? $data['markers'] : array();
			foreach ( $markers as $marker ) {
				if ( is_string( $marker ) && '' !== $marker && false !== stripos( $content, $marker ) ) {
					$evidence[] = new Evidence( $rule->id(), $rule->weight(), $rule->confidence(), $rule->message_key(), $marker );
					break;
				}
			}
		}
		return $evidence;
	}
}
