<?php

namespace CleantalkSP\SpbctWP\Scanner\OSCron;

class OSCronTaskAnalyser
{
    private $verdict = false;
    private $signature_matches = array();

    public function __construct()
    {
    }

    /**
     * @param string $command
     * @param array $signatures
     * @return $this
     */
    public function check($command, $signatures = array())
    {
        $matches = $this->scanString($command, $signatures);
        $this->signature_matches = $matches;
        $this->verdict = !empty($matches);

        return $this;
    }

    /**
     * Scan string against malware signatures
     * @param mixed $string
     * @param mixed $signatures
     * @return array
     */
    public static function scanString($string, $signatures)
    {
        $matches = array();
        foreach ($signatures as $signature) {
            if (
                isset($signature['type']) &&
                in_array($signature['type'], array('CRON', 'CODE_PHP', 'CODE_JS', 'CODE_HTML'))
            ) {
                $is_regexp = \CleantalkSP\SpbctWP\Helpers\Helper::isRegexp($signature['body']);
                if (
                    ($is_regexp && preg_match($signature['body'], $string)) ||
                    (!$is_regexp && stripos($string, $signature['body']) !== false)
                ) {
                    $matches[] = $signature;
                }
            }
        }

        return $matches;
    }

    /**
     * Get triggered signatures
     * @return array
     */
    public function getSignatureMatches()
    {
        return $this->signature_matches;
    }

    /**
     * @return bool
     */
    public function getVerdict()
    {
        return $this->verdict;
    }
}
