Exemplo n.º 1
0
function getOptions($options)
{
    $opt;
    $short = '';
    $long = array();
    $map = array();
    foreach ($options as $option) {
        $req = isset($option['required']) ? $option['required'] ? ':' : '::' : '';
        if (!empty($option['short'])) {
            $short .= $option['short'] . $req;
        }
        if (!empty($option['long'])) {
            $long[] = $option['long'] . $req;
        }
        if (!empty($option['short']) && !empty($option['long'])) {
            $map[$option['short']] = $option['long'];
        }
    }
    $arguments = getopt($short, $long);
    foreach ($map as $s => $l) {
        if (isset($arguments[$s]) && isset($arguments[$l])) {
            unset($arguments[$s]);
            continue;
        }
        if (isset($arguments[$s])) {
            $arguments[$l] = $arguments[$s];
            unset($arguments[$s]);
            continue;
        }
    }
    return $arguments;
}
Exemplo n.º 2
0
 protected function parseCliArguments()
 {
     // Prepare for getopt(). Note that it supports "require value" for cli args,
     // but we use our own format instead (see also php.net/getopt).
     $getoptShort = '';
     $getoptLong = array();
     foreach ($this->flags as $flagKey => $flagInfo) {
         switch ($flagInfo['type']) {
             case 'value':
                 $getoptShort .= $flagKey . '::';
                 break;
             case 'boolean':
                 $getoptShort .= $flagKey;
                 break;
         }
     }
     foreach ($this->options as $optionName => $optionInfo) {
         switch ($optionInfo['type']) {
             case 'value':
                 $getoptLong[] = $optionName . '::';
                 break;
             case 'boolean':
                 $getoptLong[] = $optionName;
                 break;
         }
     }
     $parsed = getopt($getoptShort, $getoptLong);
     if (!is_array($parsed)) {
         $this->error('Parsing command line arguments failed.');
     }
     $this->parsed = $parsed;
 }
