Coder Social home page Coder Social logo

asika32764 / php-simple-console Goto Github PK

View Code? Open in Web Editor NEW
21.0 4.0 1.0 10 KB

Single file CLI framework to help you write build scripts.

Home Page: https://packagist.org/packages/asika/simple-console

PHP 100.00%
cli console cli-app console-application cli-framework console-framework stdin argument-parser argv

php-simple-console's Introduction

PHP Simple Console

Single file console framework to help you write build scripts.

Installation

Use composer:

composer require asika/simple-console

Or downlaod single file to use: Download Here

Getting Started

Use closure

#!/bin/sh php
<?php
// Include single file
include_once __DIR__ . '/Console.php';

// Or use composer
include_once __DIR__ . '/vendor/autolod.php';

$app = new \Asika\SimpleConsole\Console;

// Use closure
$app->execute(function (\Asika\SimpleConsole\Console $app)
{
    // PHP 5.3
    $app->out('Hello');

    // PHP 5.4 or higher use $this
    $this->out('Hello');

    // Return TRUE will auto convert to 0 exitcode.
    return true;
});

Or Create your own class.

class Build extends \Asika\SimpleConsole\Console
{
    protected $help = <<<HELP
[Usage] php build.php <version>

[Options]
    h | help   Show help information
    v          Show more debug information.
HELP;

    protected function doExecute ()
    {
        $this->out('Hello');

        // Return TRUE will auto convert to 0 exitcode.
        return true;
    }
}

$app = new Build;
$app->execute();

Show HELP

Add -h or --help to show usage, you can add custom usage to $this->help, or override $this->getHelp().

If you want to change h and help option, override $this->helpOptions = array('...').

Handle Error

Just throw Exception in doExecute(), Console will auto catch error.

throw new \RuntimeException('...');

Add -v to show backtrace if error.

Handle Wrong Arguments

Wrong Argument use \Asika\SimpleConsole\CommandArgsException

$arg = $this->getArgument(0);

if (!$arg)
{
    throw new \Asika\SimpleConsole\CommandArgsException('Please enter a name.');
}

Console will auto show help information.

[Warning] Please enter a name.

[Usage] console.php <name>

[Options]
    h | help   Show help info.
    v          Show more debug information.

Multiple Commands

Use delegate() to delegate to different methods.

//...

    protected function doExecute()
    {
        return $this->delegate($this->getArgument(0));
    }

    protected function foo()
    {
        $this->getArgument(1); // bar
    }

    protected function baz()
    {
        // ...
    }

Now you can add sub commands

php console.php foo bar
php console.php baz

If you want to strip first argument after delgated, you can follow this code:

$this->delegate(array_shift($this->args));

Now can use getArgument(0) in sub method and ignore the first command name.

The is another way:

$command = array_shift($this->args);

$this->delegate($command, ...$this->args);
protected function foo($first, $second = null)
{
}

API

getArgument($order[, $default = null])

$first = $this->getArgument(0, 'default value');

setArgument($order, $$value)

$this->setArgument(1, 'value');

getOption($name: array|string[, $default = null])

Get option --foo

$this->getOption('foo');

Get option -f or --foo, first match will return.

$this->getOption(array('f', 'foo'));

NOTE: -abc will convert to a => 1, b => 1, c => 1 And -vvv will convert to v => 3

setOption($name, $value)

Set otpion to toption list. $name also support array.

out($string[, $newline: bool = false])

Write to STDOUT,

$this->out('Hello')->out('World');

err($string[, $newline: bool = false])

Write to STDERR

$this->err('Hello')->err('World');

in($string[$default = null, $bool = false)

Ask a question, read from STDIN

$un = $this->in('Please enter username: ', 'default_name');

Read as boolean, add true to third argument:

$bool = $this->in('Are you sure? [Y/n]', [default true/false], true);
  • yes, y, 1, true will convert to TRUE
  • no, n, 0, false will convert to FALSE

exec($cmd)

A proxy to execute a cmd by exec() and return value.

It will add a title >> {your command} before exec so you will know what has been executed.

php-simple-console's People

Contributors

asika32764 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

php-simple-console's Issues

Tip: $_SERVER['argv'] ignores well-formed URLs as last argument

See: https://forum.friendi.ca/display/ec054ce7255abe539d63ace362184392

Further test revealed that when a CLI script is called with a fully-formed URL as the last argument, $_SERVER['argv'] won't pick it up while $argv does.

script.php

#!/usr/bin/env php
<?php
var_dump($_SERVER['argv']);
var_dump($argv);

$> php script.php test http://example.com
Output:

array (
  0 => 'script.php',
  1 => 'test ',
)
array (
  0 => 'script.php',
  1 => 'test ',
  2 => 'http://example.com'
)

The Console::parseArgv gets passed $_SERVER['argv'] by default, so the Console wouldn't pick on on the argument as well. Here's the workaround I used:

#!/usr/bin/env php
<?php
require_once 'vendor/autoload.php';

// (new \Asika\SimpleConsole\Console())->execute();
(new \Asika\SimpleConsole\Console($argv))->execute();

I'm not sure if and how it can be fixed but for anyone else wondering the workaround might be useful.

Suggestion: Ignore single-letter option values by default

Hi and thanks for this gem of a library that I started using over at https://github.com/friendica/friendica. While it does mostly a good job parsing the command-line separating arguments and options, the order is often critical to get the intended result.

For example with an example bin/console:

bin/console command -p
Arguments:

  • "command"

Options:

  • p: 1

But if the order is reversed the result is completely different:

bin/console -p command
Arguments: none

Options:

  • p: "command"

I'd like to suggest to ignore values for single-letter options and add the possibility to declare specific options that actually expect a value.

What do you think about it?

Iterations calling the count function

Hi there,

A small question. Looking at the Friendica source I see they are using your Console.php code. There is however one spot in the Console.php file where a count is being used instead of calculating the array with a predefined var.

The old code:

   protected function parseArgv($argv)
    {
        $this->executable = array_shift($argv);
        $key = null;
        $out = array();
        for ($i = 0, $j = count($argv); $i < $j; $i++) {

This is a bit faster

   protected function parseArgv($argv)
    {
        $this->executable = array_shift($argv);
        $key = null;
        $out = array();
        $num_argv = count($argv);

        for ($i = 0, $j = $num_argv; $i < $j; $i++) {

Would you be willing to change this in the project code so we can use a new version of it? It prevents calling the count function for each iteration.

Thanks,

Hans

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.