laminas/laminas-stdlib
Utility components for PHP from the Laminas project: data structures, array and string helpers, hydrators, validators, option objects, and more. A shared toolbox used across Laminas and usable standalone in any PHP application.
Writing one-off scripts or vendor binaries for a package is often problematic:
STDOUT for meaningful, expected outputSTDERR for error messagesPHP_EOLLaminas\Stdlib\ConsoleHelper helps to address the second major bullet point and
all beneath it in a minimal fashion.
Typical usage is to instantiate a ConsoleHelper, and call one of its methods:
use Laminas\Stdlib\ConsoleHelper;
$helper = new ConsoleHelper();
$helper->writeLine('This is output');
You can optionally pass a PHP stream resource to the constructor, which will be used to determine whether or not color support is available:
$helper = new ConsoleHelper($stream);
By default, it assumes STDOUT, and tests against that.
ConsoleHelper provides the following methods.
colorize(string $string) : stringcolorize() accepts a formatted string, and will then apply ANSI color
sequences to them, if color support is detected.
The following sequences are currently supported:
<info>...</info> will apply a green color sequence around the provided text.<error>...</error> will apply a red color sequence around the provided text.You may mix multiple sequences within the same stream.
write(string $string, bool $colorize = true, resource $stream = STDOUT) : voidEmits the provided $string to the provided $stream (which defaults to
STDOUT if not provided). Any EOL sequences are convered to PHP_EOL. If
$colorize is true, the string is first passed to colorize() as well.
writeLine(string $string, bool $colorize = true, resource $stream = STDOUT) : voidSame as write(), except it also appends a PHP_EOL sequence to the $string.
writeErrorMessage(string $message)Wraps $message in an <error></error> sequence, and passes it to
writeLine(), using STDERR as the $stream.
Below is an example class that accepts an argument list, and determines how and what to emit.
namespace Foo;
use Laminas\Stdlib\ConsoleHelper;
class HelloWorld
{
private $helper;
public function __construct(ConsoleHelper $helper = null)
{
$this->helper = $helper ?: new ConsoleHelper();
}
public function __invoke(array $args)
{
if (! count($args)) {
$this->helper->writeErrorMessage('Missing arguments!');
return;
}
if (count($args) > 1) {
$this->helper->writeErrorMessage('Too many arguments!');
return;
}
$target = array_shift($args);
$this->helper->writeLine(sprintf(
'<info>Hello</info> %s',
$target
));
}
}
ConsoleHelper is deliberately simple, and assumes that your primary need for
console tooling is for output considerations.
If you need to parse complex argument strings, we recommend using laminas-console/zf-console or symfony/console, as these packages provide those capabilities, as well as far more colorization and console feature detection facilities.
How can I help you explore Laravel packages today?