Пример #1
0
/**
 * コマンドラインからのオプションパーサーを取得します
 *
 * @return \Commando\Command オプションパーサー
 */
function buildCommand($argv = null)
{
    $cmd = new Commando\Command($argv);
    $cmd->option('p')->aka("preset")->describe("プリセット名を指定します");
    $cmd->option('l')->boolean()->describe('プリセットの一覧を表示します');
    $cmd->option('i')->aka('dir')->aka('input')->describe("入力ディレクトリ");
    $cmd->option('regexp')->describe("正規表現");
    $cmd->option('replacement')->describe('置換文字列');
    return $cmd;
}
Пример #2
0
/**
 * @return \Commando\Command
 */
function buildCommandLineOptions()
{
    $cmd = new Commando\Command();
    $cmd->option()->require()->description('The Public Hash for the cron that is being run. ');
    $cmd->option()->require()->description('The command to run');
    $cmd->option('r')->aka('send-result')->boolean()->description('Send the std out of the passed in command to Cronalytics');
    $cmd->option('x')->aka('debug')->boolean();
    $cmd->option('v')->aka('verbose')->boolean()->description('Verbose output');
    $cmd->option('vvv')->aka('veryveryverbose')->boolean()->description('Very Very Verbose output');
    $cmd->option('s')->aka('silent')->boolean()->description('No output to std out or std err. even the script result is not printed.');
    return $cmd;
}
Пример #3
0
#!/usr/bin/env php
<?php 
require dirname(dirname(__FILE__)) . '/lib/autoload.php';
$command = new Commando\Command();
$command->option()->describedAs('Command to run: default is update.');
$command->option('cache-only')->boolean()->describedAs('Do not load metadata, only use existing cache.');
if ($command[0] === 'termcolor') {
    phpterm_demo();
    exit;
}
DiscoUtils::log("DiscoJuice update script. Now updating feide feed.", true);
$fav = Favourites::getByID('uuid:d665541c-2fe6-4843-8752-314587f4edd1');
if ($fav === null) {
    DiscoUtils::log("No favourites found");
    $fav = new Favourites(array('id' => 'uuid:d665541c-2fe6-4843-8752-314587f4edd1', 'favs' => array('foo1', 'foo2', 'bar3')));
    $fav->save();
} else {
    print_r($fav);
}
DiscoUtils::log("Done.");
<?php

// Clearer definition of Arguments vs. Flags
require dirname(__DIR__) . '/vendor/autoload.php';
// v0.2.0 started to add a clearer definition between "flag" type options
// and "argument" type options for those that may prefer it.
// In Commando, flags are options that require a name when they are being
// specified on the command line. Arguments are options that are not named in
// this way. In the example below, '-f' and '--long' are described as "flags"
// type options in Commando terms with the values 'value1' and 'value2'
// respectively, whereas value3, value4, and value5 are described as "argument"
// type options.
// php argumentsVsFlags.php -f value1 --long value2 value3 value4 value5
$cmd = new Commando\Command();
$cmd->flag('f')->flag('l')->aka('long')->argument()->argument()->argument();
var_dump($cmd->getArgumentValues());
var_dump($cmd->getFlagValues());
// This is equivalent to...
// $cmd = new Commando\Command();
// $cmd
//     ->option('f')
//     ->option('l')
//         ->aka('long')
//     ->option()
//     ->option()
//     ->option();
Пример #5
0
<?php

//https://github.com/nategood/commando
require 'vendor/autoload.php';
$cmd = new Commando\Command();
/*
$cmd->option()
	->require()
	->describedAs('A person\'s name');
*/
$cmd->option('r')->aka('reload')->must(function () {
    print 'Reloaddddd.';
});
print 'hello ' . $cmd[0];
print "\n----\n" . "oxc: OXC command line tool.\n";
Пример #6
0
<?php

