Lovely PHP wrapper for using the command-line

Overview

ShellWrap

What is it?

It's a beautiful way to use powerful Linux/Unix tools in PHP. Easily and logically pipe commands together, capture errors as PHP Exceptions and use a simple yet powerful syntax. Works with any command line tool automagically.

Features

  • Flexible and sexy syntax.
  • Exceptions are thrown if the executable returns an error.
  • Paths to binaries are automatically resolved.
  • All arguments are properly escaped.
  • Callback functions for streaming output.

Examples

<?php 
require_once 'vendor/autoload.php';
use MrRio\ShellWrap as sh;

// List all files in current dir
echo sh::ls();

// Checkout a branch in git
sh::git('checkout', 'master');

// You can also pipe the output of one command, into another
// This downloads example.com through cURL, follows location, then pipes through grep to 
// filter for 'html'
echo sh::grep('html', sh::curl('http://example.com', array(
	'location' => true
)));

// Touch a file to create it
sh::touch('file.html');

// Remove file
sh::rm('file.html');

// Remove file again (this fails, and throws an exception because the file doesn't exist)

try {
	sh::rm('file.html');
} catch (ShellWrapException $e) {
	echo 'Caught failing sh::rm() call';
}


// This throws an exception, as 'invalidoption' is not a valid argument
try {
	echo sh::ls(array('invalidoption' => true));
} catch (ShellWrapException $e) {
	echo 'Caught failing sh::ls() call';
}

// Commands can be written multiple ways
sh::git('reset', array('hard' => true), 'HEAD');
sh::git('reset', '--hard', 'HEAD');
sh::git(array('reset', '--hard', 'HEAD'));

// Arguments passed in are automatically escaped, this expands to
// date --date '2012-10-10 10:00:00'
echo sh::date(array(
	'date' => '2012-10-10 10:00:00'
));

// If arg keys are one letter, is assumes one dash prefixing it
// date -d '2012-10-10 10:00:00'
echo sh::date(array(
	'd' => '2012-10-10 10:00:00'
));


?>

Example: Tailing a file and adding timestamps to output

You can stream the output of a command into a callback function. For example:

sh::tail('-f log', function($in) {
	echo "\033[32m" . date('Y-m-d H:i:s') . "\033[39m " . $in;
});

Make sure the file 'log' exists. This will output a timestamp, and the input. Try echoing into the log file.

The escape codes are to add a little colour to the terminal.

Interactive Shell

ShellWrap also ships with an interactive shell mode. You can access this by typing:

./bin/shellwrap

Warning

Don't use any user inputted data with these commands. Even with very paranoid filtering, you can't know all the potential pitfalls of each command you're using. Use your noggin.

Acknowledgements

Inspired by the Python project sh by Andrew Moffat

Comments
  • Original namespace

    Original namespace

    I'm using this wrapper for myself. I've created a composer package installable from packagist.org. I've created this branch to keep your namespace and contribute my changes. If you want them. Here is what I did:

    • added .gitignore
    • made it psr-0 compatible
    • ready to add to packagist.org
    • passed through php-cs-fixer (minor fixes, indentation, etc)
    • moved ShellWrap.php to src/MrRio for autoloading
    • moved examples to new directory
    • added LC_ALL=en_US to testDate() to avoid error in non-english environment

    NOTE: The diff on ShellWrap is the complete file due to directory changes..

    opened by guumaster 2
  • specify current working directory explicitly when executing shell commands

    specify current working directory explicitly when executing shell commands

    If you use function chdir() to change working directory to a different directory first, following two statements should still return same directories. However, in Travis CI they return different directories back (the 2nd one returns the directory where the PHP script was invoked).

    1. getcwd()
    2. (string) ShellWrap::pwd()

    Thus we need to have the 4th parameter (getcwd()) specified explicitly here, also ideally it's unnecessary.

    opened by deminy 0
  • Magic method __toString() must return a string

    Magic method __toString() must return a string

    In some PHP IDE (e.g., PhpStorm) you may see that method _\MrRio\ShellWrap::_toString() is highlighted with notification saying

    __toString() method must return a string

    This could be triggered with following code piece where no actual shell command invoked:

    <?php
    require_once __DIR__ . '/vendor/autoload.php';
    
    echo (new MrRio\ShellWrap());
    ?>
    

    Although in reality people may not make method calls like that, it's better to get it fix to make variables consistent. Property \MrRio\ShellWrap::$output should be initialized and used as a string but not an array, as in the fix.

    opened by deminy 0
  • Composer >1.3.0 compatibility

    Composer >1.3.0 compatibility

    I've opened an issue against Boris here, however, I am also going open an issue here for anyone else experiencing this. When using shell wrap with a composer version >1.3.0, PHP gets reloaded to disable XDebug and causes an error to be thrown in the terminal. E.g.,

    PHP Warning:  Module 'pcntl' already loaded in Unknown on line 0
    
    Warning: Module 'pcntl' already loaded in Unknown on line 0
    

    As Boris is only used for the interactive debugger, is there any chance of a workaround? Boris hasn't had any commits or changes in years, maybe Psysh would be a good drop-in replacement?

    opened by barchard 1
  • Skip saving output to variable when using callback function

    Skip saving output to variable when using callback function

    My case is currently that I'm streaming use log files using sh::cat() and using a callback closure to pass the data (after a filter) to an PHPExcel object. The log files can easily get over 500MB. Looking through the code it seems that even when using a callback/closure, the output of the cat command still gets saved to a variable, making memory usage go up and up.

    I cannot grep on the log files as it's filled with IDs, possible conflicting with other data in the same line.

    Is this currently possible in a less memory consuming way? Else I'm also willing to submit a PR with some extra functionality on this. Reasoning could be that when streaming through a closure, no need is left to save things to the self::$output variable.

    opened by stefandoorn 0
  • Alternative piping syntax

    Alternative piping syntax

    echo sh::grep('html', sh::curl('http://example.com', array(
        'location' => true
    )));
    

    In current API I don't like 2 things:

    1. inverted order of commands (grep -> curl) when actually curl | grep is intended
    2. "wrap" or functional style a(b(c()))

    It would be nice to have fluid API like this

    sh::curl('http://example.com')->pipe('grep', 'html')->pipe('whatever');
    

    or

    sh::curl('http://example.com')->sh('grep', 'html')->sh('whatever');
    

    or

    sh::curl('http://example.com')->grep('html')->whatever();
    

    @MrRio what do you think?

    opened by Mihailoff 1
