Skip to content

Instantly share code, notes, and snippets.

@dfelton
Last active June 29, 2016 18:37
Show Gist options
  • Select an option

  • Save dfelton/5c1e46d3753c31ce9b5899023f0afa24 to your computer and use it in GitHub Desktop.

Select an option

Save dfelton/5c1e46d3753c31ce9b5899023f0afa24 to your computer and use it in GitHub Desktop.
Abstract shell class
<?php
/**
* Abstract shell class for non-magento sites.
*
* @category FirstScribe
* @package FirstScribe_Shell
* @author Darren Felton
*/
abstract class FirstScribe_Shell_Abstract
{
/**
* Input arguments
*
* @var array
*/
protected $_args = array();
/**
* Initialize application and parse input parameters
*/
public function __construct()
{
if (!defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
}
$this->_parseArgs();
$this->_construct();
$this->_validate();
$this->_showHelp();
}
/**
* Parse input arguments
*
* @return FirstScribe_Shell_Abstract
*/
protected function _parseArgs()
{
$current = null;
foreach ($_SERVER['argv'] as $arg) {
$match = array();
if (preg_match('#^--([\w\d_-]{1,})$#', $arg, $match) || preg_match('#^-([\w\d_]{1,})$#', $arg, $match)) {
$current = $match[1];
$this->_args[$current] = true;
} else {
if ($current) {
$this->_args[$current] = $arg;
} else if (preg_match('#^([\w\d_]{1,})$#', $arg, $match)) {
$this->_args[$match[1]] = true;
}
}
}
return $this;
}
/**
* Additional initialize instruction
*
* @return FirstScribe_Shell_Abstract
*/
protected function _construct()
{
return $this;
}
/**
* Validate arguments
*/
protected function _validate()
{
if (isset($_SERVER['REQUEST_METHOD'])) {
die('This script cannot be run from Browser. This is the shell script.');
}
}
/**
* Run script
*/
abstract public function run();
/**
* Check is show usage help
*/
protected function _showHelp()
{
if (isset($this->_args['h']) || isset($this->_args['help'])) {
die($this->usageHelp());
}
}
/**
* Retrieve Usage Help Message
*/
public function usageHelp()
{
return <<<USAGE
Usage: php -f script.php -- [options]
-h Short alias for help
help This help
USAGE;
}
/**
* Retrieve argument value by name or false
*
* @param string $name the argument name
* @return mixed
*/
public function getArg($name)
{
if (isset($this->_args[$name])) {
return $this->_args[$name];
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment