kuvalda-cron/console/MoleController.php

100 lines
2.8 KiB
PHP

<?php
/**
* @link https://www.kuvalda.ru/
* @copyright
* @license
*/
namespace dominion\cron\console;
use Yii;
use yii\console\Controller;
use yii\console\ExitCode;
use dominion\cron\models\MoleTask;
use yii\base\InlineAction;
/**
* Запуск агента по расписанию
*
* @author Rybkin Sasha <ribkin@dominion.ru>
* @since 0.1
*/
class MoleController extends Controller
{
/**
* Запуск всех агентов для проекта yii из mole_task
* @return int Exit code
*/
public function actionIndex()
{
$filePatch = Yii::getAlias('@app/runtime/lock.lock');
if (!file_exists($filePatch))
{
$fp = fopen($filePatch, "w");
fwrite($fp, "");
fclose($fp);
}
$file = fopen($filePatch, 'r+');
if (flock($file, LOCK_EX | LOCK_NB))
{
$model = new MoleTask;
$tasks = $model->getAllTask();
foreach ($tasks as $task)
{
try
{
$task->dateStart = date('Y-m-d H:i:s');
$task->save();
$params = explode('/', $task->controller);
$controller = $this->format($params[0]);
$action = 'actionIndex';
if (isset($params[1]))
{
$action = 'action' . $this->format($params[1]);
}
if(stripos($controller, 'Controller') === false)
{
$controller .= 'Controller';
}
$class = 'app\\commands\\' . $controller;
if (class_exists($class))
{
$control = new $class($task->controller, 'product');
if (method_exists($control, $action))
{
$params = $control->{$action}(unserialize($task->params));
if(!empty($params))
{
$task->params = serialize($params);
}
$task->isReady = 1;
}
}
$task->setCompleted();
} catch (\Exception $ex)
{
$task->dateStart = null;
$task->save();
print_r($ex->getMessage());
}
}
}
return ExitCode::OK;
}
protected function format($controller)
{
$params = explode('-', $controller);
foreach ($params as $key => $value)
{
$params[$key] = ucfirst($value);
}
return implode('', $params);
}
}