use Discord\WebSockets\Event;
// Allow up to 1GB memory usage.
ini_set("memory_limit", "1024M");
// Turn on garbage collection
gc_enable();
// Define the current dir
define("BASEDIR", __DIR__);
define("PLUGINDIR", __DIR__ . "/plugins/");
// In case we started from a different directory.
chdir(BASEDIR);
// Load all the vendor files
require_once BASEDIR . "/vendor/autoload.php";
$cmd = new \Commando\Command();
// Define the logfiles location
$cmd->option("c")->aka("config")->title("Path to configuration file")->describedAs("Defines the configuration file that the bot will use to run")->file(true)->require();
$cmd->option("ccp")->title("Install the ccp database")->describedAs("Installs the CCP database. Required before the bot can start properly")->boolean();
$cmd->option("conv")->aka("convert")->title("Converts a username/password login to token login")->describedAs("Converts the username/password login for Discord, to the new bot API token login");
$args = $cmd->getFlagValues();
// Define the path for the logfile
$configPath = $args["c"] ? $args["c"] : \Exception("Error, config file not loaded");
// Bot start time
$startTime = time();
// Load in the config
require_once $configPath;
// define the bots name
define("BOTNAME", strtolower($config["bot"]["botName"]));
// Conversion path triggered
if ($args["conv"]) {
    $discord = new \Discord\Discord($config["discord"]["email"], $config["discord"]["password"]);
Пример #7
0
#!/usr/bin/env php
<?php 
date_default_timezone_set('UTC');
foreach (array(__DIR__ . '/../../../autoload.php', __DIR__ . '/../../autoload.php', __DIR__ . '/../vendor/autoload.php', __DIR__ . '/vendor/autoload.php') as $file) {
    if (file_exists($file)) {
        define('COMPOSER_AUTOLOADER', $file);
        break;
    }
}
try {
    if (defined('COMPOSER_AUTOLOADER')) {
        require_once COMPOSER_AUTOLOADER;
    } else {
        throw new Exception('Composer autoloader not found!');
    }
    $cmd = new Commando\Command();
    $cmd->setHelp('uptize-php cli v0.1.1')->flag('c')->aka('config')->describedAs('Configuration file')->flag('d')->aka('dryRun')->describedAs('Dry run (do not send check data to uptize.me)')->boolean()->flag('k')->aka('key')->describedAs('Machine Key to send check data to uptize.me')->flag('o')->aka('output')->describedAs('Output check data to a file')->flag('v')->aka('verbose')->describedAs('Verbose output')->boolean()->flag('l')->aka('log')->describedAs('Log output')->default(__DIR__ . '/uptize.log');
    if (empty($cmd['config'])) {
        $config = __DIR__ . '/uptize.json';
    } else {
        $config = $cmd['config'];
    }
    if (!is_file($config)) {
        throw new Exception("Config file '{$config}' not found.");
    }
    $settings = uptize\Common\Config::loadFile($config);
    if (empty($settings['checks'])) {
        throw new Exception('Empty check list on config file.');
    }
    $report = uptize\Agent::run($settings['checks']);
    if ($cmd['dryRun']) {
Пример #8
0
// you can specify your own execution context by wrapping this script in a script that defines a custom context.
// for example, you can set a DIC in the context that then becomes available to event handlers through $event->getContext()['container']
// i.e. prototypic to inject a symfony container and event dispatcher in the context:
// <?php
// $context = T24\Context\ExecutionContext::create();
// $context['container'] = $app->getContainer();
// $context->setEventDispatcher($app->getContainer()->get['event_dispatcher']);
// require('run-agent.php');
//
$context = isset($context) ? $context : ExecutionContext::create();
if (!$context instanceof ExecutionContext) {
    throw new RuntimeException('Execution context is not an instance of T24\\Handler\\ExecutionContext but ' . get_class($context));
}
// php file.php ./assets/example.txt
ini_set('display_errors', 1);
$cmd = new Commando\Command();
$cmd->setHelp('sqs agent')->option('ttl')->describedAs('sets the ttl / runtime of the script. Defaults to 45 (in seconds)')->option('sleep')->defaultsTo(null)->describedAs('sets the time to rest between two message retrievals. Defaults to 3 (in seconds)')->option('config')->defaultsTo(null)->describedAs('configuration file');
$run = function () use($cmd, $context) {
    $_options = $cmd->getOptions();
    $options = [];
    foreach ($_options as $key => $option) {
        $options[$key] = $option->getValue();
    }
    $options['base_dir'] = __DIR__ . '/../';
    // for this binary, subscribe to some configuration events to load config files etc.
    // first, load the configuration file
    $context->getEventDispatcher()->addListener(SqsEvents::EVENT_SQSAGENT_CONFIGURE, function (ConfigEvent $event) use($options) {
        if ($options['config']) {
            $newCfg = json_decode(file_get_contents($options['config']), true);
            if (!$newCfg) {
                throw new RuntimeException('could not load config file ' . $options['config']);
Пример #9
0
<?php

require 'vendor/autoload.php';
$cmd = new Commando\Command();
$cmd->option()->require()->describedAs('Name of a song to be searched in youtube and downloaded as a mp3');
if (isset($cmd[0])) {
    $search = new \YoutubeHelper\Search($cmd[0]);
    $videoHash = $search->run();
    echo $videoHash;
}
Пример #10
0
#!/usr/bin/env php
<?php 
$autoloads = array(__DIR__ . '/../vendor/autoload.php', __DIR__ . '/../../../autoload.php');
foreach ($autoloads as $autoload) {
    $autoload = str_replace('/', DIRECTORY_SEPARATOR, $autoload);
    if (file_exists($autoload)) {
        require_once $autoload;
    }
}
/* define cli options */
$command = new \Commando\Command();
$command->setHelp("Usage: {$argv[0]} [OPTIONS] src dest\n\nChange directory structure or class name to fit the standard. \nThis tool scan src dir for class definations and put them to a new dir, other files are left.\nIt does not support namespace yet");
$command->argument()->require()->expectsFile()->title('src')->describedAs('src directory of your code');
$command->argument()->require()->title('dest')->describedAs('dest directory to generate code');
$command->option('s')->aka('standard')->describedAs('naming standard, avalible standards are: psr0, yaf_controller')->must(function ($standard) {
    $standards = array('psr0', 'yaf_controller');
    return in_array($standard, $standards);
});
$command->option('i')->aka('input')->describedAs("Regex to match input files, default is '/\\.php\$/'");
$command->option('t')->aka('target')->describedAs('if you want to rename class or method, specify target here: class, method')->must(function ($target) {
    $targets = array('class', 'method');
    return in_array($target, $targets);
});
$command->option('p')->aka('pattern')->describedAs('pattern to match your class name or method name');
$command->option('r')->aka('replace')->describedAs('replacement to replace your class or method name');
if ($command['t']) {
    $command->option('p')->require();
    $command->option('r')->require();
}
$command->parse();
/* do process */
Пример #11
0
function get($url, $headers = [], $data = [])
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    if (count($data) > 0) {
        $headers[] = 'X-HTTP-Method-Override: PUT';
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    }
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    return curl_exec($curl);
}
#
# Command line arguments
#
$cli = new Commando\Command();
$cli->option('u')->aka('username')->require()->describedAs('Cloudflare username');
$cli->option('k')->aka('api_key')->require()->describedAs('Cloudflare API key');
$cli->option('z')->aka('zone')->require()->describedAs('Cloudflare zone');
$cli->option('d')->aka('domain')->require()->describedAs('Domain name');
#
# Retrieve current DNS record
#
$cloudflareData = json_decode(get('https://api.cloudflare.com/client/v4/zones/' . $cli['zone'] . '/dns_records?type=A&name=' . $cli['domain'] . '&page=1&per_page=20&order=type&direction=desc&match=all', ['X-Auth-Email: ' . $cli['username'], 'X-Auth-Key: ' . $cli['api_key'], 'Content-Type: application/json']));
$cloudflareRecord = $cloudflareData->result[0]->id;
$currentIp = $cloudflareData->result[0]->content;
#
# Retrieve current IP address
#
$externalData = get('http://checkip.dyndns.com/');
preg_match("/((2[0-4]|1\\d|[1-9])?\\d|25[0-5])(\\.(?1)){3}/", $externalData, $matches);
Пример #12
0
    $dirmode = 0755;
    if (defined('IMGIN_DIR_MODE')) {
        $dirmode = IMGIN_DIR_MODE;
    }
    $mask = umask();
    umask(00);
    $result = mkdir($path, $dirmode, true);
    umask($mask);
    return $result;
}
/**
 * Clear manipulated image by CLI
 *
 */
if (php_sapi_name() == 'cli') {
    $imgin = new Commando\Command();
    $imgin->option()->require()->describedAs('Clear manipulated image')->must(function ($cmd) {
        return in_array($cmd, array('clearcache'));
    })->option()->describedAs('Original image path')->must(function ($originalImagePath) {
        if (is_null($originalImagePath)) {
            return true;
        }
        if (!file_exists($originalImagePath)) {
            throw new \Exception(sprintf('%s not exists', $originalImagePath));
        }
        return true;
    })->option('a')->aka('all')->describedAs('When clear cache all, use this option')->boolean();
    // clearcache
    if ($imgin[0] === 'clearcache') {
        // --all
        if ($imgin['all']) {
Пример #13
0
<?php

require dirname(__DIR__) . '/vendor/autoload.php';
// php file.php ./assets/example.txt
$cmd = new Commando\Command();
$cmd->argument()->expectsFile();
var_dump($cmd->getArgumentValues());
<?php

ini_set('memory_limit', '256M');
date_default_timezone_set('Europe/Zagreb');
require 'vendor/autoload.php';
// FaceBook app config
$fb = new Facebook\Facebook(['app_id' => '', 'app_secret' => '', 'default_graph_version' => 'v2.5', 'default_access_token' => '']);
// === CLI TOOL SETUP ===
$cmd = new Commando\Command();
$cmd->setHelp('Gets comments for the latest posts on a Facebook page.' . PHP_EOL . 'Usage: CMD [getTargetPosts|processPosts] -i {FB page ID} -f {filename for results}');
$cmd->option()->require()->describedAs('Which function should I do')->must(function ($function) {
    $functions = array('getTargetPosts', 'processPosts');
    return in_array($function, $functions);
});
$cmd->option('i')->aka('fbpageid')->require()->describedAs('ID of the Facebook page');
$cmd->option('f')->aka('filename')->require()->describedAs('File name that the result will be saved in, no extension');
// === APP LOGIC ===
// Fetches post IDs that will be scraped for comments
function getTargetPosts($app, $FBPageID)
{
    $posts = [];
    $response = $app->get('/' . $FBPageID . '/posts?limit=100');
    $response = $response->getGraphEdge();
    for ($i = 0; $i < 50; $i++) {
        foreach ($response as $post) {
            $posts[] = $post->asArray()['id'];
        }
        $response = $app->next($response);
    }
    return $posts;
}
Пример #15
0
<?php

require __DIR__ . '/vendor/autoload.php';
$sainsburys_cmd = new Commando\Command();
$sainsburys_cmd->option('p')->aka('plainjson')->describedAs('Use plain json instead of human readable.')->boolean()->option('t')->aka('texterrors')->describedAs('Display errors as plain text instead of json.')->boolean()->option('d')->aka('descriptiontext')->describedAs('Get the product description from the page text instead of the meta tags.')->boolean()->option('f')->aka('fileget')->describedAs('Use PHP file_get_contents instead of CURL.')->boolean();
//Create scraper and display results
$scraper = new Sainsburys\Scraper($sainsburys_cmd['fileget'], $sainsburys_cmd['texterrors'], $sainsburys_cmd['plainjson'], $sainsburys_cmd['descriptiontext']);
echo $scraper->scrape(), PHP_EOL;
#!/usr/bin/env php
<?php 
require_once 'vendor/autoload.php';
// 初期セットアップ、環境変数も見る
$cmd = new Commando\Command();
$cmd->option('mysql_base')->describedAs('インストール済みMysql base dir (/usr や /usr/local/Cellar/mysql/5.6.27 (brew)).')->default('/usr/local/Cellar/mysql/5.6.27');
$cmd->option('port')->describedAs('生成する設定ファイルに記述するmysql の受付ポート')->default('3306');
$cmd->option('datadir')->describedAs('新しく作成するmysql dataディレクトリの設置先')->default(realpath(getcwd()));
// カレントディレクトリ
// 処理していくぞ
$dir = $cmd['datadir'];
// datadirが本当に存在して空かチェックする
if (!file_exists($dir) || filetype($dir) !== 'dir') {
    echo "インストール先ディレクトリがみつかりません";
    exit(1);
}
$file_list = glob($dir . '/*');
if (count($file_list) > 0) {
    echo "インストール先ディレクトリが空ではないです";
    exit(1);
}
// mysqlのBasedirがあっているか確認する
// Could not find my-default.cnf
if (!file_exists("{$cmd['mysql_base']}/support-files/my-default.cnf")) {
    echo "mysql base dirがみつかりません(/support-files/my-default.cnfがみつかりません)";
    exit(1);
}
chdir($dir);
$mysql_install_db = $cmd['mysql_base'] . "/bin/mysql_install_db --datadir={$dir}/mysql_data/ --basedir=" . $cmd['mysql_base'];
//本当につくっていいか聞く
echo "以下の内容で作成しますか?\n(変更したい場合には、 --help を参照してください)\n--\n作成されるmysqlのdata_dir: {$dir}/mysql_data\n起動停止スクリプト生成先: {$dir}\n接続受付ポート: {$cmd['port']}\n利用するmysqlのbase dir: {$cmd['mysql_base']}\n--\n以下コマンドが実行され、同時にスクリプトファイルが生成されます。\n\$ {$mysql_install_db}\n\ny/n: ";
Пример #17
0
• Emails need to be set to be lower case before being inserted into DB
• The script should validate the email address before inserting to make sure that it is valid (valid means that it is a legal email format e.g. “xxxx@asdf@asdf is not a legal format). In the instance that an email is invalid, no insert should be made to database and error message reported to STDOUT.
We are looking for a script that is robust and gracefully handles errors/exceptions.

Command line options:
 --file [csv file name] – this is the name of the CSV to be parsed
 --create_table – this will cause the MySQL users table to be built (and no further
 action will be taken)
 --dry_run – this will be used with the --file directive in the instance that we want to run the script but not insert into the DB. All other functions will be executed, but the database won't be altered.
 -u – MySQL username
 -p – MySQL password
 -h – MySQL host
 --help – which will output the above list of directives with details.
*/
require_once 'vendor/autoload.php';
$cmd_options = new Commando\Command();
// Define option "--file"
$cmd_options->option('file')->file()->describedAs('Input file with CSV data to be parced');
// Define flag "--create_table"
$cmd_options->flag('create_table')->boolean()->needs('u', 'p', 'h')->describedAs('Instructs to create table in MySQL DB with name "users"');
// Define flag "--dry_run"
$cmd_options->flag('dry_run')->boolean()->describedAs('No data will be added to DB. All other functions will be executed');
// Define option "u"
$cmd_options->option('u')->needs('p', 'h')->describedAs('MySQL username');
// Define option "-p"
$cmd_options->option('p')->needs('u', 'h')->describedAs('Password of MySQL user');
// Define option "-h"
$cmd_options->option('h')->needs('u', 'p')->describedAs('MySQL hostname or IP');
//Compose help message
$help = "Usage:\n\nCreating table:\n\tphp user_upload.php --create_table -u <MySQL user>\n\t\t-p <MySQL user password> -h <MySQL hostname>\n\t\t\nDry run, check CSV content and exit without importing to DB:\n\tphp user_upload.php --dru_run --file <CSV filename>\n\nImporting file:\n\tphp user_upload.php --file <CSV filename> -u <MySQL user> \n\t\t-p <MySQL user password> -h <MySQL hostname>\n\nIf invalid emails are found in CSV then no DB insert will be done.\n\t\t\nOnly above described sets of options could be used. E.g. you cannot use --create_table together with --dry_run  \n";
$cmd_options->setHelp($help);
Пример #18
0
#!/usr/bin/env php
<?php 
require dirname(dirname(__FILE__)) . '/lib/autoload.php';
$command = new Commando\Command();
$command->option()->describedAs('Command to run: default is update.');
$command->option('f')->aka('feed')->describedAs('The feed identifier to load.');
$command->option('cache-only')->boolean()->describedAs('Do not load metadata, only use existing cache.');
if ($command[0] === 'termcolor') {
    phpterm_demo();
    exit;
}
$backend = new DiscoJuiceBackend();
if ($command['cache-only']) {
    DiscoUtils::log("Running in cache-only mode");
    $backend->enableCacheOnly(true);
}
DiscoUtils::log("DiscoJuice update script. Now updating metadata.", true);
if ($command['feed']) {
    $backend->updateFeed($command['feed']);
} else {
    $backend->update();
}
Пример #19
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
// Set Global Facade
class Graylogger extends \Graylogger\Graylogger
{
}
// Prevent CLI handling if loaded another way
if (PHP_SAPI != 'cli') {
    return;
}
$cmd = new \Commando\Command();
$cmd->setHelp('A simple CLI executable for sending a message to a Graylog server using PHP.');
$cmd->option()->require()->referToAs('message')->description('The log message.');
$cmd->option('f')->aka('facility')->default(Graylogger::FACILITY)->description('The log facility. Default: ' . Graylogger::FACILITY);
$cmd->option('l')->aka('level')->default(Graylogger::LEVEL)->description('The log level, per PSR-7. Default: ' . Graylogger::LEVEL);
$cmd->option('h')->aka('host')->default(Graylogger::HOST)->description('The Graylog server host. Default: ' . Graylogger::HOST);
$cmd->option('p')->aka('port')->default(Graylogger::PORT)->description('The Graylog server port. Default: ' . Graylogger::PORT);
Graylogger::log($cmd[0], $cmd['host'], $cmd['port'], $cmd['facility'], $cmd['level']);
Пример #20
0
<?php

// Demo using default error reporting and "the beep"
// Run this and forget the required -r flag.
// > php errors.php
require dirname(__DIR__) . '/vendor/autoload.php';
$cmd = new Commando\Command();
$cmd->beepOnError();
$cmd->option('-r')->require();
echo "Argument -r: " . $cmd['-r'] . PHP_EOL;
Пример #21
0
    echo "ERROR({$errno}) at {$errfile}:{$errline}, {$errstr}\n";
    exit(1);
});
require_once __DIR__ . '/vendor/autoload.php';
foreach ($_SERVER['argv'] as &$token) {
    // this is dirty patch.
    // PHP will add return-path(-f) option that like as `-fjhondoe@example.com`.
    // commando library can handle `-f jhondoe@...`, BUT can't `-fjhondoe@...` .
    if (preg_match('/^\\-f.+@/u', $token)) {
        $token = preg_replace('/^\\-f/', '-f ', $token);
    }
}
// default
define('DEFAULT_OUTPUT_FILENAME', '/tmp/mail.eml');
// parse params
$cmd = new Commando\Command();
$cmd->option('f')->aka('return_path')->describedAs('return-path addr.')->default('NO_RETURN_PATH');
$cmd->option('o')->aka('output_filename')->default(DEFAULT_OUTPUT_FILENAME)->describedAs('output file name, require base dir.')->must(function ($path) {
    $dir = basename($path);
    return file_exists($dir) && filetype($dir) === 'dir';
});
$cmd->option('n')->aka('no_file_output')->describedAs('no file output')->boolean();
$cmd->option('t')->aka('through_stdout')->describedAs('through stdout')->boolean();
$cmd->option('a')->aka('append')->describedAs('append output.(erase before output, when not append on.)')->boolean();
// read stdin
$raw = file_get_contents('php://stdin');
// TODO: beauty parse.
// write
if (!$cmd['no_file_output']) {
    file_put_contents($cmd['output_filename'], $raw, $cmd['append'] ? FILE_APPEND : null);
}