diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..47f53f7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,50 @@ +# Created by .gitignore support plugin (hsz.mobi) +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm + +*.iml + +## Directory-based project format: +.idea/ +# if you remove the above rule, at least ignore the following: + +# User-specific stuff: +# .idea/workspace.xml +# .idea/tasks.xml +# .idea/dictionaries + +# Sensitive or high-churn files: +# .idea/dataSources.ids +# .idea/dataSources.xml +# .idea/sqlDataSources.xml +# .idea/dynamic.xml +# .idea/uiDesigner.xml + +# Gradle: +# .idea/gradle.xml +# .idea/libraries + +# Mongo Explorer plugin: +# .idea/mongoSettings.xml + +## File-based project format: +*.ipr +*.iws + +## Plugin-specific files: + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties + + diff --git a/README.md b/README.md index 15b8ef1..aa6831f 100644 --- a/README.md +++ b/README.md @@ -29,16 +29,16 @@ Database Configuration Open `php-cli-app-phalcon/app/config.php` and edit your database connection credentials ```php -$settings = array( - 'database' => array( +$settings = [ + 'database' => [ 'adapter' => 'Mysql', /* Possible Values: Mysql, Postgres, Sqlite */ 'host' => 'your_ip_or_hostname', 'username' => 'your_user', 'password' => 'your_password', 'name' => 'your_database_schema', 'port' => 3306 - ), -); + ], +]; ``` Import the tables into your MySQL Server @@ -96,6 +96,8 @@ Only allow 1 instance to run at a time `--single` php cli.php Example test1 --single ``` +> Single param has problem in windows machine + Enable all flags ```bash php cli.php Example test1 --debug --record --single diff --git a/app/config/autoload.php b/app/config/autoload.php index 4a69ab5..43edc14 100644 --- a/app/config/autoload.php +++ b/app/config/autoload.php @@ -2,28 +2,28 @@ /** * Autoload Class files by PHP namespacing support - * + * * @author Jete O'Keeffe - * @eg - $autoload = [ - 'namespace' => '/path/to/dir', - 'namespace' => '/path/to/dir' - ]; - return $autoload; + * @eg +$autoload = [ + * 'namespace' => '/path/to/dir', + * 'namespace' => '/path/to/dir' + * ]; + * return $autoload; * * @note $appDir is the app directory (/path/to/php-cli-app-phalcon/app) */ $autoload = [ - 'Utilities\Debug' => $appDir . '/library/utilities/debug/', - 'Application' => $appDir . '/library/application/', - 'Interfaces' => $appDir . '/library/interfaces/', - 'Controllers' => $appDir . '/controllers/', - 'Models' => $appDir . '/models/', - 'Tasks' => $appDir . '/tasks/', - 'Cli' => $appDir . '/library/cli/', - 'Events\Cli' => $appDir . '/library/events/cli/', - 'Events\Database' => $appDir . '/library/events/database/', + 'Utilities\Debug' => $appDir . '/library/utilities/debug/', + 'Application' => $appDir . '/library/application/', + 'Interfaces' => $appDir . '/library/interfaces/', + 'Controllers' => $appDir . '/controllers/', + 'Models' => $appDir . '/models/', + 'Tasks' => $appDir . '/tasks/', + 'Cli' => $appDir . '/library/cli/', + 'Events\Cli' => $appDir . '/library/events/cli/', + 'Events\Database' => $appDir . '/library/events/database/', ]; return $autoload; diff --git a/app/config/config.php b/app/config/config.php index e40b941..585ff96 100644 --- a/app/config/config.php +++ b/app/config/config.php @@ -4,16 +4,16 @@ * Settings to be stored in dependency injector */ -$settings = array( - 'database' => array( - 'adapter' => 'Mysql', - 'host' => 'localhost', - 'username' => 'test', - 'password' => 'test', - 'name' => 'cli', - 'port' => 3306 - ), -); +$settings = [ + 'database' => [ + 'adapter' => 'Mysql', + 'host' => 'localhost', + 'username' => 'test', + 'password' => 'test', + 'name' => 'cli', + 'port' => 3306 + ], +]; return $settings; diff --git a/app/library/application/Cli.php b/app/library/application/Cli.php index c534bcf..6a4753b 100644 --- a/app/library/application/Cli.php +++ b/app/library/application/Cli.php @@ -3,7 +3,7 @@ /** * Cli based Application used to setup Tasks to run * - * @author Jete O'Keeffe + * @author Jete O'Keeffe * @version 1.0 * @package Cli */ @@ -13,465 +13,488 @@ use \Cli\Output as Output; use \Interfaces\IRun as IRun; -class Cli extends \Phalcon\Cli\Console implements IRun { - - /** - * @const - */ - const ERROR_SINGLE = 999; - - /** - * @var string filename that will store the pid - */ - protected $_pidFile; - - /** - * @var string directory path that will contain the pid file - */ - protected $_pidDir = '/tmp'; - - /** - * @var bool if debug mode is on or off - */ - protected $_isDebug; - - /** - * @var bool whether to record tasks by inserting into the database or not - */ - protected $_isRecording; - - /** - * @var - */ - protected $_argc; - - /** - * @var - */ - protected $_argv; - - /** - * @var - */ - protected $_isSingleInstance; - - /** - * Task for cli handler to run - */ - protected $_task; - /** - * Action for cli handler to run - */ - protected $_action; - - /** - * Parameters to be passed to Task - * @var - */ - protected $_params; - - /** - * Task Id from the database - * @var - */ - protected $_taskId; - - /** - * constructor - * - * @param directory of the pid file - */ - public function __construct($pidDir = '/tmp') { - $this->_pidDir = $pidDir; - $this->_stderr = $this->_stdout = ''; - $this->_isSingleInstance = $this->_isRecording = FALSE; - $this->_task = $this->_action = NULL; - $this->_params = array(); - $this->_taskId = NULL; - } - - /** - * Set Dependency Injector with configuration variables - * - * @throws Exception - * @param string $file full path to configuration file - */ - public function setConfig($file) { - - if (!file_exists($file)) { - throw new \Exception('Unable to load configuration file'); - } - - $di = new \Phalcon\DI\FactoryDefault\CLI(); - $di->set('config', new \Phalcon\Config(require $file)); - - $di->set('db', function() use ($di) { - - $type = strtolower($di->get('config')->database->adapter); - $creds = array( - 'host' => $di->get('config')->database->host, - 'username' => $di->get('config')->database->username, - 'password' => $di->get('config')->database->password, - 'dbname' => $di->get('config')->database->name - ); - - if ($type == 'mysql') { - $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($creds); - } else if ($type == 'postgres') { - $connection = new \Phalcon\Db\Adapter\Pdo\Postgesql($creds); - } else if ($type == 'sqlite') { - $connection = new \Phalcon\Db\Adapter\Pdo\Sqlite($creds); - } else { - throw new Exception('Bad Database Adapter'); - } - - $connection->setEventsManager(new \Events\Database\Profile()); - - return $connection; - }); - - $this->setDI($di); +class Cli extends \Phalcon\Cli\Console implements IRun +{ + + /** + * @const + */ + const ERROR_SINGLE = 999; + + /** + * @var string filename that will store the pid + */ + protected $_pidFile; + + /** + * @var string directory path that will contain the pid file + */ + protected $_pidDir = '/tmp'; + + /** + * @var bool if debug mode is on or off + */ + protected $_isDebug; + + /** + * @var bool whether to record tasks by inserting into the database or not + */ + protected $_isRecording; + + /** + * @var int count arguments + */ + protected $_argc; + + /** + * @var array of arguments + */ + protected $_argv; + + /** + * @var bool + */ + protected $_isSingleInstance; + + /** + * Task for cli handler to run + * @var string current task + */ + protected $_task; + + /** + * Action for cli handler to run + * @var string name of current action + */ + protected $_action; + + /** + * Parameters to be passed to Task + * @var array + */ + protected $_params; + + /** + * Task Id from the database + * @var bool|int + */ + protected $_taskId; + + /** + * constructor + * + * @param string $pidDir directory of the pid file + */ + public function __construct($pidDir = '/tmp') + { + $this->_pidDir = $pidDir; + $this->_stderr = $this->_stdout = ''; + $this->_isSingleInstance = $this->_isRecording = false; + $this->_task = $this->_action = null; + $this->_params = []; + $this->_taskId = null; + } + + /** + * Set Dependency Injector with configuration variables + * + * @throws \Exception + * @param string $file full path to configuration file + * @param \Phalcon\DI\FactoryDefault\CLI $di + */ + public function setConfig($file, \Phalcon\DI\FactoryDefault\CLI $di) + { + + if (!file_exists($file)) { + throw new \Exception('Unable to load configuration file'); } + $di->set('config', new \Phalcon\Config(require $file)); + + $di->set('db', function () use ($di) { + + $type = strtolower($di->get('config')->database->adapter); + $creds = [ + 'host' => $di->get('config')->database->host, + 'username' => $di->get('config')->database->username, + 'password' => $di->get('config')->database->password, + 'dbname' => $di->get('config')->database->name + ]; + + if ($type == 'mysql') { + $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($creds); + } else if ($type == 'postgres') { + $connection = new \Phalcon\Db\Adapter\Pdo\Postgesql($creds); + } else if ($type == 'sqlite') { + $connection = new \Phalcon\Db\Adapter\Pdo\Sqlite($creds); + } else { + throw new \Exception('Bad Database Adapter'); + } + + $connection->setEventsManager(new \Events\Database\Profile()); + + return $connection; + }); + } + + /** + * Get default DI to CLI application + * @return \Phalcon\DI\FactoryDefault\CLI + */ + public function getDefaultDI() + { + return new \Phalcon\DI\FactoryDefault\CLI(); + } + + + /** + * Set namespaces to tranverse through in the autoloader + * + * @link http://docs.phalconphp.com/en/latest/reference/loader.html + * @throws \Exception + * @param string $file map of namespace to directories + * @param string $appDir require to autoloader file + */ + public function setAutoload($file, $appDir) + { + if (!file_exists($file)) { + throw new \Exception('Unable to load autoloader file'); + } - /** - * Set namespaces to tranverse through in the autoloader - * - * @link http://docs.phalconphp.com/en/latest/reference/loader.html - * @throws Exception - * @param string $file map of namespace to directories - * @param string $appDir location of the app directory - */ - public function setAutoload($file, $appDir) { - if (!file_exists($file)) { - throw new \Exception('Unable to load autoloader file'); - } - - // Set dir to be used inside include file - $namespaces = include $file; + // Set dir to be used inside include file + $namespaces = require $file; + + $loader = new \Phalcon\Loader(); + $loader->registerNamespaces($namespaces)->register(); + } + + + /** + * Set Application arguments + * + * @param array $argv array of arguments + * @param int $argc count of arguments + */ + public function setArgs($argv, $argc) + { + $this->_argv = $argv; + $this->_argc = $argc; + } + + + /** + * Set events to be triggered before/after certain stages in Micro App + * + * @param \Phalcon\Events\Manager $events events to add + */ + public function setEvents(\Phalcon\Events\Manager $events) + { + $this->setEventsManager($events); + } + + + /** + * kick off the task + */ + public function run() + { + + try { + $exit = 0; + $taskId = null; + + // Check on stupid mistakes + $this->preTaskCheck($this->_argc); + + $this->determineTask($this->_argv); + // Check Instance Mode (can only one run at a time) + $this->checkProcessInstance($this->_argv); + + // Add Record to DB that task started + if ($this->_isRecording) { + $task = new \Models\Task(); + $this->_taskId = $task->insertTask($_SERVER['PHP_SELF']); + } + + // Setup args (task, action, params) for console + $args['task'] = 'Tasks' . "\\" . $this->_task; + $args['action'] = !empty($this->_action) ? $this->_action : 'main'; + if (!empty($this->_params)) { + $args['params'] = $this->_params; + } + + // Kick off Task + $this->handle($args); + + $this->removeProcessInstance(); + + // Update status + if ($this->_isRecording) { + $task->updateSuccessful($this->_taskId, Output::getStdout(), Output::getStderr(), $exit); + } + + + } catch (\Cli\Exception $e) { + $exit = 3; + $this->handleException($e, $this->_taskId, $exit); + + } catch (\Phalcon\Exception $e) { + $exit = 2; + $this->handleException($e, $this->_taskId, $exit); + + } catch (\Exception $e) { + $exit = 1; + $this->handleException($e, $this->_taskId, $exit); + } - $loader = new \Phalcon\Loader(); - $loader->registerNamespaces($namespaces)->register(); + return $exit; + } + + + /** + * Check if pid file needs to be created + * + * @throws \Exception + */ + public function checkProcessInstance() + { + + // Single Instance + if ($this->isSingleInstance()) { + + $file = sprintf('%s-%s.pid', $this->_task, $this->_action); + $pid = \Cli\Pid::singleton($file); + + // Default + $this->_pidFile = $file; + + // Make sure only 1 app at a time is running + if ($pid->exists()) { + throw new \Exception('Instance of task is already running', self::ERROR_SINGLE); + } else { + if ($pid->create()) { + if ($this->isDebug()) { + Output::stdout("[DEBUG] Created Pid File: " . $pid->getFileName()); + } + } else { + $desc = ''; + throw new \Exception('unable to create pid file ' . $desc); + } + } } + } + + /** + * Remove Pid File + * + * @return bool + */ + public function removeProcessInstance() + { + if ($this->isSingleInstance()) { + $pid = \Cli\Pid::singleton(''); + if ($pid->created() && !$pid->removed()) { + if ($result = $pid->remove()) { + if ($this->isDebug()) { + Output::stdout("[DEBUG] Removed Pid File: " . $pid->getFileName()); + } + } else { + $msg = Output::COLOR_RED . "[ERROR]" . Output::COLOR_NONE . " Failed to remove Pid File: $this->_pidFile"; + Output::stderr($msg); + } + return $result; + } + } - /** - * Set Application arguments - * - * @param array of arguments - * @param count of arguments - */ - public function setArgs($argv, $argc) { - $this->_argv = $argv; - $this->_argc = $argc; - } - - - /** - * Set events to be triggered before/after certain stages in Micro App - * - * @param object $event events to add - */ - public function setEvents(\Phalcon\Events\Manager $events) { - $this->setEventsManager($events); + return true; + } + + /** + * Get the task/action to direct to + * + * @param array $flags cli arguments to determine tasks/action/param + * @throws \Exception + */ + protected function determineTask($flags) + { + + // Since first argument is the name so script executing (pop it off the list) + array_shift($flags); + + if (is_array($flags) && !empty($flags)) { + foreach ($flags as $flag) { + if (empty($this->_task) && !$this->isFlag($flag)) { + $this->_task = $flag; + } else if (empty($this->_action) && !$this->isFlag($flag)) { + $this->_action = $flag; + } else if (!$this->isFlag($flag)) { + $this->_params[] = $flag; + } + } + } else { + throw new \Exception('Unable to determine task/action/params'); + } + } + + /** + * set mode of multiple or single instance at a time + * + * @param int $mode + */ + public function setMode($mode) + { + $this->_mode = $mode; + } + + /** + * set the directory location of the pid file + * + * @param $dir string + */ + public function setPidDir($dir) + { + $this->_pidDir = $dir; + } + + + /** + * make sure everything required is setup before starting the task + * + * @param int $argc count of arguments + * @throws \Exception + */ + protected function preTaskCheck($argc) + { + + // Make sure task is added + if ($argc < 2) { + throw new \Exception('Bad Number of Params needed for script'); + } + } + + /** + * sets debug mode + * + * @param bool $debug + */ + public function setDebug($debug) + { + $this->_isDebug = $debug; + if ($debug) { + error_reporting(E_ALL); + ini_set('display_errors', 1); + } + } + + /** + * Is debug enable? + * @return bool + */ + public function isDebug() + { + return $this->_isDebug; + } + + /** + * Set Application to record results to database + * + * @param bool + */ + public function setRecording($record) + { + $this->_isRecording = $record; + } + + /** + * Determine if application is recording output (stdout and stderr) to database + * + * @return bool + */ + public function isRecording() + { + return $this->_isRecording; + } + + /** + * Set Single Instance Flag + * + * @param bool + */ + public function setSingleInstance($single) + { + $this->_isSingleInstance = $single; + } + + /** + * determine if only a single instance is allowed to run + * + * @return bool + */ + public function isSingleInstance() + { + return $this->_isSingleInstance; + } + + + /** + * handle script ending exception + * + * @param \Exception $e that caused the failure + * @param int $taskId id of the task you started + * @param int $exit code status of the process + */ + protected function handleException(\Exception $e, $taskId, $exit) + { + + $sub = '%s[ERROR]%s %s file: %s line: %d'; + + // Remove Process Instance + if ($e->getCode() != self::ERROR_SINGLE) { + $this->removeProcessInstance(); } + // Update Failure + if ($this->_isRecording && $taskId > 0) { + $stdout = Output::getStdout(); + $stderr = Output::getStderr(); + // Update Task w/ error messages + $task = new \Models\Task(); + $task->updateFailed($taskId, $stdout, $stderr, $exit); + } - /** - * kick off the task - */ - public function run() { - - try { - $exit = 0; - $taskId = NULL; - - // Check on stupid mistakes - $this->preTaskCheck($this->_argc); - - $this->determineTask($this->_argv); - // Check Instance Mode (can only one run at a time) - $this->checkProcessInstance($this->_argv); - - // Add Record to DB that task started - if ($this->_isRecording) { - $task = new \Models\Task(); - $this->_taskId = $task->insertTask($_SERVER['PHP_SELF']); - } - - // Setup args (task, action, params) for console - $args['task'] = 'Tasks' . "\\" . $this->_task; - $args['action'] = !empty($this->_action) ? $this->_action : 'main'; - if (!empty($this->_params)) { - $args['params'] = $this->_params; - } - - // Kick off Task - $this->handle($args); - - $this->removeProcessInstance(); - - // Update status - if ($this->_isRecording) { - $task->updateSuccessful($this->_taskId, Output::getStdout(), Output::getStderr(), $exit); - } - - - } catch(\cli\Exception $e) { - $exit = 3; - $this->handleException($e, $this->_taskId, $exit); - - } catch(\Phalcon\Exception $e) { - $exit = 2; - $this->handleException($e, $this->_taskId, $exit); - - } catch(\Exception $e) { - $exit = 1; - $this->handleException($e, $this->_taskId, $exit); - } - - return $exit; - } - - - /** - * Check if pid file needs to be created - * - * @param array $argv cli arguments - */ - public function checkProcessInstance($argv) { - - // Single Instance - if ($this->isSingleInstance()) { - - $file = sprintf('%s-%s.pid', $this->_task, $this->_action); - $pid = \Cli\Pid::singleton($file); - - // Default - $this->_pidFile = $file; - - // Make sure only 1 app at a time is running - if ($pid->exists()) { - throw new \Exception('Instance of task is already running', self::ERROR_SINGLE); - } else { - // Create PID File - /* - $fp = fopen($this->_pidFile, 'r+'); - if (!flock($fp, LOCK_EX | LOCK_NB)) { - fclose($fp); - throw new \exceptions\System('unable to create pid file', $desc); - }*/ - - if ($pid->create()) { - if ($this->isDebug()) { - Output::stdout("[DEBUG] Created Pid File: " . $pid->getFileName()); - } - } else { - $desc = ''; - throw new \exceptions\System('unable to create pid file', $desc); - } - - /*if (!file_put_contents($this->_pidFile, getmypid())) { - $desc = ''; - throw new \exceptions\System('unable to create pid file', $desc); - }*/ - - } - } - } - - /** - * Remove Pid File - * - * @return bool - */ - public function removeProcessInstance() { - if ($this->isSingleInstance()) { - $pid = \Cli\Pid::singleton(''); - if ($pid->created() && !$pid->removed()) { - if ($result = $pid->remove()) { - if ($this->isDebug()) { - Output::stdout("[DEBUG] Removed Pid File: " . $pid->getFileName()); - } - } else { - $msg = Output::COLOR_RED . "[ERROR]" . Output::COLOR_NONE . " Failed to remove Pid File: $this->_pidFile"; - Output::stderr($msg); - } - return $result; - } - } - - return TRUE; - } - - /** - * Get the task/action to direct to - * - * @param array $flags cli arguments to determine tasks/action/param - * @throws Exception - */ - protected function determineTask($flags) { - - // Since first argument is the name so script executing (pop it off the list) - array_shift($flags); - - if (is_array($flags) && !empty($flags)) { - foreach($flags as $flag) { - if (empty($this->_task) && !$this->isFlag($flag)) { - $this->_task = $flag; - } else if (empty($this->_action) && !$this->isFlag($flag)) { - $this->_action = $flag; - } else if (!$this->isFlag($flag)) { - $this->_params[] = $flag; - } - } - } else { - throw new Exception('Unable to determine task/action/params'); - } - } - - /** - * set mode of multiple or single instance at a time - * - * @param int $mode - */ - public function setMode($mode) { - $this->_mode = $mode; - } - - /** - * set the directory location of the pid file - * - * @param $dir string - */ - public function setPidDir($dir) { - $this->_pidDir = $dir; - } - - - /** - * make sure everything required is setup before starting the task - * - * @param array $argv array of arguments - * @param int $argc count of arguments - * @throws Exception - */ - protected function preTaskCheck($argc) { - - // Make sure task is added - if ($argc < 2) { - throw new \Exception('Bad Number of Params needed for script'); - } - } - - /** - * sets debug mode - * - * @param bool $debug - */ - public function setDebug($debug) { - $this->_isDebug = $debug; - if ($debug) { - error_reporting(E_ALL); - ini_set('display_errors', 1); - } - } - - public function isDebug() { - return $this->_isDebug; - } - - /** - * Set Application to record results to database - * - * @param bool - */ - public function setRecording($record) { - $this->_isRecording = $record; - } - - /** - * Determine if application is recording output (stdout and stderr) to database - * - * @return bool - */ - public function isRecording() { - return $this->_isRecording; - } - - /** - * Set Single Instance Flag - * - * @param bool - */ - public function setSingleInstance($single) { - $this->_isSingleInstance = $single; - } - - /** - * determine if only a single instance is allowed to run - * - * @return bool - */ - public function isSingleInstance() { - return $this->_isSingleInstance; - } - - - /** - * handle script ending exception - * - * @param Exception that caused the failure - * @param id of the task you started - * @param exit code status of the process - */ - protected function handleException(\Exception $e, $taskId, $exit) { - - $sub = '%s[ERROR]%s %s file: %s line: %d'; - - // Remove Process Instance - if ($e->getCode() != self::ERROR_SINGLE) { - $this->removeProcessInstance(); - } - - // Update Failure - if ($this->_isRecording && $taskId > 0) { - $stdout = Output::getStdout(); - $stderr = Output::getStderr(); - // Update Task w/ error messages - $task = new \Models\Task(); - $task->updateFailed($taskId, $stdout, $stderr, $exit); - } - - $msg = sprintf($sub, Output::COLOR_RED, Output::COLOR_NONE, $e->getMessage(), $e->getFile(), $e->getLine()); - - // Let user that ran this know it failed - Output::stderr($msg); - } - - /** - * Determine if argument is a special flag - * - * @param string - * @return bool - */ - protected function isFlag($flag) { - return substr(trim($flag), 2) == '--'; - } - - /** - * Get the PID File location - * @return string - */ - public function getPidFile() { - return $this->_pidFile; - } - - /** - * Get the auto incremented value for current task - * @return int|NULL - */ - public function getTaskId() { - return $this->_taskId; - } + $msg = sprintf($sub, Output::COLOR_RED, Output::COLOR_NONE, $e->getMessage(), $e->getFile(), $e->getLine()); + + // Let user that ran this know it failed + Output::stderr($msg); + } + + /** + * Determine if argument is a special flag + * + * @param string + * @return bool + */ + protected function isFlag($flag) + { + return substr(trim($flag), 2) == '--'; + } + + /** + * Get the PID File location + * @return string + */ + public function getPidFile() + { + return $this->_pidFile; + } + + /** + * Get the auto incremented value for current task + * @return int|NULL + */ + public function getTaskId() + { + return $this->_taskId; + } } diff --git a/app/library/cli/Command.php b/app/library/cli/Command.php index 1967698..9b765a3 100644 --- a/app/library/cli/Command.php +++ b/app/library/cli/Command.php @@ -5,62 +5,64 @@ * * a containter class that holds all attributes that make up a command * - * @author Jete O'Keeffe + * @author Jete O'Keeffe * @version 1.0 * @package cli */ namespace Cli; -class Command { +class Command +{ - /** - * @var string command executed - */ - public $command; + /** + * @var string command executed + */ + public $command; - /** - * @var string file that executed command - */ - public $file; + /** + * @var string file that executed command + */ + public $file; - /** - * @var int on which line was command executed - */ - public $line; + /** + * @var int on which line was command executed + */ + public $line; - /** - * @var bool was command successful - */ - public $success; + /** + * @var bool was command successful + */ + public $success; - /** - * @var string standard output from command - */ - public $stdout; + /** + * @var string standard output from command + */ + public $stdout; - /** - * @var string error output from command - */ - public $stderr; + /** + * @var string error output from command + */ + public $stderr; - /** - * @var string time taken for command to execute - */ - public $time; + /** + * @var string time taken for command to execute + */ + public $time; - /** - * @var int command status/return result - */ - public $result_code; + /** + * @var int command status/return result + */ + public $result_code; - /** - * echo out command to table row display - */ - public function toRow() { - echo "
" . print_r($this->_command, TRUE) . ""; - } + $command = new \Cli\Command; + $command->command = $cmd; + $command->file = $file; + $command->line = $line; + $command->result_code = $return; + $command->success = $return == 0 ? true : false; + $command->stdout = $stdout; + $command->stderr = $stderr; + $command->time = ($end - $start); + + $this->_command[] = $command; + + return $return == 0 ? true : $return; + } + + + /** + * Get all commands executed + * + * @return array of executed commands + */ + public function getCommands() + { + return $this->_command; + } + + + /** + * Output the object + */ + public function __toString() + { + if (PHP_SAPI == 'cli') + return print_r($this->_command, true); + else + return "
" . print_r($this->_command, true) . ""; + } } diff --git a/app/library/cli/Output.php b/app/library/cli/Output.php index bbfe9c8..56ff1a9 100644 --- a/app/library/cli/Output.php +++ b/app/library/cli/Output.php @@ -3,105 +3,111 @@ /** * Send Standard Output and Standard Error in CLI * - * @author Jete O'Keeffe + * @author Jete O'Keeffe * @version 1.0 * @package cli */ namespace Cli; -class Output { - - /** - * Bash shell code for red - * @const COLOR_RED - */ - const COLOR_RED = "\e[0;31m"; - - /** - * Bash shell code for yellow - * @const COLOR_YELLOW - */ - const COLOR_YELLOW = "\e[1;33m"; - - /** - * Bash shell code for green - * @const COLOR_GREEN - */ - const COLOR_GREEN = "\e[0;32m"; - - /** - * Bash shell code for blue - * @const COLOR_BLUE - */ - const COLOR_BLUE = "\e[0;34m"; - - /** - * Bash shell code for no color - * @const COLOR_NONE original shell color - */ - const COLOR_NONE = "\e[0m"; - - - /** - * @var string output sent to standard error - */ - protected static $_stderr; - - /** - * @var string output sent to standard output - */ - protected static $_stdout; - - - /** - * output to standard error - * - * @param $msg string - */ - public static function stderr($msg) { - fwrite(STDERR, $msg . PHP_EOL); - self::$_stderr .= $msg . PHP_EOL; - } - - - /** - * output to standard output - * - * @param $msg string - */ - public static function stdout($msg) { - fwrite(STDOUT, $msg . PHP_EOL); - self::$_stdout .= $msg . PHP_EOL; - } - - - /** - * get all standard output text - * - * @return string - */ - public static function getStdout() { - return self::$_stdout; - } - - - /** - * get all standard error text - * - * @return string - */ - public static function getStderr() { - return self::$_stderr; - } +class Output +{ + + /** + * Bash shell code for red + * @const COLOR_RED + */ + const COLOR_RED = "\e[0;31m"; + + /** + * Bash shell code for yellow + * @const COLOR_YELLOW + */ + const COLOR_YELLOW = "\e[1;33m"; + + /** + * Bash shell code for green + * @const COLOR_GREEN + */ + const COLOR_GREEN = "\e[0;32m"; + + /** + * Bash shell code for blue + * @const COLOR_BLUE + */ + const COLOR_BLUE = "\e[0;34m"; + + /** + * Bash shell code for no color + * @const COLOR_NONE original shell color + */ + const COLOR_NONE = "\e[0m"; + + + /** + * @var string output sent to standard error + */ + protected static $_stderr; + + /** + * @var string output sent to standard output + */ + protected static $_stdout; + + + /** + * output to standard error + * + * @param $msg string + */ + public static function stderr($msg) + { + fwrite(STDERR, $msg . PHP_EOL); + self::$_stderr .= $msg . PHP_EOL; + } + + + /** + * output to standard output + * + * @param $msg string + */ + public static function stdout($msg) + { + fwrite(STDOUT, $msg . PHP_EOL); + self::$_stdout .= $msg . PHP_EOL; + } + + + /** + * get all standard output text + * + * @return string + */ + public static function getStdout() + { + return self::$_stdout; + } + + + /** + * get all standard error text + * + * @return string + */ + public static function getStderr() + { + return self::$_stderr; + } /** * Clear Output */ - public static function clear() { - unset(self::$_stderr); - self::$_stderr = ''; - unset(self::$_stdout); - self::$_stdout = ''; + public static function clear() + { + unset(self::$_stderr); + self::$_stderr = ''; + unset(self::$_stdout); + self::$_stdout = ''; } } diff --git a/app/library/cli/Pid.php b/app/library/cli/Pid.php index 84a092a..f90a714 100644 --- a/app/library/cli/Pid.php +++ b/app/library/cli/Pid.php @@ -4,125 +4,143 @@ * Handling of the ProcessID(Pid) file's creation, removal and existance * * @package Cli - * @author Jete O'Keeffe + * @author Jete O'Keeffe */ namespace Cli; -class Pid { - - /** - * - */ - protected $_isCreated; - - /** - * - */ - protected $_isRemoved; - - /** - * - */ - protected static $_instance; - - /** - * File pointer - */ - protected $_fp; - - /** - * - */ - protected function __construct($file) { - $this->_pidFile = $file; - $this->_isCreated = FALSE; - $this->_isRemoved = FALSE; - $this->_fp = NULL; - } - - /** - * Get instance - * - * @param string file name of the pid file - * @param string directory of the pid file - */ - public static function singleton($file, $dir = '/tmp') { - if (empty(self::$_instance)) { - self::$_instance = new Pid($dir . '/' . $file); - } - return self::$_instance; - } - - - /** - * Remove the ProcessID file - */ - public function remove() { - if ($this->_isCreated) { - // close handle to file and remove it - fclose($this->_fp); - if ($result = unlink($this->_pidFile)) { - return $this->_isRemoved = TRUE; - } else { - return FALSE; - } - } - } - - - /** - * Create the ProcessID file - */ - public function create() { - if ($this->exists()) { - throw new Exception('Pid File exists/Instance of script is already running'); - } - - if (is_writable($this->_pidFile)) { - throw new Exception('Unable to write to this file'); - } - - if ($this->_fp = fopen($this->_pidFile, "x")) { - if (!flock($this->_fp, LOCK_EX | LOCK_NB)) { - fclose($this->_fp); - return FALSE; - } - } else { - return FALSE; - } - - $this->_isCreated = TRUE; - return TRUE; - } - - /** - * Check if the PID file exists - */ - public function exists() { - return file_exists($this->_pidFile); - } - - /** - * Check if Pid has been created - */ - public function created() { - return $this->_isCreated; - } - - /** - * Check if Pid file has been deleted - */ - public function removed() { - return $this->_isRemoved; - } - - /** - * Get the file name (location) of the pid file - * - * @param string - */ - public function getFileName() { - return $this->_pidFile; - } +class Pid +{ + + /** + * @var bool + */ + protected $_isCreated; + + /** + * @var bool + */ + protected $_isRemoved; + + /** + * @var self + */ + protected static $_instance; + + /** + * File pointer + * @var resource + */ + protected $_fp; + + /** + * + */ + protected function __construct($file) + { + $this->_pidFile = $file; + $this->_isCreated = false; + $this->_isRemoved = false; + $this->_fp = null; + } + + /** + * Get instance + * + * @param string $file name of the pid file + * @param string $dir of the pid file + * @return Pid instance + */ + public static function singleton($file, $dir = '/tmp') + { + if (empty(self::$_instance)) { + self::$_instance = new Pid($dir . '/' . $file); + } + + return self::$_instance; + } + + + /** + * Remove the ProcessID file + * @return bool + */ + public function remove() + { + if ($this->_isCreated) { + // close handle to file and remove it + fclose($this->_fp); + if ($result = unlink($this->_pidFile)) { + return $this->_isRemoved = true; + } + } + + return false; + } + + + /** + * Create the ProcessID file + * @throws \Exception + */ + public function create() + { + if ($this->exists()) { + throw new \Exception('Pid File exists/Instance of script is already running'); + } + + if (is_writable($this->_pidFile)) { + throw new \Exception('Unable to write to this file'); + } + if (file_exists($this->_pidFile) && $this->_fp = fopen($this->_pidFile, "x")) { + if (!flock($this->_fp, LOCK_EX | LOCK_NB)) { + fclose($this->_fp); + + return false; + } + } else { + return false; + } + + $this->_isCreated = true; + + return true; + } + + /** + * Check if the PID file exists + * @return bool + */ + public function exists() + { + return file_exists($this->_pidFile); + } + + /** + * Check if Pid has been created + * @return bool + */ + public function created() + { + return $this->_isCreated; + } + + /** + * Check if Pid file has been deleted + * @return bool + */ + public function removed() + { + return $this->_isRemoved; + } + + /** + * Get the file name (location) of the pid file + * + * @param string + */ + public function getFileName() + { + return $this->_pidFile; + } } diff --git a/app/library/events/cli/Debug.php b/app/library/events/cli/Debug.php index 634fcda..4cb4b5a 100644 --- a/app/library/events/cli/Debug.php +++ b/app/library/events/cli/Debug.php @@ -2,11 +2,11 @@ /** * Event that displays debug output at the end of the application - * - * @package Cli + * + * @package Cli * @subpackage Events - * @author Jete O'Keeffe - * @version 1.0 + * @author Jete O'Keeffe + * @version 1.0 */ namespace Events\Cli; @@ -15,121 +15,128 @@ use \Cli\Execute as Execute; use \Interfaces\IEvent as IEvent; -class Debug extends \Phalcon\Events\Manager implements IEvent { - - /** - * Constructor - */ - public function __construct($enable = TRUE) { - if ($enable === TRUE) { - $this->handleEvent(); - } - } - - - /** - * Setup an event to trigger after running task - */ - public function handleEvent() { - $this->attach('console:afterHandleTask', function ($event, $console) { - $this->display($console); - }); - } - - - /** - * - */ - public function display($console) { - - $dispatcher = $console->getDI()->getShared('dispatcher'); - - $taskName = $dispatcher->getTaskName(); - $actionName = $dispatcher->getActionName(); - - if (!class_exists('\\Cli\Output')) { - fwrite(STDERR, "Unable to find Output class" . PHP_EOL); - return; - } - - // Get Memory Usage - $curMem = memory_get_usage(FALSE); - $curRealMem = memory_get_usage(TRUE); - $peakMem = memory_get_peak_usage(FALSE); - $peakRealMem = memory_get_peak_usage(TRUE); - // Get Time - $totalTime = microtime(TRUE) - $_SERVER['REQUEST_TIME']; - $startTime = date('m/d/y h:i:s', $_SERVER['REQUEST_TIME']); - - Output::stdout(""); - Output::stdout(Output::COLOR_BLUE . "--------------DEBUG ENABLED---------------------" . Output::COLOR_NONE); - Output::stdout(Output::COLOR_BLUE . "+++Overview+++" . Output::COLOR_NONE); - Output::stdout("task: $taskName"); - Output::stdout("action: $actionName"); - Output::stdout("total time: $totalTime start time: $startTime end time: " . date('m/d/y h:i:s')); - if ($console->isRecording()) { - Output::stdout("task id: " . $console->getTaskId()); - } - Output::stdout("hostname: " . php_uname('n')); - Output::stdout("pid: " . getmypid()); - - if ($console->isSingleInstance()) { - Output::stdout("pid file: " . \Cli\Pid::singleton('')->getFileName() ); - } - - Output::stdout(""); - Output::stdout("current memory: $curMem bytes " . round($curMem/1024, 2) . " kbytes" ); - Output::stdout("current real memory: $curRealMem bytes " . round($curRealMem/1024, 2) . " kbytes"); - Output::stdout("peak memory: $peakMem bytes " . round($peakMem/1024, 2) . " kbytes"); - Output::stdout("peak real memory: $peakRealMem bytes " . round($peakRealMem/1024, 2) . " kbytes"); - Output::stdout(""); - - // Print out Commands - $commands = Execute::singleton()->getCommands(); - if (!empty($commands)) { - Output::stdout(Output::COLOR_BLUE . "+++Cli Commands+++" . Output::COLOR_NONE); - foreach($commands as $command) { - Output::stdout($command->command); - Output::stdout($command->file . "\t" . $command->line . "\t" . ($command->success ? - Output::COLOR_GREEN . "Success" . Output::COLOR_NONE : - Output::COLOR_RED . "Failed" . Output::COLOR_NONE)); - Output::stdout(""); - } - Output::stdout(""); - } - - // Print out Queries - if ($console->getDI()->has('profiler')) { - Output::stdout(Output::COLOR_BLUE . "+++Queries+++" . Output::COLOR_NONE); - $profiles = $console->getDI()->getShared('profiler')->getProfiles(); - if (!empty($profiles)) { - foreach ($profiles as $profile) { - Output::stdout($profile->getSQLStatement()); - Output::stdout("time: " . $profile->getTotalElapsedSeconds()); - Output::stdout(""); - } - Output::stdout(""); - } - } - - // Print out Exceptions - /*$exceptions = Logger::getInstance()->getAll(); - if (!empty($exceptions)) { - Output::stdout(Output::COLOR_BLUE . "+++Exceptions+++" . Output::COLOR_NONE); - foreach($exceptions as $except) { - Output::stdout($except->getMessage()); - Output::stdout($except->getCode() . "\t" . $except->getFile() . "\t" . $except->getLine()); - Output::stdout(""); - } - Output::stdout(""); - }*/ - - // Print out all included php files - $files = get_required_files(); - Output::stdout(Output::COLOR_BLUE . "+++Included Files+++" . Output::COLOR_NONE); - foreach($files as $file) { - Output::stdout($file); - } - Output::stdout(""); - } +class Debug extends \Phalcon\Events\Manager implements IEvent +{ + + /** + * Constructor + * @param bool $enable enable event to trigger after task? + */ + public function __construct($enable = true) + { + if ($enable === true) { + $this->handleEvent(); + } + } + + + /** + * Setup an event to trigger after running task + */ + public function handleEvent() + { + $this->attach('console:afterHandleTask', function ($event, $console) { + $this->display($console); + }); + } + + + /** + * Display current job to console when job was finished + * @param object $console + */ + public function display($console) + { + + $dispatcher = $console->getDI()->getShared('dispatcher'); + + $taskName = $dispatcher->getTaskName(); + $actionName = $dispatcher->getActionName(); + + if (!class_exists('\\Cli\Output')) { + fwrite(STDERR, "Unable to find Output class" . PHP_EOL); + + return; + } + + // Get Memory Usage + $curMem = memory_get_usage(false); + $curRealMem = memory_get_usage(true); + $peakMem = memory_get_peak_usage(false); + $peakRealMem = memory_get_peak_usage(true); + // Get Time + $totalTime = microtime(true) - $_SERVER['REQUEST_TIME']; + $startTime = date('m/d/y h:i:s', $_SERVER['REQUEST_TIME']); + + Output::stdout(""); + Output::stdout(Output::COLOR_BLUE . "--------------DEBUG ENABLED---------------------" . Output::COLOR_NONE); + Output::stdout(Output::COLOR_BLUE . "+++Overview+++" . Output::COLOR_NONE); + Output::stdout("task: $taskName"); + Output::stdout("action: $actionName"); + Output::stdout("total time: $totalTime start time: $startTime end time: " . date('m/d/y h:i:s')); + if ($console->isRecording()) { + Output::stdout("task id: " . $console->getTaskId()); + } + Output::stdout("hostname: " . php_uname('n')); + Output::stdout("pid: " . getmypid()); + + if ($console->isSingleInstance()) { + Output::stdout("pid file: " . \Cli\Pid::singleton('')->getFileName()); + } + + Output::stdout(""); + Output::stdout("current memory: $curMem bytes " . round($curMem / 1024, 2) . " kbytes"); + Output::stdout("current real memory: $curRealMem bytes " . round($curRealMem / 1024, 2) . " kbytes"); + Output::stdout("peak memory: $peakMem bytes " . round($peakMem / 1024, 2) . " kbytes"); + Output::stdout("peak real memory: $peakRealMem bytes " . round($peakRealMem / 1024, 2) . " kbytes"); + Output::stdout(""); + + // Print out Commands + $commands = Execute::singleton()->getCommands(); + if (!empty($commands)) { + Output::stdout(Output::COLOR_BLUE . "+++Cli Commands+++" . Output::COLOR_NONE); + foreach ($commands as $command) { + Output::stdout($command->command); + Output::stdout($command->file . "\t" . $command->line . "\t" . ($command->success ? + Output::COLOR_GREEN . "Success" . Output::COLOR_NONE : + Output::COLOR_RED . "Failed" . Output::COLOR_NONE)); + Output::stdout(""); + } + Output::stdout(""); + } + + // Print out Queries + if ($console->getDI()->has('profiler')) { + Output::stdout(Output::COLOR_BLUE . "+++Queries+++" . Output::COLOR_NONE); + $profiles = $console->getDI()->getShared('profiler')->getProfiles(); + if (!empty($profiles)) { + foreach ($profiles as $profile) { + Output::stdout($profile->getSQLStatement()); + Output::stdout("time: " . $profile->getTotalElapsedSeconds()); + Output::stdout(""); + } + Output::stdout(""); + } + } + + // Print out Exceptions + /*$exceptions = Logger::getInstance()->getAll(); + if (!empty($exceptions)) { + Output::stdout(Output::COLOR_BLUE . "+++Exceptions+++" . Output::COLOR_NONE); + foreach($exceptions as $except) { + Output::stdout($except->getMessage()); + Output::stdout($except->getCode() . "\t" . $except->getFile() . "\t" . $except->getLine()); + Output::stdout(""); + } + Output::stdout(""); + }*/ + + // Print out all included php files + $files = get_required_files(); + Output::stdout(Output::COLOR_BLUE . "+++Included Files+++" . Output::COLOR_NONE); + foreach ($files as $file) { + Output::stdout($file); + } + Output::stdout(""); + } } diff --git a/app/library/events/database/Profile.php b/app/library/events/database/Profile.php index b9fca8c..5bd9975 100644 --- a/app/library/events/database/Profile.php +++ b/app/library/events/database/Profile.php @@ -3,7 +3,7 @@ /** * Event to trigger profiling SQL statements * - * @author Jete O'Keeffe + * @author Jete O'Keeffe * @version 1.0 */ @@ -11,36 +11,39 @@ use \Interfaces\IEvent as IEvent; -class Profile extends \Phalcon\Events\Manager implements IEvent { - - /** - * Constructor - */ - public function __construct() { - $this->handleEvent(); - } - - /** - * Create the Event - */ - public function handleEvent() { - - $di = \Phalcon\DI::getDefault(); - $di->set('profiler', function() { - return new \Phalcon\Db\Profiler(); - }, TRUE); - $profiler = $di->get('profiler'); - - - $this->attach('db', function($event, $connection) use ($profiler) { - if ($event->getType() == 'beforeQuery') { - $profiler->startProfile($connection->getSQLStatement()); - } - - - if ($event->getType() == 'afterQuery') { - $profiler->stopProfile(); - } - }); - } +class Profile extends \Phalcon\Events\Manager implements IEvent +{ + + /** + * Constructor + */ + public function __construct() + { + $this->handleEvent(); + } + + /** + * Create the Event + */ + public function handleEvent() + { + + $di = \Phalcon\DI::getDefault(); + $di->set('profiler', function () { + return new \Phalcon\Db\Profiler(); + }, true); + $profiler = $di->get('profiler'); + + + $this->attach('db', function ($event, $connection) use ($profiler) { + if ($event->getType() == 'beforeQuery') { + $profiler->startProfile($connection->getSQLStatement()); + } + + + if ($event->getType() == 'afterQuery') { + $profiler->stopProfile(); + } + }); + } } diff --git a/app/library/interfaces/IEvent.php b/app/library/interfaces/IEvent.php index 882ddcf..64fd33a 100644 --- a/app/library/interfaces/IEvent.php +++ b/app/library/interfaces/IEvent.php @@ -1,17 +1,18 @@ title = $errStr; - $rt->file = $errFile; - $rt->line = $errLine; - $rt->error_type = $errNo; - $rt->server_name = php_uname('n'); - $rt->execution_script = $script; - $rt->pid = getmypid(); - $rt->ip_address = $ip; - $rt->save(); - } + // Get Remote Ip or CLI script? + if (PHP_SAPI == 'cli') { + $script = $_SERVER['PHP_SELF']; + $ip = 'CLI'; + } else { + $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://'; + $script = $protocol . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; + $ip = $_SERVER['REMOTE_ADDR']; + } - return FALSE; - } + $rt = new RuntimeError(); + $rt->title = $errStr; + $rt->file = $errFile; + $rt->line = $errLine; + $rt->error_type = $errNo; + $rt->server_name = php_uname('n'); + $rt->execution_script = $script; + $rt->pid = getmypid(); + $rt->ip_address = $ip; + $rt->save(); + } - /** - * Capture any errors at the end script (especially runtime errors) - */ - public static function runtimeShutdown() { - $e = error_get_last(); - if (!empty($e)) { - // Record Error - PhpError::errorHandler($e['type'], $e['message'], $e['file'], $e['line']); - } - } + return false; + } + + /** + * Capture any errors at the end script (especially runtime errors) + */ + public static function runtimeShutdown() + { + $e = error_get_last(); + if (!empty($e)) { + // Record Error + PhpError::errorHandler($e['type'], $e['message'], $e['file'], $e['line']); + } + } } diff --git a/app/models/RuntimeError.php b/app/models/RuntimeError.php index e9bdbbc..7d3bbfa 100644 --- a/app/models/RuntimeError.php +++ b/app/models/RuntimeError.php @@ -2,9 +2,11 @@ namespace Models; -class RuntimeError extends \Phalcon\Mvc\Model { +class RuntimeError extends \Phalcon\Mvc\Model +{ - public function initialize() { - $this->setSource("runtimeError"); - } + public function initialize() + { + $this->setSource("runtimeError"); + } } diff --git a/app/models/Task.php b/app/models/Task.php index 87cb356..6a23e88 100644 --- a/app/models/Task.php +++ b/app/models/Task.php @@ -2,69 +2,75 @@ namespace Models; -class Task extends \Phalcon\Mvc\Model { +class Task extends \Phalcon\Mvc\Model +{ - public function initialize() { - $this->setSource("task"); - } + public function initialize() + { + $this->setSource("task"); + } - /** - * @param - * @return FALSE|int - */ - public function insertTask($scriptName) { + /** + * @param string $scriptName $_SERVER['PHP_SELF'] name + * @return FALSE|int + */ + public function insertTask($scriptName) + { - $this->script_name = $_SERVER['_'] . ' ' . $scriptName; - $this->params = implode(' ', $_SERVER['argv']); - $this->server_name = php_uname('n'); - $this->server_user = get_current_user(); - $this->start_time = date('Y-m-d H:i:s'); - $this->pid = getmypid(); + $this->script_name = PHP_BINARY . ' ' . $scriptName; + $this->params = implode(' ', $_SERVER['argv']); + $this->server_name = php_uname('n'); + $this->server_user = get_current_user(); + $this->start_time = date('Y-m-d H:i:s'); + $this->pid = getmypid(); - if ($this->save()) { - return $this->task_id; - } + if ($this->save()) { + return $this->task_id; + } - return FALSE; - } + return false; + } - /** - * @param - * @param - * @param - * @param - * @return bool - */ - public function updateFailed($taskId, $stdout, $stderr, $status) { - $state = $status === 0 ? 'SUCCESSFUL' : 'FAILED'; + /** + * @param int $taskId id of the task you started + * @param string $stdout + * @param string $stderr + * @param int $status exit status code + * @return bool + */ + public function updateFailed($taskId, $stdout, $stderr, $status) + { + $state = $status === 0 ? 'SUCCESSFUL' : 'FAILED'; - $this->task_id = $taskId; - $this->exit_status = $status; - $this->state = $state; - $this->stdout = $stdout; - $this->stderr = $stderr; - $this->stop_time = date('Y-m-d H:i:s'); + $this->task_id = $taskId; + $this->exit_status = $status; + $this->state = $state; + $this->stdout = $stdout; + $this->stderr = $stderr; + $this->stop_time = date('Y-m-d H:i:s'); - return $this->update(); - } + return $this->update(); + } - /** - * @param - * @param - * @param - * @param - * @return - */ - public function updateSuccessful($taskId, $stdout, $stderr, $status) { - $state = $status == 0 ? 'SUCCESSFUL' : 'FAILED'; + /** + * @param int $taskId id of the task you started + * @param string $stdout + * @param string $stderr + * @param int $status exit status code + * @return bool + */ + public function updateSuccessful($taskId, $stdout, $stderr, $status) + { + $state = $status == 0 ? 'SUCCESSFUL' : 'FAILED'; - $this->exit_status = $status; - $this->state = $state; - $this->stdout = $stdout; - $this->stderr = $stderr; - $this->stop_time = date('Y-m-d H:i:s'); + $this->taskId = $taskId; + $this->exit_status = $status; + $this->state = $state; + $this->stdout = $stdout; + $this->stderr = $stderr; + $this->stop_time = date('Y-m-d H:i:s'); - return $this->update(); - } + return $this->update(); + } } diff --git a/app/tasks/ExampleTask.php b/app/tasks/ExampleTask.php index a6124ff..7d46740 100644 --- a/app/tasks/ExampleTask.php +++ b/app/tasks/ExampleTask.php @@ -2,8 +2,8 @@ /** * Example of a Task/Cli application - * - * @author Jete O'Keeffe + * + * @author Jete O'Keeffe * @version 1.0 */ @@ -12,37 +12,44 @@ use \Cli\Output as Output; -class ExampleTask extends \Phalcon\Cli\Task { +class ExampleTask extends \Phalcon\Cli\Task +{ - public function test1Action() { - Output::stdout("Hello World!"); - } + public function test1Action() + { + Output::stdout("Hello World!"); + } - public function mainAction() { - Output::stdout("Main Action"); - } + public function mainAction() + { + Output::stdout("Main Action"); + } - public function cmdAction() { - $cmd = \Cli\Execute::singleton(); - $success = $cmd->execute("whoami", __FILE__, __LINE__, $output); + public function cmdAction() + { + $cmd = \Cli\Execute::singleton(); + $output = ''; + $success = $cmd->execute("whoami", __FILE__, __LINE__, $output); - Output::stdout("You're running this script under $output user"); - } + Output::stdout("You're running this script under $output user"); + } - public function test2Action($paramArray) { - Output::stdout("First param: $paramArray[0]"); - Output::stdout("Second param: $paramArray[1]"); - } + public function test2Action($paramArray) + { + Output::stdout("First param: $paramArray[0]"); + Output::stdout("Second param: $paramArray[1]"); + } - /** - * Action to trigger a fatal error - */ - public function fatalAction() { - // trigger a fatal error w/ Class that doesn't exist - //new TriggerARuntimeFatal(); - strpos(); - } + /** + * Action to trigger a fatal error + */ + public function fatalAction() + { + // trigger a fatal error w/ Class that doesn't exist + //new TriggerARuntimeFatal(); + strpos(); + } } diff --git a/mysql.data.sql b/mysql.data.sql index 568c89e..e3b1b9b 100644 --- a/mysql.data.sql +++ b/mysql.data.sql @@ -11,7 +11,7 @@ CREATE TABLE `runtimeError` ( `ip_address` varchar(16) DEFAULT NULL, `user_id` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`error_id`) -) ENGINE=InnoDB DEFAULT CHARSET=latin1; +) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `queryError` ( @@ -27,7 +27,7 @@ CREATE TABLE `queryError` ( `ip_address` varchar(16) DEFAULT NULL, `user_id` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`error_id`) -) ENGINE=InnoDB DEFAULT CHARSET=latin1; +) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `task` ( `task_id` int(10) unsigned NOT NULL AUTO_INCREMENT, @@ -43,4 +43,4 @@ CREATE TABLE `task` ( `stderr` text, `pid` int(10) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`task_id`) -) ENGINE=InnoDB DEFAULT CHARSET=latin1; +) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/private/cli.php b/private/cli.php index 390dfcf..1eaa062 100755 --- a/private/cli.php +++ b/private/cli.php @@ -5,19 +5,19 @@ * * a cli script that launches phalcon tasks * - * @package cli - * @author Jete O'Keeffe - * @version 1.0 + * @package cli + * @author Jete O'Keeffe + * @version 1.0 * @copyright never * - * @example php cli.php [task] [action] [param1 [param2 ...]] - * @example php cli.php Example index - * @example php cli.php Example index --debug --single --no-record + * @example php cli.php [task] [action] [param1 [param2 ...]] + * @example php cli.php Example index + * @example php cli.php Example index --debug --single --no-record */ // Setup configuration directories -$dir = dirname(__DIR__); +$dir = dirname(__DIR__); $appDir = $dir . '/app'; // Necessary requires to get things going @@ -26,50 +26,50 @@ require $appDir . '/library/application/Cli.php'; // Capture runtime errors -register_shutdown_function(['Utilities\Debug\PhpError','runtimeShutdown']); +register_shutdown_function(['Utilities\Debug\PhpError', 'runtimeShutdown']); // Necessary paths to autoload & config files $configPath = $appDir . '/config/'; -$config = $configPath . 'config.php'; -$autoLoad = $configPath . 'autoload.php'; +$config = $configPath . 'config.php'; +$autoLoad = $configPath . 'autoload.php'; try { - $app = new Application\Cli(); + $app = new Application\Cli(); - // Record any php warnings/errors - set_error_handler(['Utilities\Debug\PhpError','errorHandler']); + // Record any php warnings/errors + set_error_handler(['Utilities\Debug\PhpError', 'errorHandler']); - $app->setAutoload($autoLoad, $appDir); - $app->setConfig($config); + $app->setAutoload($autoLoad, $appDir); + $di = $app->getDefaultDI(); + $app->setConfig($config, $di); + $app->setDI($di); - // Check if only run single instance - if ($key = array_search('--single', $argv)) { - $app->setSingleInstance(TRUE); - // Ensure pid removes even on fatal error - register_shutdown_function([$app, 'removeProcessInstance']); - } + // Check if only run single instance + if ($key = array_search('--single', $argv)) { + $app->setSingleInstance(true); + // Ensure pid removes even on fatal error + register_shutdown_function([$app, 'removeProcessInstance']); + } - // Check if logging to database - if ($key = array_search('--record', $argv)) { - $app->setRecording(TRUE); - } + // Check if logging to database + if ($key = array_search('--record', $argv)) { + $app->setRecording(true); + } - // Check if debug mode - if ($key = array_search('--debug', $argv)) { - $app->setDebug(TRUE); - // Ensure debug display even on fatal error - register_shutdown_function([new Events\Cli\Debug(FALSE), 'display'], $app); - } + // Check if debug mode + if ($key = array_search('--debug', $argv)) { + $app->setDebug(true); + // Ensure debug display even on fatal error + register_shutdown_function([new Events\Cli\Debug(false), 'display'], $app); + } - $app->setArgs($argv, $argc); + $app->setArgs($argv, $argc); - // Boom, Run - $app->run(); + // Boom, Run + $app->run(); -} catch(Exception $e) { - echo $e; - exit(255); +} catch (Exception $e) { + echo $e; + exit(255); } - -?> diff --git a/test/library/cli/ExecuteTest.php b/test/library/cli/ExecuteTest.php index 86490b2..92bf401 100755 --- a/test/library/cli/ExecuteTest.php +++ b/test/library/cli/ExecuteTest.php @@ -7,41 +7,50 @@ */ class ExecuteTest extends \PHPUnit_Framework_TestCase { - protected $_cmd; - protected $_input; - - public function setUp(){ - $this->_cmd = \Cli\Execute::singleton(); - $line[] = '_input = implode(PHP_EOL, $line); - } - - public function testExecuteSimple(){ + protected $_cmd; + protected $_input; + + public function setUp() + { + $this->_cmd = \Cli\Execute::singleton(); + $line[] = '_input = implode(PHP_EOL, $line); + } + + public function testExecuteSimple() + { + $output = null; + $err = null; $success = $this->_cmd->execute('echo "123"', __FILE__, __LINE__, $output); $this->assertTrue($success); - $this->assertEquals(trim($output),'123'); + $this->assertEquals(trim($output), '123'); - $success = $this->_cmd->execute('cd wrongDirsTest123', __FILE__, __LINE__, $output,$err); - $this->assertInternalType('int',$success); - } + $success = $this->_cmd->execute('cd wrongDirsTest123', __FILE__, __LINE__, $output, $err); + $this->assertInternalType('int', $success); + } - private function execPhp($input){ + private function execPhp($input) + { + $output = null; + $err = null; $success = $this->_cmd->execute('php', __FILE__, __LINE__, $output, $err, $input); $this->assertTrue($success); - $this->assertEquals(trim($output),"test123"); - } - - public function testExecuteWithStdinAsString(){ - $this->execPhp($this->_input); - } - - public function testExecuteWithStdinAsStream(){ - $temp = tmpfile(); - fwrite($temp, $this->_input); - fseek($temp, 0); - $this->execPhp($temp); - fclose($temp); - } + $this->assertEquals(trim($output), "test123"); + } + + public function testExecuteWithStdinAsString() + { + $this->execPhp($this->_input); + } + + public function testExecuteWithStdinAsStream() + { + $temp = tmpfile(); + fwrite($temp, $this->_input); + fseek($temp, 0); + $this->execPhp($temp); + fclose($temp); + } } \ No newline at end of file