<?php

namespace CleantalkSP\SpbctWP\Scanner\OSCron\Shell;

class OSCronSetEnvCron
{
    /**
     * @var string The template for the command to write to the crontab.
     */
    private static $write_command_template = 'echo %s | crontab -';

    /**
     * Sets a new cron set using the provided command.
     *
     * @param string $command The command to be added to the crontab.
     * @return void
     * @psalm-suppress ForbiddenCode
     */
    public static function set($command)
    {
        //probably need to sanitize $command
        $command = sprintf(static::$write_command_template, self::prepare($command));
        if ( function_exists('shell_exec') ) {
            @shell_exec($command);
        }
    }

    /**
     * Prepare command, using escapeshellarg if exists
     * @param string $command
     *
     * @return string
     */
    private static function prepare($command)
    {
        if (function_exists('escapeshellarg')) {
            $command = escapeshellarg($command);
        } else {
            $command = '"' . str_replace('"', '\"', $command) . '"';
        }
        return $command;
    }
}
