A collection of tools to help with PHP command line utilities

Overview

PHP Command Line Tools

Build Status

A collection of functions and classes to assist with command line development.

Requirements

  • PHP >= 5.3

Suggested PHP extensions

  • mbstring - Used for calculating string widths.

Function List

  • cli\out($msg, ...)
  • cli\out_padded($msg, ...)
  • cli\err($msg, ...)
  • cli\line($msg = '', ...)
  • cli\input()
  • cli\prompt($question, $default = false, $marker = ':')
  • cli\choose($question, $choices = 'yn', $default = 'n')
  • cli\menu($items, $default = false, $title = 'Choose an Item')

Progress Indicators

  • cli\notify\Dots($msg, $dots = 3, $interval = 100)
  • cli\notify\Spinner($msg, $interval = 100)
  • cli\progress\Bar($msg, $total, $interval = 100)

Tabular Display

  • cli\Table::__construct(array $headers = null, array $rows = null)
  • cli\Table::setHeaders(array $headers)
  • cli\Table::setRows(array $rows)
  • cli\Table::setRenderer(cli\table\Renderer $renderer)
  • cli\Table::addRow(array $row)
  • cli\Table::sort($column)
  • cli\Table::display()

The display function will detect if output is piped and, if it is, render a tab delimited table instead of the ASCII table rendered for visual display.

You can also explicitly set the renderer used by calling cli\Table::setRenderer() and giving it an instance of one of the concrete cli\table\Renderer classes.

Tree Display

  • cli\Tree::__construct()
  • cli\Tree::setData(array $data)
  • cli\Tree::setRenderer(cli\tree\Renderer $renderer)
  • cli\Tree::render()
  • cli\Tree::display()

Argument Parser

Argument parsing uses a simple framework for taking a list of command line arguments, usually straight from $_SERVER['argv'], and parses the input against a set of defined rules.

Check examples/arguments.php for an example.

Usage

See examples/ directory for examples.

Todo

  • Expand this README
  • Add doc blocks to rest of code