Releases(0.4.1)
Owner
James Hall
James Hall
PHP Interminal is a command-line tool that gives you access to PHP Internals discussions in your terminal.

PHP Interminal is a command-line tool that gives you access to PHP Internals discussions in your terminal. ??

Nuno Maduro 32 Dec 26, 2022
A PHP library for command-line argument processing

GetOpt.PHP GetOpt.PHP is a library for command-line argument processing. It supports PHP version 5.4 and above. Releases For an overview of the releas

null 324 Dec 8, 2022
Patrol is an elegant command-line tool that keeps your PHP Project's dependencies in check.

Patrol is an elegant command-line tool that keeps your PHP Project's dependencies in check. Installation / Usage Requires PHP 8.0+ First, install Patr

Nuno Maduro 237 Nov 14, 2022
Twitter raffles in the command line, with PHP and minicli

Rafflebird Rafflebird is a highly experimental CLI application for giveaways / raffles on Twitter, built in PHP with Minicli. Disclaimer: The recent s

Erika Heidi 33 Nov 16, 2022
A PHP command line tool used to install shlink

Shlink installer A PHP command line tool used to install shlink. Installation Install this tool using composer.

null 8 Nov 3, 2022
Command-line control panel for Nginx Server to manage WordPress sites running on Nginx, PHP, MySQL, and Let's Encrypt

EasyEngine v4 EasyEngine makes it greatly easy to manage nginx, a fast web-server software that consumes little memory when handling increasing volume

EasyEngine 2k Jan 4, 2023
Generic PHP command line flags parse library

PHP Flag Generic PHP command line flags parse library Features Generic CLI options and arguments parser. Support set value data type(int,string,bool,a

PHP Toolkit 23 Nov 13, 2022
A simple command-line tool whose aim is to facilitate the continous delivery of PHP apps

Deployer Simple command-line tool that aims to facilitate the continous delivery of PHP apps, particularly Laravel apps. Imagine you want to update yo

Fernando Bevilacqua 4 Sep 8, 2021
🍃 In short, it's like Tailwind CSS, but for the PHP command-line applications.

Termwind Termwind allows you to build unique and beautiful PHP command-line applications, using the Tailwind CSS API. In short, it's like Tailwind CSS

Nuno Maduro 1.8k Dec 30, 2022
A PHP Command Line tool that makes it easy to compile, concat, and minify front-end Javascript and CSS/SCSS dependencies.

Front End Compiler A PHP Command Line tool that makes it easy to compile, concat, and minify front-end Javascript and CSS/SCSS dependencies. The minif

Happy Medium 2 Nov 12, 2021
php command line script to DCA crypto from Coinbase Pro

dca.php A simple php script designed to be run via the command line via a cron job. This will connect to coinbase pro and buy the crypto coins specifi

Ben Suffolk 2 Oct 22, 2021
A PHP library for command-line argument processing

GetOpt.PHP GetOpt.PHP is a library for command-line argument processing. It supports PHP version 7.1 and above. Releases For an overview of the releas

null 324 Dec 8, 2022
BetterWPCLI - a small, zero-dependencies, PHP library that helps you build enterprise WordPress command-line applications.

BetterWPCLI - a small, zero-dependencies, PHP library that helps you build enterprise WordPress command-line applications.

Snicco 5 Oct 7, 2022
Command-Line Interface tools

Aura.Cli Provides the equivalent of request ( Context ) and response ( Stdio ) objects for the command line interface, including Getopt support, and a

Aura for PHP 102 Dec 31, 2022
Another Command Line Argument Parser

Optparse — Another Command Line Argument Parser Install 1. Get composer. 2. Put this into your local composer.json: { "require": { "chh/optparse

Christoph Hochstrasser 18 Nov 1, 2019
👨🏻‍🚀 A command-line tool that gives you the Alpine Day 2021 schedule in your timezone. 🚀

Alpine Day Schedule a command-line tool that gives you the Alpine Day 2021 schedule in your timezone. ?? Quick start Requires PHP 7.4+ # First, instal

Nuno Maduro 11 Jun 10, 2021
A command line code generator for Drupal.

Drupal Code Generator A command line code generator for Drupal. Installation Download the latest stable release of the code generator.

Ivan 227 Dec 14, 2022
Laracon Schedule a command-line tool that gives you the Laracon Online schedule in your timezone.

Laracon Schedule a command-line tool that gives you the Laracon Online schedule in your timezone. ?? Quick start Requires PHP 7.4+ # First, install: c

Nuno Maduro 101 Sep 16, 2022
Simple command-line tool to access HiWeb account information

Simple command-line tool to access HiWeb account information.

Milad Nekofar 2 Dec 26, 2022