Exemplo n.º 3
0
class CLIOptionsHandler
{
    /**
   * Accept the REPL object and perform any setup necessary from the CLI flags.
   *
   * @param Boris $boris
   */
    public function handle($boris)
    {
        $args = getopt('hvr:', array('help', 'version', 'require:'));
        foreach ($args as $option => $value) {
            switch ($option) {
                /*
         * Sets files to load at startup, may be used multiple times,
         * i.e: boris -r test.php,foo/bar.php -r ba/foo.php --require hey.php
         */
                case 'r':
                case 'require':
                    $this->_handleRequire($boris, $value);
                    break;
                    /*
         * Show Usage info
         */
                /*
         * Show Usage info
         */
Exemplo n.º 4
0
 /**
  * Инициализируем переменные с коммандной строки
  *
  */
 protected function _initOptParams()
 {
     $arrayInput = getopt(false, array('url:'));
     if ($arrayInput && array_key_exists('url', $arrayInput)) {
         $_SERVER['REQUEST_URI'] = $arrayInput['url'];
     }
 }
Exemplo n.º 5
0
function get_opts()
{
    $short_opts = "u:c:h::";
    $long_opts = array("bccwarn:", "bcccrit:", "sirwarn:", "sircrit:", "user:"******"pass:");
    $options = getopt($short_opts, $long_opts);
    return $options;
}
Exemplo n.º 6
0
 public function init()
 {
     function addopt($opt)
     {
         cli::$longopts[] = $opt;
         cli::$shortopts = cli::$shortopts . substr($opt, 0, 1);
     }
     $elems = array("help" => "Display this menu");
     foreach (array_merge(data::$elements, $elems) as $name => $element) {
         addopt($name);
     }
     $options = getopt(cli::$shortopts, cli::$longopts);
     $realopts = array();
     foreach ($options as $name => $option) {
         foreach (cli::$longopts as $opt) {
             if (substr($name, 0, 1) == substr($opt, 0, 1)) {
                 $name = $opt;
                 break;
             }
         }
         $realopts[$name] = $option;
     }
     cli::$cli_opts = $realopts;
     if (in_array("help", array_keys($realopts))) {
         foreach (array_merge(data::$elements, $elems) as $name => $element) {
             echo $name . "\t\t\t" . $element . PHP_EOL;
         }
         exit(0);
     }
 }
Exemplo n.º 7
0
function zpa_handle()
{
    $shortoptions = "w:r:d:li:h:u:p:";
    $options = getopt($shortoptions);
    $mapi = MAPI_SERVER;
    $user = "******";
    $pass = "";
    if (isset($options['h'])) {
        $mapi = $options['h'];
    }
    if (isset($options['u']) && isset($options['p'])) {
        $user = $options['u'];
        $pass = $options['p'];
    }
    $zarafaAdmin = zpa_zarafa_admin_setup($mapi, $user, $pass);
    if (isset($zarafaAdmin['adminStore']) && isset($options['l'])) {
        zpa_get_userlist($zarafaAdmin['adminStore']);
    } elseif (isset($zarafaAdmin['adminStore']) && isset($options['d']) && !empty($options['d'])) {
        zpa_get_userdetails($zarafaAdmin['adminStore'], $zarafaAdmin['session'], trim($options['d']));
    } elseif (isset($zarafaAdmin['adminStore']) && isset($options['w']) && !empty($options['w']) && isset($options['i']) && !empty($options['i'])) {
        zpa_wipe_device($zarafaAdmin['adminStore'], $zarafaAdmin['session'], trim($options['w']), trim($options['i']));
    } elseif (isset($zarafaAdmin['adminStore']) && isset($options['r']) && !empty($options['r']) && isset($options['i']) && !empty($options['i'])) {
        zpa_remove_device($zarafaAdmin['adminStore'], $zarafaAdmin['session'], trim($options['r']), trim($options['i']));
    } else {
        echo "Usage:\nz-push-admin.sh [actions] [options]\n\nActions: [-l] | [[-d|-w|-r] username]\n\t-l\t\tlist users\n\t-d user\t\tshow user devices\n\t-w user\t\twipe user device, '-i DeviceId' option required\n\t-r user\t\tremove device from list, '-i DeviceId' option required\n\nGlobal options: [-h path] [[-u remoteuser] [-p password]]\n\t-h path\t\tconnect through <path>, e.g. file:///var/run/socket\n\t-u remoteuser\tlogin as remoteuser\n\t-p password\tpassword of the remoteuser\n\n";
    }
}
Exemplo n.º 8
0
 public function run($argc, array $argv)
 {
     $options = getopt("c::h::", ["clean:", "help::"]);
     if (isset($options['h']) || isset($options['help'])) {
         self::usage();
         return;
     }
     $cleanOutput = false;
     if (isset($options['c']) || isset($options['clean'])) {
         $cleanOutput = true;
     }
     $list = [];
     \Phasty\Tman\TaskManager::getInstance()->scanDir(function ($className) use(&$list, $cleanOutput) {
         $runTimes = $className::getRunTime();
         if (!$runTimes) {
             return;
         }
         $className = \Phasty\Tman\TaskManager::fromClassName(substr($className, strlen($this->cfg["tasksNs"])));
         foreach ((array) $runTimes as $args => $runTime) {
             if (substr(trim($runTime), 0, 1) === '#' && $cleanOutput) {
                 continue;
             }
             $list[] = "{$runTime} " . $this->cfg["tman"] . " run " . "{$className}" . (is_string($args) ? " {$args}" : "");
         }
     });
     if (!empty($list)) {
         echo implode(" #tman:" . $this->cfg["tman"] . "\n", $list) . " #tman:" . $this->cfg["tman"] . "\n";
     }
 }
Exemplo n.º 9
0
 /**
  * @param array $config
  */
 function handler(array $cfg = [])
 {
     $key = ['listen::', 'indexer::', 'conf::', 'build::', 'status::'];
     $opt = getopt('', $key);
     $this->cmd = 'listen';
     foreach ($key as $v) {
         $v = str_replace('::', '', $v);
         if (isset($opt[$v])) {
             $this->cmd = $v;
             $this->args = $opt[$v];
             break;
         }
     }
     $this->default_value($cfg, 'redis', 'tcp://127.0.0.1:6379');
     $this->default_value($cfg, 'agent_log', __DIR__ . '/agent.log');
     $this->default_value($cfg, 'type', 'log');
     $this->default_value($cfg, 'input_sync_memory', 5 * 1024 * 1024);
     $this->default_value($cfg, 'input_sync_second', 5);
     $this->default_value($cfg, 'parser', [$this, 'parser']);
     $this->default_value($cfg, 'log_level', 'product');
     $this->default_value($cfg, 'elastic', ['http://127.0.0.1:9200']);
     $this->default_value($cfg, 'prefix', 'phplogstash');
     $this->default_value($cfg, 'shards', 5);
     $this->default_value($cfg, 'replicas', 1);
     $this->config = $cfg;
     $this->redis();
     return $this;
 }
Exemplo n.º 10
0
/**
 * Permet de récupérer les arguments de la console
 * Permet surtout de toujours avoir les arguments obligatoire par le système.
 * 
 * @link http://php.net/manual/fr/function.getopt.php
 * 
 * @param string $options  : Chaque caractère dans cette chaîne sera utilisé en tant que caractères optionnels et 
 *                           devra correspondre aux options passées, commençant par un tiret simple (-). 
 *                           Par exemple, une chaîne optionnelle "x" correspondra à l'option -x. 
 *                           Seuls a-z, A-Z et 0-9 sont autorisés.
 * @param array  $longopts : Un tableau d'options. Chaque élément de ce tableau sera utilisé comme option et devra 
 *                           correspondre aux options passées, commençant par un tiret double (--). 
 *                           Par exemple, un élément longopts "opt" correspondra à l'option --opt.
 *                           Le paramètre options peut contenir les éléments suivants :
 *                              * Caractères individuels (n'accepte pas de valeur)
 *                              * Caractères suivis par un deux-points (le paramètre nécessite une valeur)
 *                              * Caractères suivis par deux deux-points (valeur optionnelle)
 *                           Les valeurs optionnelles sont les premiers arguments après la chaîne. 
 *                           Si une valeur est requise, peu importe que la valeur soit suivi d'un espace ou non.
 * 
 * @return array
 */
function getCliParams($options, $longopts = array())
{
    $longopts = array_merge($longopts, array('type_site::'));
    $opt = getopt('f:' . $options, $longopts);
    unset($opt['f']);
    return $opt;
}
Exemplo n.º 11
0
 /** 初始化 */
 private function init()
 {
     $this->is_win = strstr(PHP_OS, 'WIN') ? true : false;
     $this->is_cli = PHP_SAPI == 'cli' ? true : false;
     $this->is_cgi = 0 === strpos(PHP_SAPI, 'cgi') || false !== strpos(PHP_SAPI, 'fcgi') ? true : false;
     if (!$this->is_cli) {
         $this->http_host = isset($_SERVER['HTTP_HOST']) ? strtolower($_SERVER['HTTP_HOST']) : '';
         $this->request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
         $pos = strpos($this->request_uri, '?');
         $this->request_path = $pos === false ? $this->request_uri : substr($this->request_uri, 0, $pos);
         $this->query_string = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
         $this->request_method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper($_SERVER['REQUEST_METHOD']) : '';
         $this->is_ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' || !empty($_POST[$this->conf['PARAMS_AJAX_SUBMIT']]) || !empty($_GET[$this->conf['PARAMS_AJAX_SUBMIT']]) ? true : false;
         $this->is_get = $this->request_method === 'GET' ? true : false;
         $this->is_post = $this->request_method === 'POST' ? true : false;
         $this->is_put = $this->request_method === 'PUT' ? true : false;
         $this->is_delete = $this->request_method === 'DELETE' ? true : false;
     } else {
         $opt = getopt('r:', [$this->conf['URL_REQUEST_URI'] . ':']);
         $this->request_uri = !empty($opt['r']) ? $opt['r'] : (!empty($opt[$this->conf['URL_REQUEST_URI']]) ? $opt[$this->conf['URL_REQUEST_URI']] : '');
         $pos = strpos($this->request_uri, '?');
         $this->request_path = $pos === false ? $this->request_uri : substr($this->request_uri, 0, $pos);
         $this->query_string = $pos === false ? '' : substr($this->request_uri, $pos + 1);
     }
 }
Exemplo n.º 12
0
 private function handleArguments()
 {
     $options = getopt('D::H::E::I::A', array('debug::', 'help::', 'exclude::', 'include::', 'all::'));
     foreach ($options as $option => $value) {
         switch ($option) {
             case 'D':
             case 'debug':
                 Utils::log('Debug mode enabled');
                 $this->debugMode = true;
                 break;
             case 'H':
             case 'help':
                 Utils::help();
                 exit;
             case 'E':
             case 'exclude':
                 $this->insertSpecification($value);
                 break;
             case 'I':
             case 'include':
                 $this->insertSpecification($value, false);
                 break;
             case 'A':
             case 'all':
                 Utils::logf('Possible units are: %s', implode(',', $this->units));
                 exit;
         }
     }
     $this->validateUnits();
 }
Exemplo n.º 13
0
 /**
  * @param $configFilename
  * @return FileWatcher
  */
 public function readConfig($configFilename)
 {
     include $configFilename;
     $this->_config = $config;
     $this->_log('Config file loaded');
     if (php_sapi_name() == "cli") {
         $longopts = array('password::', 'overallHash::');
         $options = getopt('', $longopts);
         if (isset($options['password'])) {
             $this->_providedPassword = $options['password'];
         }
         if (isset($options['overallHash'])) {
             $this->_providedOverallHash = $options['overallHash'];
         }
     } else {
         // not in cli-mode, try to get password from $_GET or $_POST
         if (isset($_POST['password'])) {
             $this->_providedPassword = $_POST['password'];
         } elseif ($_GET['password']) {
             $this->_providedPassword = $_GET['password'];
         }
         if (isset($_POST['overallHash'])) {
             $this->_providedOverallHash = $_POST['overallHash'];
         } elseif ($_GET['overallHash']) {
             $this->_providedOverallHash = $_GET['overallHash'];
         }
     }
     return $this;
 }
Exemplo n.º 14
0
 function __construct($options)
 {
     $this->reset($options);
     pcntl_signal(SIGTERM, array("JAXLHTTPd", "shutdown"));
     pcntl_signal(SIGINT, array("JAXLHTTPd", "shutdown"));
     $options = getopt("p:b:");
     foreach ($options as $opt => $val) {
         switch ($opt) {
             case 'p':
                 $this->settings['port'] = $val;
                 break;
             case 'b':
                 $this->settings['maxq'] = $val;
             default:
                 break;
         }
     }
     $this->httpd = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_set_option($this->httpd, SOL_SOCKET, SO_REUSEADDR, 1);
     socket_bind($this->httpd, 0, $this->settings['port']);
     socket_listen($this->httpd, $this->settings['maxq']);
     $this->id = $this->getResourceID($this->httpd);
     $this->clients = array("0#" . $this->settings['port'] => $this->httpd);
     echo "JAXLHTTPd listening on port " . $this->settings['port'] . PHP_EOL;
 }
Exemplo n.º 15
0
 public function run()
 {
     $this->buffer = new \Threaded();
     $opts = getopt("", ["disable-readline"]);
     if (extension_loaded("readline") and $this->stream === "php://stdin" and !isset($opts["disable-readline"])) {
         $this->readline = true;
     } else {
         $this->readline = false;
         $this->fp = fopen($this->stream, "r");
         stream_set_blocking($this->fp, 1);
         //Non-blocking STDIN won't work on Windows
     }
     $lastLine = microtime(true);
     while (true) {
         if (($line = $this->readLine()) !== "") {
             $this->buffer->synchronized(function (\Threaded $buffer, $line) {
                 $buffer[] = preg_replace("#\\x1b\\x5b([^\\x1b]*\\x7e|[\\x40-\\x50])#", "", $line);
             }, $this->buffer, $line);
             $lastLine = microtime(true);
         } elseif (microtime(true) - $lastLine <= 0.1) {
             //Non blocking! Sleep to save CPU
             usleep(40000);
         }
     }
 }
Exemplo n.º 16
0
function get_opts()
{
    $short_opts = "u:h::";
    $long_opts = array("user:"******"pass:");
    $options = getopt($short_opts, $long_opts);
    return $options;
}
 public function __construct($volume = null, $region = null, $quiet = null, $noOperation = null, $verbose = null, $description = null)
 {
     if ($volume == null) {
         // Check parameters
         $params = getopt('v:r::d::qno');
         $volume = isset($params['v']) ? $params['v'] : null;
         $region = isset($params['r']) ? $params['r'] : null;
         $quiet = isset($params['q']) ? $params['q'] : null;
         $noOperation = isset($params['n']) ? $params['n'] : null;
         $verbose = isset($params['o']) ? $params['o'] : null;
         $description = isset($params['d']) ? $params['d'] : null;
     }
     $this->volume = isset($volume) ? $volume : exit("EC2 Volume ID required\n");
     $this->region = isset($region) && array_key_exists($region, self::$regions) ? $region : 'us-east-1';
     $this->quiet = isset($quiet) ? true : false;
     $this->noOperation = isset($noOperation) ? true : false;
     $this->verbose = isset($verbose) ? true : false;
     $this->description = isset($description) ? $description : null;
     // Print settings
     $this->printLine("\n", true);
     $this->printLine("SETTINGS\n");
     $this->printLine("========\n");
     $this->printLine("Volume: .......... " . $this->volume . "\n");
     $this->printLine("Region: .......... " . self::$regions[$this->region] . "\n");
     $this->printLine("Quiet: ........... " . ($this->quiet ? 'Y' : 'N') . "\n");
     $this->printLine("No Operation: .... " . ($this->noOperation ? 'Y' : 'N') . "\n");
     $this->printLine("Verbose: ......... " . ($this->verbose ? 'Y' : 'N') . "\n\n");
     // Setup EC2 Client
     $this->client = Ec2Client::factory(['profile' => 'ec2snapshot', 'region' => $this->region]);
 }
Exemplo n.º 18
0
 public static function getOptions()
 {
     $parameters = array('s:' => 'source:', 'o:' => 'output:', 'e:' => 'exclude:', 'E:' => 'exclude-classes:');
     $getops = getopt(implode(array_keys($parameters)), $parameters);
     $options = array('source' => __DIR__ . "/../lib/", 'output' => WeixinFile::NS_ROOT . '.php', 'exclude' => array());
     foreach ($getops as $option => $value) {
         switch ($option) {
             case 's':
             case 'source':
                 $options['source'] = $value;
                 break;
             case 'o':
             case 'output':
                 $options['output'] = $value;
                 break;
             case 'E':
             case 'exclude-classes':
                 $options['exclude'] = @file($value, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: $value;
                 break;
             case 'e':
             case 'exclude':
                 $options['exclude'] = is_array($value) ? $value : array($value);
                 break;
         }
     }
     return $options;
 }
Exemplo n.º 19
0
 public static function getArgs()
 {
     $argv = $_SERVER['argv'];
     $deploy = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'deploy.ini';
     $commands = array('-l', '-r', '-c', '-d', '--revert', '--log', '--repo');
     $deploy_file = isset($argv[1]) ? end($argv) : "deploy.ini";
     if (!in_array($deploy_file, $commands)) {
         $deploy = $deploy_file . (substr($deploy_file, -4) === '.ini' ? '' : '.ini');
     }
     $opts = getopt("lr:d:c:", array("revert", "log::", "repo:"));
     if (isset($opts['log'])) {
         define('WRITE_TO_LOG', $opts['revert'] ? $opts['revert'] : 'git_deploy_php_log.txt');
     }
     if (isset($opts['d'])) {
         $deploy = $opts['d'];
     }
     if (isset($opts['c'])) {
         $opts['r'] = $opts['c'];
     }
     if (isset($opts['repo'])) {
         $repo_path = $opts['repo'];
     } else {
         $repo_path = getcwd() . DIRECTORY_SEPARATOR;
     }
     return array('config_file' => $deploy, 'target_commit' => isset($opts['r']) ? $opts['r'] : 'HEAD', 'list_only' => isset($opts['l']), 'revert' => isset($opts['revert']), 'repo_path' => $repo_path);
 }
Exemplo n.º 20
0
 public static function start()
 {
     $logger = new DefaultLogger('starter');
     $longopts = ['node:', 'worker', 'manager'];
     $params = getopt("", $longopts);
     if (!isset($params['node'])) {
         throw new \Exception('Parameter --node is required. It must be a name of Celium Node.');
     }
     if (isset($params['worker'])) {
         $logger->info('Worker is starting...');
         if (!isset(self::$workers[$params['node']])) {
             throw new \Exception('Workers for ' . $params['node'] . ' not found');
         }
         $function = self::$workers[$params['node']];
         $worker = $function($params['node'], $params);
         if (!$worker instanceof Worker) {
             throw new \Exception('onStartManager function must return the object of \\Celium\\Services\\Worker');
         }
         $worker->start();
     } elseif (isset($params['manager'])) {
         $logger->info('Manager is starting...');
         if (!isset(self::$managers[$params['node']])) {
             throw new \Exception('Managers for ' . $params['node'] . ' not found');
         }
         $function = self::$managers[$params['node']];
         $manager = $function($params['node'], $params);
         if (!$manager instanceof Manager) {
             throw new \Exception('onStartManager function must return the object of \\Celium\\Services\\Manager');
         }
         $manager->start('127.0.0.1:4730', 1000 * 1000);
         // @todo Make it configurable
     } else {
         throw new \Exception("Nothing to start. Use --worker or --manager options.\n");
     }
 }
Exemplo n.º 21
0
 /**
  * Sets up options, and initialises the Runner to perform mutation
  * tests and echo out the results
  *
  * @param array                              $options
  * @param \Mutagenesis\Runner\RunnerAbstract $runner Optional custom runner
  */
 public static function main(array $options = null, RunnerAbstract $runner = null)
 {
     if (is_null($options)) {
         self::$_options = getopt('', array('base::', 'src::', 'tests::', 'adapter::', 'bootstrap::', 'options::', 'timeout::', 'detail-captures::', 'log-format::', 'log-path::', 'constraint::', 'src-exclude::'));
     } else {
         self::$_options = $options;
     }
     if (is_null($runner)) {
         $runner = new BaseRunner();
     }
     self::setBaseDirectory($runner);
     self::setSourceDirectory($runner);
     self::setSourceExcludes($runner);
     self::setTestDirectory($runner);
     self::setAdapterName($runner);
     self::setBootstrap($runner);
     self::setAdapterOptions($runner);
     self::setTimeout($runner);
     self::setDetailCaptures($runner);
     self::setLogFormat($runner);
     self::setLogPath($runner);
     self::setAdapterConstraint($runner);
     $result = $runner->execute();
     echo $result;
 }
Exemplo n.º 22
0
 public static function init()
 {
     self::$win = substr(PHP_OS, 0, 3) == 'WIN';
     self::$hasReadline = function_exists('readline_callback_handler_install');
     if ($_ = getopt('d', ['log::', 'locales::', 'mpqDataDir::', 'delete'])) {
         // optional logging
         if (!empty($_['log'])) {
             self::$logFile = trim($_['log']);
         }
         // alternative data source (no quotes, use forward slash)
         if (!empty($_['mpqDataDir'])) {
             self::$srcDir = str_replace(['\\', '"', '\''], ['/', '', ''], $_['mpqDataDir']);
         }
         // optional limit handled locales
         if (!empty($_['locales'])) {
             // engb and enus are identical for all intents and purposes
             $from = ['engb', 'esmx'];
             $to = ['enus', 'eses'];
             $_['locales'] = str_ireplace($from, $to, strtolower($_['locales']));
             self::$locales = array_intersect(Util::$localeStrings, explode(',', $_['locales']));
         }
         if (isset($_['d']) || isset($_['delete'])) {
             self::$tmpDBC = true;
         }
     }
     if (!self::$locales) {
         self::$locales = array_filter(Util::$localeStrings);
     }
     // restrict actual locales
     foreach (self::$locales as $idx => $str) {
         if (!defined('CFG_LOCALES') || CFG_LOCALES & 1 << $idx) {
             self::$localeIds[] = $idx;
         }
     }
 }
function get_options($server_cfg)
{
    $options = array();
    $params = getopt("g:t:p:j:");
    $period = "daily";
    $timeslot = time();
    $games = $server_cfg['game_list'];
    $job = "both";
    if (isset($params['g'])) {
        $games = explode(",", $params['g']);
    }
    if (isset($params['t'])) {
        $timeslot = (int) $params['t'];
    }
    if (isset($params['p'])) {
        $period = $params['p'];
    }
    if (isset($params['j'])) {
        $job = $params['j'];
    }
    $timeslot = (int) ($timeslot / 1800);
    $options['games'] = $games;
    $options['timeslot'] = $timeslot;
    $options['period'] = $period;
    $options['job'] = $job;
    return $options;
}
Exemplo n.º 24
0
 private static function handleCLIOpts(&$doTbls)
 {
     $doTbls = [];
     $_ = getopt(self::$shortOpts, self::$longOpts);
     if ((isset($_['help']) || isset($_['h'])) && empty($_['sql'])) {
         self::printCLIHelp();
         exit;
     }
     // required subScripts
     if (!empty($_['sync'])) {
         $sync = explode(',', $_['sync']);
         foreach (self::$tables as $name => $info) {
             if (!empty($info[3]) && array_intersect($sync, $info[3])) {
                 $doTbls[] = $name;
             }
         }
         // recursive dependencies
         foreach (self::$tables as $name => $info) {
             if (!empty($info[2]) && array_intersect($doTbls, $info[2])) {
                 $doTbls[] = $name;
             }
         }
         $doTbls = $doTbls ? array_unique($doTbls) : null;
     } else {
         if (!empty($_['sql'])) {
             $doTbls = explode(',', $_['sql']);
         }
     }
 }
Exemplo n.º 25
0
 protected function processArgs()
 {
     $short = "u::s::q::l::";
     $long = ['uri::', 'skip-wget::', 'quiet-wget::', 'log-file::'];
     $options = getopt($short, $long);
     foreach ($options as $key => $val) {
         switch ($key) {
             case 'u':
             case 'uri':
                 $this->setBaseUri($val);
                 break;
             case 's':
             case 'skip-wget':
                 $this->setOption('skip-wget', true);
                 break;
             case 'q':
             case 'quiet-wget':
                 $this->setOption('quiet-wget', true);
                 break;
             case 'l':
             case 'log-file':
                 $this->logger->setStream($this->getOutputStream($val));
                 break;
         }
     }
 }
Exemplo n.º 26
0
 protected function handleArguments()
 {
     $shortopts = '';
     $longopts = array('class:', 'action:');
     $options = !function_exists('getopt') ? $this->_getopt() : ($options = getopt($shortopts, $longopts));
     $options = $this->_optionNormalize($options);
     if (!isset($options['class'])) {
         throw new Exception('class name is require.');
     }
     $this->_options['class'] = 'Tasks_' . $options['class'];
     if (empty($options['action'])) {
         // actionの指定がない場合
         $ref_class = new ReflectionClass($this->_options['class']);
         foreach ($ref_class->getMethods() as $methods) {
             if (strpos($methods->name, 'task', 0) !== 0) {
                 continue;
             }
             // taskから始まらないメソッドはskip
             $this->_options['action'][] = $methods->name;
             // taskメソッドを全て実行対象とする
         }
     } else {
         // 指定があればそれらのみを実行対象とする
         foreach ($options['action'] as $action) {
             $this->_options['action'][] = 'task' . ucfirst($action);
         }
     }
 }
Exemplo n.º 27
0
 public static function init()
 {
     $args = getopt('f:t:d:o:', array('tc::'));
     if (isset($args['f']) && isset($args['t']) && isset($args['d'])) {
         self::$query_date = $args['d'];
         self::$from_station_name = $args['f'];
         self::$to_station_name = $args['t'];
         self::$station_train_code = isset($args['tc']) ? $args['tc'] : '';
     } else {
         $usage = "请输入参数:\n-f\t出发地,如北京 \n-t\t目的地,如郓城 \n-d\t出发日,如2016-01-06 \n--tc\t车次,支持多车次查询如--tc='D2320,D2322'";
         self::show($usage);
         exit;
     }
     $stations = explode('|', self::$station_names);
     $total = count($stations);
     for ($i = 0; $i < $total && (empty(self::$from_station_code) || empty(self::$to_station_code)); $i++) {
         if (empty(self::$from_station_code) && $stations[$i] == self::$from_station_name) {
             self::$from_station_code = isset($stations[$i + 1]) ? $stations[$i + 1] : '';
         } else {
             if (empty(self::$to_station_code) && $stations[$i] == self::$to_station_name) {
                 self::$to_station_code = isset($stations[$i + 1]) ? $stations[$i + 1] : '';
             }
         }
     }
     if (empty(self::$from_station_code) || empty(self::$to_station_code) || empty(self::$query_date)) {
         $usage = "请输入参数:\n-f\t出发地,如北京 \n-t\t目的地,如郓城 \n-d\t出发日,如2016-01-06 \n";
         self::show($usage);
         exit;
     }
 }
/**
 * Application main function.  Retrieves cli args and runs engine.
 */
function main()
{
    $opt = getopt("D:d:h:u:p:o:v:m:n:c:t:s:xw?");
    if (@$opt['?'] || !@$opt['d']) {
        print_help();
        return -1;
    }
    $config = array();
    $config['db'] = get_option($opt, 'd');
    $config['host'] = get_option($opt, 'h', 'localhost');
    $config['user'] = get_option($opt, 'u', 'root');
    $config['pass'] = get_option($opt, 'p', '');
    $config['namespace_prefix'] = get_option($opt, 'n', '');
    $config['verbosity'] = get_option($opt, 'v', 1);
    $config['output_dir'] = get_option($opt, 'm', './cdc_audit_sync');
    $config['tables'] = get_option($opt, 't', null);
    $config['wipe'] = isset($opt['w']) ? true : false;
    $config['stdout'] = STDOUT;
    if (isset($opt['o'])) {
        $fh = fopen($opt['o'], 'w');
        if (!$fh) {
            die("Could not open {$opt['o']} for writing");
        }
        $config['stdout'] = $fh;
    }
    $engine = new cdc_audit_sync_mysql($config);
    $success = $engine->run();
    fclose($config['stdout']);
    return $success ? 0 : -1;
}
Exemplo n.º 29
0
 public function parseOptions()
 {
     $shortopts = '';
     $longopts = array();
     $defaults = array();
     foreach (self::$optionDefs as $name => $def) {
         $def += array('default' => '', 'short' => false);
         $defaults[$name] = $def['default'];
         $postfix = is_bool($defaults[$name]) ? '' : ':';
         $longopts[] = $name . $postfix;
         if ($def['short']) {
             $shortmap[$def['short']] = $name;
             $shortopts .= $def['short'] . $postfix;
         }
     }
     $received = getopt($shortopts, $longopts);
     foreach (array_keys($received) as $key) {
         if (strlen($key) === 1) {
             $received[$shortmap[$key]] = $received[$key];
             unset($received[$key]);
         }
     }
     // getopt is odd ... it returns false for received args with no options allowed
     foreach (array_keys($received) as $key) {
         if (false === $received[$key]) {
             $received[$key] = true;
         }
     }
     $received += $defaults;
     if ($received['help']) {
         $this->usage();
         exit(0);
     }
     return $received;
 }
Exemplo n.º 30
0
 public function __construct($options)
 {
     $opts = array();
     $longopts = array();
     $relations = array();
     foreach ($options as $k => $v) {
         if (is_numeric($k)) {
             if (strlen($v) == 1) {
                 $opts[] = $v;
             } else {
                 $longopts[] = $v;
             }
         } else {
             $opts[] = $k;
             $longopts[] = $v;
             $k = trim($k, ':');
             $v = trim($v, ':');
             $relations[$k] = $v;
             $relations[$v] = $k;
         }
     }
     $arguments = array();
     foreach (getopt(implode('', $opts), $longopts) as $k => $v) {
         if (isset($relations[$k]) && !isset($arguments[$relations[$k]])) {
             $arguments[$relations[$k]] = $v;
         }
         $arguments[$k] = $v;
     }
     parent::__construct($arguments, \ArrayObject::STD_PROP_LIST | \ArrayObject::ARRAY_AS_PROPS);
 }