Comments
  • Incorrect table column width with multibyte text.

    Incorrect table column width with multibyte text.

    Incorrect table column width with multibyte text. I added a test for this problem so it will be failed.

    The output is like following.

    array(8) {
      [0]=>
      string(79) "+----------------------------------------------------------------+------------+"
      [1]=>
      string(79) "| Field                                                          | Value      |"
      [2]=>
      string(79) "+----------------------------------------------------------------+------------+"
      [3]=>
      string(208) "| この文章はダミーです。文字の大きさ、量、字間、行間等を確認するために入れています。この文章はダミーです。文字の大きさ、量、字 | こんにちは |"
      [4]=>
      string(131) "| 間、行間等を確認するために入れています。この文章はダミーです。文字の大きさ、 |            |"
      [5]=>
      string(79) "| Lorem Ipsum is simply dummy text of the printing and typesetti | Hello      |"
      [6]=>
      string(79) "| ng industry.                                                   |            |"
      [7]=>
      string(79) "+----------------------------------------------------------------+------------+"
    }
    

    I am trying to fix this problem, but I haven't find a cause for now. Are there any hints?

    opened by miya0001 16
  • Adds fallback for mb_strlen, fixes #61

    Adds fallback for mb_strlen, fixes #61

    Adds a function_exists check for mb_strlen() and will use php's strlen() in place of mb_strlen(). Addresses issues with PHP installations that do not have the non-default mbstring extension enabled.

    bug 
    opened by jesseoverright 12
  • Adding a hiding option to \cli\prompt

    Adding a hiding option to \cli\prompt

    I was trying to create a prompt for passwords, and those are the changes I needed.

    Sorry if the code style is not what you're used to, but honestly I found the original style quite confusing, so I did my best.

    I tested it using PuTTY and noticed some weird behaviour, like in the screenshot below, but it looks more like a bug in the program, since after a clear it does not happen.

    capture

    enhancement scope:shell 
    opened by igorsantos07 12
  • Colors in table

    Colors in table

    Hi,

    I know you havent touched this for some time, but its aweome! Just one question/request, how do I combine colors with the table? Id like colored text in the table. It does work, but extra characters for the color coding mess up the table layout. Thanks!

    opened by R5fan 11
  • Use grapheme_substr & pcre_match in safe_substr for #117. Ascii::columns fix.

    Use grapheme_substr & pcre_match in safe_substr for #117. Ascii::columns fix.

    Issue https://github.com/wp-cli/php-cli-tools/issues/117

    Uses grapheme_substr() and preg_match() in safe_substr() (and grapheme_strlen() and preg_match_all() in safe_strlen()) to deal with combining characters correctly, in a manner similar to that in strwidth().

    Refactors the East Asian Width stuff into a function _safe_substr_eaw() and adds can_use_pcre_x() helper to check for PCRE \X availability.

    Removes use of iconv() as it varies widely over PHP versions and isn't easily tested and wasn't that useful anyway.

    Incorporates the test data from @ShinichiNishikawa.

    Fixes a gatepost error in Ascii::setWidths().

    Also tries stty as well in Shell::columns() as relying on the env var COLUMNS as introduced by me in https://github.com/wp-cli/php-cli-tools/pull/113 turns out not to be that great as it's not normally exported. Sigh.

    Edit: had to add an ICU check function to guard against the old 4.8.1.1 version on Travis (all PHP versions) flaking out - chose 54.1 as min which is Unicode 7.0 and fairly modern.

    Also added "phpunit6-compat.php" from core (as introduced by @miya0001 in https://core.trac.wordpress.org/ticket/39822), modded to remove the getTickets(), and PHP 7.0 & 7.1 to the Travis build, and some php info and the --debug switch on phpunit.

    bug 
    opened by gitlost 9
  • Use HTML-like syntax instead of own custom one

    Use HTML-like syntax instead of own custom one

    What I mean is to replace:

    %ySomething yellow%n
    

    with:

    <y>Something yellow</y>
    

    Benefits:

    • easier and more familiar to read, since there is no ySomething and similar things, at the end of the day we are all well trained to read HTML:)
    • IDE usually supports HTML within string literals, so it will be:
      • automatically highlighted
      • possible to fold blocks of text
      • working with autocomplete of closing such "tags"
      • working with spellchecking
      • so on...
    • there are numerous HTML parsers that can be used to pre/post-process such strings or strip HTML tags from string

    I've implemented such approach in very basic form here: https://github.com/nazar-pc/phpt-tests-runner/blob/master/bin/phpt-tests-runner#L284 Even GitHub is capable to automatically highlight it in a basic form :smile:

    opened by nazar-pc 9
  • Fixed the 'No arg value warning' when an option is passed with no value ...

    Fixed the 'No arg value warning' when an option is passed with no value ...

    ...as the last arg.

    This is a fix for https://github.com/wp-cli/php-cli-tools/issues/77 This code takes care of the case where the last option passed has no value. The warning will be thrown as well.

    literally it is a simplified version of:

    if ($this->_lexer->end() || (!$this->_lexer->end() && !$this->_lexer->peek->isValue)) {
        //...
    }
    
    bug 
    opened by rantonmattei 7
  • Optimize double-width safe_substr when all double-width.

    Optimize double-width safe_substr when all double-width.

    Related https://github.com/wp-cli/php-cli-tools/pull/111

    Looking at the @miya0001's test table at https://github.com/wp-cli/php-cli-tools/pull/111#pullrequestreview-52207165 it struck me that most of the time a column with double-width chars will have a number of entries with double-width content only, which suggests this simple optimization which checks for this using a preg_match_all() and just halves the length if so.

    Crude benchmarking suggests a performance win if the percentage of such entries is above 10% or so, and only a small (2%) penalty if it's less than that, and a major win (100s of %) if it's anything above 50%, which I'm guessing is most likely to be the case - @miya0001 could you comment on whether this is likely in your experience for real data?

    enhancement scope:table 
    opened by gitlost 6
  • Cron, posix_isatty and STDOUT

    Cron, posix_isatty and STDOUT

    when running under cron and automating some task, my log keeps on throwing in:

    production.ERROR: exception 'ErrorException' with message 'Use of undefined constant STDOUT - assumed 'STDOUT'' in /var/www/seat-ec/vendor/wp-cli/php-cli-tools/lib/cli/Shell.php:57

    I've been looking for several day's to get this fixed or getting a satisfied solution but the results are null to not helping. Perhaps you might be able to help me solving this issue.

    CentOS 6.5, Easyapache with php 5.4 STDOUT is a TTY output to what's told.

    state:unconfirmed 
    opened by DGTnt 6
  • setRenderer doesn't work

    setRenderer doesn't work

    When I use: $table->setRenderer(new \cli\table\Ascii([80, 20, 20])) or I change array values into Ascii this doesn't work, table doesn't rendered.

    $table = new \cli\Table(); $table->setHeaders($headers); $table->setRows($results); $table->setRenderer(new \cli\table\Ascii([80, 20, 20])); $table->display();

    Please any help I pleasure it.

    captura

    bug 
    opened by joerecra 5
  • Colors::colorize removes sprintf flags on windows

    Colors::colorize removes sprintf flags on windows

    I'm using the script on windows, and shouldColorize returns false, so the following lines strips all sprintf flags:

    $return = preg_replace('/%((%)|.)/', '$2', $string);
    

    Causes cli\menu() to show a list of dots instead of the choices.

    bug 
    opened by Korri 5
  • Fix unexpected test failure in test_strwidth()

    Fix unexpected test failure in test_strwidth()

    In https://github.com/wp-cli/php-cli-tools/pull/155, we marked a test skipped 217cb51 because it was unexpectedly failing.

    We should track down why it was failing, and restore the test.

    Done is:

    • $this->markTestSkipped() is removed from the test.
    bug scope:testing 
    opened by danielbachhuber 1
  • Wrong expected total time in progress bar when make_progress_bar used multiple times

    Wrong expected total time in progress bar when make_progress_bar used multiple times

    Using make_progress_bar multiple times in a WP_CLI command displays wrong expected total time after the first use.

    Repro:

    Consider the following cli command

    class TestMultipleProgressBars {
        private function run($message) {
            $progress = \WP_CLI\Utils\make_progress_bar($message, 10);
            $i = 10;
            while ($i-- >= 0) {
                sleep(1);
                $progress->tick();
            }
            $progress->finish();
            $progress->reset();
            unset($progress);
        }
        public function multiple_progress_bars() {
            $this->run('1st pass');
            $this->run('2nd pass');
            $this->run('3rd pass');
        }
    }
    WP_CLI::add_command('test', 'TestMultipleProgressBars');
    

    running this results in the following STDOUT output

    $ wp test multiple_progress_bars
    1st pass  100% [====================================] 0:10 / 0:10
    2nd pass  100% [====================================] 0:10 / 0:21
    3rd pass  100% [====================================] 0:10 / 0:32
    

    The expected result should read 0:10 as the expected time for the 2nd and 3rd pass. The numbers shown during the execution are also wrong, calculating a much higher time when each subsequent pass starts.

    This is due to the usage of static function variables in php-cli-tools lib/cli/Notify.php

    	public function speed() {		
                  static $tick, $iteration = 0, $speed = 0;
    

    The fix would be to convert those as member variables of the class, or somehow reset them when the Reset method is called.

    opened by ctzkane 0
  • Fix type hinting for prompt function

    Fix type hinting for prompt function

    I was confused by phpstan analyse output: "Parameter #2 $default of function cli\prompt expects string, false given." Soon I found out that problem is in type hinting for this function in lib/cli/cli.php. Hope my fix is helpful.

    opened by valeriySeregin 0
  • Broken table layout when reporting WordPress vulnerabilities.

    Broken table layout when reporting WordPress vulnerabilities.

    Hi,

    Running wp vuln status through WordPress 4.9.6 breaks the table layout when the package reports any vulnerabilities with WordPress version (not plugins, not themes. See screenshots).

    Expected behavior:

    Table layout is not broken. Expected to see the same layout as it is with the reports of plugins and themes.

    Current behavior:

    The table layout breaks.

    Steps to reproduce:

    Run wp-vulnerability scanner through a WordPress 4.9.6 install 1.- wp vuln status

    WP-CLI version: 2.0.0-alpha-2646dac

    Screenshots:

    Layout broken when reporting problems with WordPress 4.9.6: vuln1

    Layout is fine when reporting no vulnerabilities with WordPress 4.9.7 vuln2

    It seems like it has been a recurring issue (https://github.com/wp-cli/php-cli-tools/issues/106)

    Thank you!

    state:unconfirmed scope:table 
    opened by oscarssanchez 3
  • Progress bar goes to new line under windows

    Progress bar goes to new line under windows

    The progressbar instead of updating the current row print a new row with the updated values.

    To fix this I've found that can be esily fixed by changing into Bar.php line 58 from

    $size = Shell::columns();

    to

    $size = Shell::columns() - 1;

    If it was ok as I fix I can also make a pull request for it.

    Currently I've not tested it under others OS.

    bug scope:shell 
    opened by marcovalloni 4
  • sprintf(): Too few arguments

    sprintf(): Too few arguments

    Can't really figure this one out. Sometimes (not often, but often enough to end up in my logs and irritate me) \cli\line() causes a warning: sprintf(): Too few arguments.

    This is the offending line:

    \cli\line("[%C%k%s%N] Starting!", date("Y-m-d H:i:s"));
    

    Can't really see how the argument to sprintf() gets lost here, but obv it does.

    environment: php5.6.33 (with mbstring) on debian, php-cli-tools v0.11.8.

    Logfile trace:

    in function LoggingErrorHandler::handleError
    in function call_user_func in /foo/include/classes/LoggingErrorHandler.php on line 402
    in function LoggingErrorHandler::{closure}
    in function sprintf
    in function call_user_func_array in /foo/include/deps/wp-cli/php-cli-tools/lib/cli/Streams.php on line 48
    in function cli\Streams::render
    in function call_user_func_array in /foo/include/deps/wp-cli/php-cli-tools/lib/cli/Streams.php on line 13
    in function cli\Streams::_call in /foo/include/deps/wp-cli/php-cli-tools/lib/cli/Streams.php on line 68
    in function cli\Streams::out
    in function call_user_func_array in /foo/include/deps/wp-cli/php-cli-tools/lib/cli/Streams.php on line 13
    in function cli\Streams::_call in /foo/include/deps/wp-cli/php-cli-tools/lib/cli/Streams.php on line 95
    in function cli\Streams::line
    in function call_user_func_array in /foo/include/deps/wp-cli/php-cli-tools/lib/cli/Streams.php on line 13
    in function cli\Streams::_call in /foo/include/deps/wp-cli/php-cli-tools/lib/cli/cli.php on line 62
    in function cli\line in /foo/bin/my_foobar_script.php on line 35
    
    bug scope:colors 
    opened by nahkampf 2
Releases(v0.11.16)
Owner
WP-CLI
The command line interface for WordPress
WP-CLI
A set of tools for lexical and syntactical analysis written in pure PHP.

Welcome to Dissect! master - this branch always contains the last stable version. develop - the unstable development branch. Dissect is a set of tools

Jakub Lédl 221 Nov 29, 2022
Skeleton Application for Laminas API Tools

Laminas API Tools Skeleton Application Requirements Please see the composer.json file. Installation Via release tarball Grab the latest release via th

Laminas API Tools 43 Dec 8, 2022
Analyze PHP code with one command

PHPQA Analyze PHP code with one command. Requirements PHP >= 5.4.0 xsl extension for HTML reports Why? Every analyzer has different arguments and opti

edgedesign/phpqa 542 Dec 24, 2022
A package to help you clean up your controllers in laravel

?? Laravel Terminator ?? ?? "Tell, don't ask principle" for your laravel controllers What this package is good for ? Short answer : This package helps

Iman 241 Oct 10, 2022
PHPMD is a spin-off project of PHP Depend and aims to be a PHP equivalent of the well known Java tool PMD. PHPMD can be seen as an user friendly frontend application for the raw metrics stream measured by PHP Depend.

PHPMD PHPMD is a spin-off project of PHP Depend and aims to be a PHP equivalent of the well known Java tool PMD. PHPMD can be seen as an user friendly

PHP Mess Detector 2.1k Jan 8, 2023
A PHP parser written in PHP

PHP Parser This is a PHP 5.2 to PHP 8.0 parser written in PHP. Its purpose is to simplify static code analysis and manipulation. Documentation for ver

Nikita Popov 15.9k Jan 3, 2023
A PHP VM implementation in PHP

PHPPHP A PHP VM implementation written in PHP. This is a basic VM implemented in PHP using the AST generating parser developed by @nikic To see what's

Anthony Ferrara 801 Dec 25, 2022
PHP Architecture Tester - Easy to use architectural testing tool for PHP :heavy_check_mark:

Easy to use architecture testing tool for PHP Introduction ?? PHP Architecture Tester is a static analysis tool to verify architectural requirements.

Carlos A Sastre 765 Dec 30, 2022
Provides functionality that helps writing PHP code that has runtime-specific (PHP / HHVM) execution paths

sebastian/environment This component provides functionality that helps writing PHP code that has runtime-specific (PHP / HHVM) execution paths. Instal

Sebastian Bergmann 6.5k Jan 3, 2023
Search PHP source code for function & method calls, variables, and more from PHP.

Searching PHP source code made easy Search PHP source code for function & method calls, variable assignments, classes and more directly from PHP. Inst

Permafrost Software 22 Nov 24, 2022
A full-scale PHP sandbox class that utilizes PHP-Parser to prevent sandboxed code from running unsafe code

A full-scale PHP 7.4+ sandbox class that utilizes PHP-Parser to prevent sandboxed code from running unsafe code. It also utilizes FunctionParser to di

Corveda 192 Dec 10, 2022
A tool to automatically fix PHP Coding Standards issues

PHP Coding Standards Fixer The PHP Coding Standards Fixer (PHP CS Fixer) tool fixes your code to follow standards; whether you want to follow PHP codi

null 11.6k Jan 3, 2023
PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.

About PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a define

Squiz Labs 9.9k Jan 4, 2023
PHP Static Analysis Tool - discover bugs in your code without running it!

PHPStan - PHP Static Analysis Tool PHPStan focuses on finding errors in your code without actually running it. It catches whole classes of bugs even b

PHPStan 11.6k Dec 30, 2022
Phan is a static analyzer for PHP. Phan prefers to avoid false-positives and attempts to prove incorrectness rather than correctness.

Phan is a static analyzer for PHP that prefers to minimize false-positives. Phan attempts to prove incorrectness rather than correctness. Phan looks f

null 5.4k Jan 7, 2023
A PHP code-quality tool

GrumPHP Sick and tired of defending code quality over and over again? GrumPHP will do it for you! This composer plugin will register some git hooks in

PHPro 3.9k Jan 1, 2023
Beautiful and understandable static analysis tool for PHP

PhpMetrics PhpMetrics provides metrics about PHP project and classes, with beautiful and readable HTML report. Documentation | Twitter | Contributing

PhpMetrics 2.3k Dec 22, 2022
A tool for quickly measuring the size of a PHP project.

PHPLOC phploc is a tool for quickly measuring the size and analyzing the structure of a PHP project. Installation This tool is distributed as a PHP Ar

Sebastian Bergmann 2.3k Jan 4, 2023
Copy/Paste Detector (CPD) for PHP code.

PHP Copy/Paste Detector (PHPCPD) phpcpd is a Copy/Paste Detector (CPD) for PHP code. Installation This tool is distributed as a PHP Archive (PHAR): $

Sebastian Bergmann 2.2k Jan 1, 2023