Skip to content

Instantly share code, notes, and snippets.

@arleighdickerson
Last active January 27, 2016 16:17
Show Gist options
  • Save arleighdickerson/c898e3add6963304699c to your computer and use it in GitHub Desktop.
Save arleighdickerson/c898e3add6963304699c to your computer and use it in GitHub Desktop.
<?php
namespace console\controllers;
use yii\helpers\StringHelper;
use yii\console\Controller;
use Yii;
abstract class SimulationController extends Controller {
public $defaultAction = 'default';
public $simulationMethodPrefix = 'sim';
public function actionOn() {
self::setStatus(true);
}
public function actionOff() {
self::setStatus(false);
}
public function actionRun($min, $max) {
return $this->runSimulation($min, $max, function () {
return true;
});
}
public function actionDefault($min = 3, $max = 15) {
try {
return $this->runSimulation($min, $max, function () {
return self::getStatus();
});
} catch (\Exception $e) {
self::setStatus(false);
throw $e;
}
}
protected function runSimulation($min, $max, $condition) {
try {
if ($condition()) {
$this->randomMethod();
}
} catch (\Exception $e) {
Yii::error($e->getMessage(), self::class);
}
sleep(rand($min, $max));
return $this->runSimulation($min, $max, $condition);
}
public static function setStatus($flag) {
if ($flag !== self::getStatus()) {
$flag
? self::start()
: self::stop();
}
}
public static function getStatus() {
if (file_exists(self::getMarker())) {
$pid = intval(trim(file_get_contents(self::getMarker())));
if (self::pidExists($pid)) {
return true;
}
}
return false;
}
public static function getMarker() {
return dirname(Yii::getAlias("@app")) . "/console/runtime/simulate.on";
}
public static function pidExists($pid) {
return boolval(exec('if kill -0 ' . $pid . ' >/dev/null 2>&1; then eval "echo 1"; else eval "echo 0"; fi'));
}
public static function start() {
if (file_exists(self::getMarker())) {
unlink(self::getMarker());
}
$yii = dirname(Yii::getAlias("@app")) . '/yii';
$file = self::getMarker();
$cmd = "nohup $yii simulate > /dev/null 2>&1 & echo $! > $file";
exec($cmd);
}
public static function stop() {
if (file_exists(self::getMarker())) {
$pid = intval(trim(file_get_contents(self::getMarker())));
exec("kill $pid");
unlink(self::getMarker());
}
}
public function randomMethod() {
$methods = array_filter(get_class_methods($this), function ($name) {
return StringHelper::startsWith($name, $this->simulationMethodPrefix);
});
$this->{$methods[array_rand($methods)]}();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment