Skip to content

Instantly share code, notes, and snippets.

@BurakBoz
Created July 28, 2019 02:06
Show Gist options
  • Save BurakBoz/4fb36bbb301ce91b60e183b1d16b5b71 to your computer and use it in GitHub Desktop.
Save BurakBoz/4fb36bbb301ce91b60e183b1d16b5b71 to your computer and use it in GitHub Desktop.
PHP Crontab shell command utilizer class
<?php
/**
* Class Crontab
* About: crontab shell command utilizer.
* Author: Burak BOZ
* GitHub: https://github.com/BurakBoz
* License: No License & Restrictions
*/
class Crontab
{
/**
* @param string $jobs
* @return array
*/
static private function stringToArray($jobs = '')
{
return array_filter(explode("\n", trim(preg_replace("/(\r+|\n+)/", "\n", $jobs))));
}
/**
* @param array $jobs
* @return string
*/
static private function arrayToString($jobs = [])
{
return implode("\n", $jobs);
}
/**
* @param array $jobs
* @return string|null
*/
static private function saveJobs($jobs = [])
{
return shell_exec('echo ' . escapeshellarg(self::arrayToString($jobs)) . ' | crontab -');
}
/**
* @return array
*/
static public function getJobs()
{
return self::stringToArray(shell_exec('crontab -l'));
}
/**
* @param string $job
* @return bool
*/
static public function doesJobExist($job = '')
{
return in_array($job, self::getJobs());
}
/**
* @param string $job
* @return bool|string|null
*/
static public function addJob($job = '')
{
if (self::doesJobExist($job)) return false;
$jobs = self::getJobs();
$jobs[] = $job;
return self::saveJobs($jobs);
}
/**
* @param string $job
* @return bool|string|null
*/
static public function removeJob($job = '')
{
if (!self::doesJobExist($job)) return false;
$jobs = self::getJobs();
unset($jobs[array_search($job, $jobs)]);
return self::saveJobs($jobs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment