PHPackages                             mulertech/mterm - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [CLI &amp; Console](/categories/cli)
4. /
5. mulertech/mterm

ActiveLibrary[CLI &amp; Console](/categories/cli)

mulertech/mterm
===============

This application is a PHP CLI.

v1.0.2(1y ago)0531MITPHPPHP ^8.2CI passing

Since Mar 22Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/mulertech/mterm)[ Packagist](https://packagist.org/packages/mulertech/mterm)[ RSS](/packages/mulertech-mterm/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (5)Versions (4)Used By (1)

MTerm
=====

[](#mterm)

---

[![Latest Version on Packagist](https://camo.githubusercontent.com/f1c113b4e8663b576b72c26b7931a545d1e784b85607c2664482a5ee107cd15f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d756c6572746563682f6d7465726d2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mulertech/mterm)[![GitHub Tests Action Status](https://camo.githubusercontent.com/a835d73869e2b271ee10e1aacd48fd34acade62f3473db48723de0fc6e55b320/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d756c6572746563682f6d7465726d2f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/mulertech/mterm/actions/workflows/tests.yml)[![GitHub PHPStan Action Status](https://camo.githubusercontent.com/a2ed3feda627949111ac0b97901067f58ca628136ac853baab68ede5f2a7ffac/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d756c6572746563682f6d7465726d2f7068707374616e2e796d6c3f6272616e63683d6d61696e266c6162656c3d7068707374616e267374796c653d666c61742d737175617265)](https://github.com/mulertech/mterm/actions/workflows/phpstan.yml)[![GitHub Security Action Status](https://camo.githubusercontent.com/e2bd0d1daf6a8a9620862b43b1e9a0a69027f2ee350fafdf90f32ed3808d604a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d756c6572746563682f6d7465726d2f73656375726974792e796d6c3f6272616e63683d6d61696e266c6162656c3d7365637572697479267374796c653d666c61742d737175617265)](https://github.com/mulertech/mterm/actions/workflows/security.yml)[![Total Downloads](https://camo.githubusercontent.com/1f94445d2905b7f3982910f1612c1f023b835663f78e183af4d36525b427ba73/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d756c6572746563682f6d7465726d2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mulertech/mterm)[![Test Coverage](https://raw.githubusercontent.com/mulertech/mterm/badge/badge-coverage.svg)](https://packagist.org/packages/mulertech/mterm)

---

This class is a simple class to create a terminal interface for your application.

---

Installation
------------

[](#installation)

###### *Two methods to install MTerm package with composer :*

[](#two-methods-to-install-mterm-package-with-composer-)

1.

Add to your "**composer.json**" file into require section :

```
"mulertech/mterm": "^1.0"

```

and run the command :

```
php composer.phar update

```

2.

Run the command :

```
php composer.phar require mulertech/mterm "^1.0"

```

---

Usage
-----

[](#usage)

MTerm provides a simple and elegant way to build interactive command-line interfaces in PHP. Below are the main classes and their methods with usage examples.

### Basic Usage

[](#basic-usage)

```
$terminal = new Terminal();
$terminal->write('Hello, World!');
$terminal->writeLine('Hello with a new line!');
```

### Terminal Class

[](#terminal-class)

The main class for interacting with the terminal.

### Method Reference

[](#method-reference)

Here's a comprehensive guide to all public methods in the Terminal class:

#### Reading Input

[](#reading-input)

##### `read(string $prompt = null): string`

[](#readstring-prompt--null-string)

Reads a line of input from the terminal.

```
$name = $terminal->read('Enter your name: ');
$input = $terminal->read(); // No prompt
```

##### `readChar(string $prompt = null): string`

[](#readcharstring-prompt--null-string)

Reads a single character from the terminal.

```
$char = $terminal->readChar('Continue? (y/n): ');
if ($char === 'y') {
    // Process confirmation
}
```

#### Output Methods

[](#output-methods)

##### `write(string $text, string $color = null, bool $bold = false): void`

[](#writestring-text-string-color--null-bool-bold--false-void)

Writes text to the terminal without a newline.

```
$terminal->write('Regular text ');
$terminal->write('Red text ', 'red');
$terminal->write('Bold blue ', 'blue', true);
```

##### `writeLine(string $text, string $color = null, bool $bold = false): void`

[](#writelinestring-text-string-color--null-bool-bold--false-void)

Writes text to the terminal followed by a newline.

```
$terminal->writeLine('First line');
$terminal->writeLine('Success message', 'green');
$terminal->writeLine('Error message', 'red', true);
```

#### Terminal Control

[](#terminal-control)

##### `clear(): void`

[](#clear-void)

Clears the terminal screen.

```
$terminal->clear();
```

##### `specialMode(): void`

[](#specialmode-void)

Sets the terminal to special mode where characters are read immediately.

```
$terminal->specialMode();
// Read characters without waiting for Enter
$terminal->normalMode(); // Return to standard mode
```

##### `normalMode(): void`

[](#normalmode-void)

Restores the terminal to its normal mode.

```
$terminal->normalMode();
```

##### `system(string $command): void`

[](#systemstring-command-void)

Executes a system command.

```
$terminal->system('ls -la');
```

#### Utility Methods

[](#utility-methods)

##### `supportsAnsi(): bool`

[](#supportsansi-bool)

Checks if the terminal supports ANSI color codes.

```
if ($terminal->supportsAnsi()) {
    $terminal->writeLine('Colors supported', 'green');
}
```

##### `inputStream(): resource`

[](#inputstream-resource)

Returns the input stream resource.

```
$stream = $terminal->inputStream();
```

### Available Colors

[](#available-colors)

The Terminal class supports: black, red, green, yellow, blue, magenta, cyan, white.

### Creating Interactive Menus

[](#creating-interactive-menus)

```
function showMenu($terminal) {
    $terminal->clear();
    $terminal->writeLine('=== MENU ===', 'blue', true);
    $terminal->writeLine('1. Option One');
    $terminal->writeLine('2. Exit');
    return $terminal->read('Select: ');
}

while (true) {
    $choice = showMenu($terminal);
    if ($choice === '2') break;
}
```

Command System
--------------

[](#command-system)

MTerm includes a robust command system for creating and managing terminal commands.

### CommandInterface

[](#commandinterface)

This interface defines the basic structure for all commands.

```
class HelloCommand implements CommandInterface
{
    public function getName(): string
    {
        return 'hello';
    }

    public function getDescription(): string
    {
        return 'Greets a user';
    }

    public function execute(array $args = []): int
    {
        $name = $args[0] ?? 'World';
        $this->terminal->writeLine("Hello, $name!");
        return 0;
    }
}
```

### AbstractCommand

[](#abstractcommand)

A base class that implements basic functionality for CommandInterface.

```
class DateCommand extends AbstractCommand
{
    public function __construct(Terminal $terminal)
    {
        parent::__construct($terminal);
        $this->name = 'date';
        $this->description = 'Shows date/time';
    }

    public function execute(array $args = []): int
    {
        $format = $args[0] ?? 'Y-m-d H:i:s';
        $this->terminal->writeLine(date($format));
        return 0;
    }
}

// Usage
$cmd = new DateCommand($terminal);
$cmd->execute(['Y-m-d']); // Shows date in specified format
```

### CommandRegistry

[](#commandregistry)

Manages a collection of commands.

```
$registry = new CommandRegistry();

$registry->register(new HelloCommand($terminal));
$registry->has('hello'); // Check if exists
$command = $registry->get('date'); // Get specific command
$allCommands = $registry->getAll(); // Get all commands
$registry->execute('hello', ['User']); // Execute with arguments
```

### Simple CLI Application

[](#simple-cli-application)

```
$terminal = new Terminal();
$registry = new CommandRegistry();

// Register commands
$registry->register(new HelloCommand($terminal));

// Main loop
while (true) {
    $input = $terminal->read('> ');
    $parts = explode(' ', $input);
    $commandName = array_shift($parts);

    if ($commandName === 'exit') break;

    if ($registry->has($commandName)) {
        $registry->execute($commandName, $parts);
    }
}
```

Application Class
-----------------

[](#application-class)

The Application class implements a singleton pattern for managing terminal interactions.

### Method Reference

[](#method-reference-1)

#### `getInstance(): Application`

[](#getinstance-application)

Gets the singleton instance of the Application class.

```
$app = Application::getInstance();
```

#### `getTerminal(): Terminal`

[](#getterminal-terminal)

Returns the Terminal instance.

```
$terminal = $app->getTerminal();
$terminal->writeLine('Hello!');
```

#### `getCommandRunner(): CommandRunner`

[](#getcommandrunner-commandrunner)

Returns the CommandRunner instance.

```
$runner = $app->getCommandRunner();
$result = $runner->run('ls -la');
```

#### `run(): void`

[](#run-void)

Starts the application's main execution loop.

```
$app = Application::getInstance();
$app->run();
```

CommandRunner Class
-------------------

[](#commandrunner-class)

The CommandRunner class provides methods to execute system commands.

### Method Reference

[](#method-reference-2)

#### `run(string $command): array`

[](#runstring-command-array)

Executes a command and returns output and return code.

```
$runner = new CommandRunner();
$result = $runner->run('echo "Hello"');
// Returns ['output' => ['Hello'], 'returnCode' => 0]
```

#### `runWithStderr(string $command): array`

[](#runwithstderrstring-command-array)

Executes a command and returns stdout, stderr, and return code.

```
$result = $runner->runWithStderr('ls /nonexistent');
// Returns ['stdout' => '', 'stderr' => 'error message...', 'returnCode' => 1]
```

### Combining Classes Example

[](#combining-classes-example)

```
$app = Application::getInstance();
$terminal = $app->getTerminal();
$runner = $app->getCommandRunner();

$command = $terminal->read('Command: ');
$result = $runner->runWithStderr($command);
$terminal->writeLine($result['stdout']);
if ($result['stderr']) {
    $terminal->writeLine($result['stderr'], 'red');
}
```

Form Classes
------------

[](#form-classes)

### AbstractField

[](#abstractfield)

#### `__construct(string $name, string $label)`

[](#__constructstring-name-string-label)

Constructor for the AbstractField class.

```
$field = new AbstractField('username', 'Username');
$field->setDescription('Enter your username');
$field->setRequired(true);
$field->setDefault('guest');
$field->setTerminal(new Terminal());
```

#### `getName(): string`

[](#getname-string)

Returns the name of the field.

```
$field->getName(); // Returns 'username'
```

#### `getLabel(): string`

[](#getlabel-string)

Returns the label of the field.

```
$field->getLabel(); // Returns 'Username'
```

#### `getDescription(): ?string`

[](#getdescription-string)

Returns the description of the field.

```
$field->getDescription(); // Returns 'Enter your username'
```

#### `setDescription(string $description): self`

[](#setdescriptionstring-description-self)

Sets the description of the field.

```
$field->setDescription('Enter your username');
```

#### `isRequired(): bool`

[](#isrequired-bool)

Checks if the field is required.

```
$field->isRequired(); // Returns true
```

#### `setRequired(bool $required = true): self`

[](#setrequiredbool-required--true-self)

Sets whether the field is required.

```
$field->setRequired(true);
```

#### `getDefault(): string|int|float|array|null`

[](#getdefault-stringintfloatarraynull)

Returns the default value of the field.

```
$field->getDefault(); // Returns 'guest'
```

#### `setDefault(string|int|float|array $defaultValue): self`

[](#setdefaultstringintfloatarray-defaultvalue-self)

Sets the default value of the field.

```
$field->setDefault('guest');
```

#### `clearErrors(): void`

[](#clearerrors-void)

Clears the errors of the field.

```
$field->clearErrors();
```

#### `addValidator(ValidatorInterface $validator): self`

[](#addvalidatorvalidatorinterface-validator-self)

Adds a validator to the field.

```
$validator = new NotEmptyValidator();
$field->addValidator($validator);
```

#### `validate(string|int|float|array|null $value): array`

[](#validatestringintfloatarraynull-value-array)

Validates the field value.

```
$errors = $field->validate(''); // Returns array of errors
```

#### `processInput(string $input): string|int|float|array`

[](#processinputstring-input-stringintfloatarray)

Processes the user input.

```
$value = $field->processInput('guest'); // Returns processed value
```

#### `setTerminal(Terminal $terminal): self`

[](#setterminalterminal-terminal-self)

Sets the terminal instance for the field.

```
$field->setTerminal(new Terminal());
```

### CheckboxField

[](#checkboxfield)

#### `setCheckedValue(string $value): self`

[](#setcheckedvaluestring-value-self)

Sets the checked value for the checkbox.

```
$field = new CheckboxField('accept_terms', 'Accept Terms');
$field->setCheckedValue('yes');
```

#### `setUncheckedValue(string $value): self`

[](#setuncheckedvaluestring-value-self)

Sets the unchecked value for the checkbox.

```
$field->setUncheckedValue('no');
```

#### `processInput(string $input): string|int|float|array`

[](#processinputstring-input-stringintfloatarray-1)

Processes the user input for the checkbox.

```
$value = $field->processInput('yes'); // Returns 'yes'
```

### ColorField

[](#colorfield)

#### `validate(string|int|float|array|null $value): array`

[](#validatestringintfloatarraynull-value-array-1)

Validates the color field value.

```
$field = new ColorField('favorite_color', 'Favorite Color');
$errors = $field->validate('red'); // Returns array of errors
```

### DateField

[](#datefield)

#### `setFormat(string $format): self`

[](#setformatstring-format-self)

Sets the date format.

```
$field = new DateField('birthdate', 'Birthdate');
$field->setFormat('Y-m-d');
```

#### `getFormat(): string`

[](#getformat-string)

Returns the date format.

```
$field->getFormat(); // Returns 'Y-m-d'
```

#### `processInput(string $input): string|int|float|array`

[](#processinputstring-input-stringintfloatarray-2)

Processes the user input for the date field.

```
$value = $field->processInput('2022-01-01'); // Returns processed value
```

#### `validate(string|int|float|array|null $value): array`

[](#validatestringintfloatarraynull-value-array-2)

Validates the date field value.

```
$errors = $field->validate('2022-01-01'); // Returns array of errors
```

### EmailField

[](#emailfield)

#### `validate(string|int|float|array|null $value): array`

[](#validatestringintfloatarraynull-value-array-3)

Validates the email field value.

```
$field = new EmailField('email', 'Email');
$errors = $field->validate('user@example.com'); // Returns array of errors
```

### FieldInterface

[](#fieldinterface)

#### `getName(): string`

[](#getname-string-1)

Returns the name of the field.

#### `getLabel(): string`

[](#getlabel-string-1)

Returns the label of the field.

#### `getDescription(): ?string`

[](#getdescription-string-1)

Returns the description of the field.

#### `setDescription(string $description): self`

[](#setdescriptionstring-description-self-1)

Sets the description of the field.

#### `isRequired(): bool`

[](#isrequired-bool-1)

Checks if the field is required.

#### `setRequired(bool $required = true): self`

[](#setrequiredbool-required--true-self-1)

Sets whether the field is required.

#### `clearErrors(): void`

[](#clearerrors-void-1)

Clears the errors of the field.

#### `setDefault(string|int|float|array $defaultValue): self`

[](#setdefaultstringintfloatarray-defaultvalue-self-1)

Sets the default value of the field.

#### `getDefault(): string|int|float|array|null`

[](#getdefault-stringintfloatarraynull-1)

Returns the default value of the field.

#### `processInput(string $input): string|int|float|array`

[](#processinputstring-input-stringintfloatarray-3)

Processes the user input.

#### `validate(string|int|float|array|null $value): array`

[](#validatestringintfloatarraynull-value-array-4)

Validates the field value.

#### `setTerminal(Terminal $terminal): self`

[](#setterminalterminal-terminal-self-1)

Sets the terminal instance for the field.

### FileField

[](#filefield)

#### `setAllowedExtensions(array $extensions): self`

[](#setallowedextensionsarray-extensions-self)

Sets the allowed file extensions.

```
$field = new FileField('profile_picture', 'Profile Picture');
$field->setAllowedExtensions(['jpg', 'png']);
```

#### `setMaxSize(int $bytes): self`

[](#setmaxsizeint-bytes-self)

Sets the maximum file size.

```
$field->setMaxSize(1048576); // 1 MB
```

#### `processInput(string $input): string|int|float|array`

[](#processinputstring-input-stringintfloatarray-4)

Processes the user input for the file field.

```
$value = $field->processInput('path/to/file.jpg'); // Returns processed value
```

#### `validate(string|int|float|array|null $value): array`

[](#validatestringintfloatarraynull-value-array-5)

Validates the file field value.

```
$errors = $field->validate('path/to/file.jpg'); // Returns array of errors
```

### NumberField

[](#numberfield)

#### `setMin(?float $min): self`

[](#setminfloat-min-self)

Sets the minimum value for the number field.

```
$field = new NumberField('age', 'Age');
$field->setMin(18);
```

#### `setMax(?float $max): self`

[](#setmaxfloat-max-self)

Sets the maximum value for the number field.

```
$field->setMax(99);
```

#### `setAllowFloat(bool $allowFloat): self`

[](#setallowfloatbool-allowfloat-self)

Sets whether to allow floating-point numbers.

```
$field->setAllowFloat(false);
```

#### `processInput(string $input): string|int|float|array`

[](#processinputstring-input-stringintfloatarray-5)

Processes the user input for the number field.

```
$value = $field->processInput('25'); // Returns processed value
```

#### `validate(string|int|float|array|null $value): array`

[](#validatestringintfloatarraynull-value-array-6)

Validates the number field value.

```
$errors = $field->validate('25'); // Returns array of errors
```

### PasswordField

[](#passwordfield)

#### `isMaskInput(): bool`

[](#ismaskinput-bool)

Checks if the input should be masked.

```
$field = new PasswordField('password', 'Password');
$field->isMaskInput(); // Returns true
```

#### `setMaskInput(bool $maskInput = true): self`

[](#setmaskinputbool-maskinput--true-self)

Sets whether the input should be masked.

```
$field->setMaskInput(true);
```

#### `getMaskChar(): string`

[](#getmaskchar-string)

Returns the mask character.

```
$field->getMaskChar(); // Returns '*'
```

#### `setMaskChar(string $maskChar): self`

[](#setmaskcharstring-maskchar-self)

Sets the mask character.

```
$field->setMaskChar('*');
```

#### `parseInput(string $input): string`

[](#parseinputstring-input-string)

Parses the user input.

```
$value = $field->parseInput('password'); // Returns parsed value
```

#### `processInput(string $input = ''): string`

[](#processinputstring-input---string)

Processes the user input for the password field.

```
$value = $field->processInput('password'); // Returns processed value
```

### RadioField

[](#radiofield)

#### `__construct(string $name, string $label)`

[](#__constructstring-name-string-label-1)

Constructor for the RadioField class.

```
$field = new RadioField('gender', 'Gender');
```

#### `setMultipleSelection(bool $multipleSelection = true): self`

[](#setmultipleselectionbool-multipleselection--true-self)

Sets whether multiple selection is allowed.

```
$field->setMultipleSelection(false);
```

### RangeField

[](#rangefield)

#### `__construct(string $name, string $label)`

[](#__constructstring-name-string-label-2)

Constructor for the RangeField class.

```
$field = new RangeField('rating', 'Rating');
```

#### `setStep(int $step): self`

[](#setstepint-step-self)

Sets the step value for the range field.

```
$field->setStep(1);
```

#### `getStep(): int`

[](#getstep-int)

Returns the step value for the range field.

```
$field->getStep(); // Returns 1
```

#### `validate(string|int|float|array|null $value): array`

[](#validatestringintfloatarraynull-value-array-7)

Validates the range field value.

```
$errors = $field->validate(5); // Returns array of errors
```

### SelectField

[](#selectfield)

#### `__construct(string $name, string $label, bool $multipleSelection = false)`

[](#__constructstring-name-string-label-bool-multipleselection--false)

Constructor for the SelectField class.

```
$field = new SelectField('country', 'Country');
```

#### `setOptions(array $options): self`

[](#setoptionsarray-options-self)

Sets the options for the select field.

```
$field->setOptions(['USA', 'Canada', 'UK']);
```

#### `setMultipleSelection(bool $multipleSelection = true): self`

[](#setmultipleselectionbool-multipleselection--true-self-1)

Sets whether multiple selection is allowed.

```
$field->setMultipleSelection(false);
```

#### `isMultipleSelection(): bool`

[](#ismultipleselection-bool)

Checks if multiple selection is allowed.

```
$field->isMultipleSelection(); // Returns false
```

#### `parseInput(string $input): string`

[](#parseinputstring-input-string-1)

Parses the user input.

```
$value = $field->parseInput('USA'); // Returns parsed value
```

#### `processInput(string $input = ''): string|array`

[](#processinputstring-input---stringarray)

Processes the user input for the select field.

```
$value = $field->processInput('USA'); // Returns processed value
```

#### `renderSelectMultipleField(Terminal $terminal): array`

[](#renderselectmultiplefieldterminal-terminal-array)

Renders the select field for multiple selection.

```
$options = $field->renderSelectMultipleField(new Terminal()); // Returns array of options
```

#### `renderSelectSingleField(Terminal $terminal): string`

[](#renderselectsinglefieldterminal-terminal-string)

Renders the select field for single selection.

```
$option = $field->renderSelectSingleField(new Terminal()); // Returns selected option
```

#### `validate(string|int|float|array|null $value): array`

[](#validatestringintfloatarraynull-value-array-8)

Validates the select field value.

```
$errors = $field->validate('USA'); // Returns array of errors
```

#### `getCurrentOption(): string`

[](#getcurrentoption-string)

Returns the current selected option.

```
$field->getCurrentOption(); // Returns 'USA'
```

### TextField

[](#textfield)

#### `setMinLength(int $minLength): self`

[](#setminlengthint-minlength-self)

Sets the minimum length for the text field.

```
$field = new TextField('username', 'Username');
$field->setMinLength(3);
```

#### `setMaxLength(?int $maxLength): self`

[](#setmaxlengthint-maxlength-self)

Sets the maximum length for the text field.

```
$field->setMaxLength(20);
```

#### `validate(string|int|float|array|null $value): array`

[](#validatestringintfloatarraynull-value-array-9)

Validates the text field value.

```
$errors = $field->validate('guest'); // Returns array of errors
```

### UrlField

[](#urlfield)

#### `validate(string|int|float|array|null $value): array`

[](#validatestringintfloatarraynull-value-array-10)

Validates the URL field value.

```
$field = new UrlField('website', 'Website');
$errors = $field->validate('https://example.com'); // Returns array of errors
```

### Form

[](#form)

#### `__construct(Terminal $terminal)`

[](#__constructterminal-terminal)

Constructor for the Form class.

```
$form = new Form(new Terminal());
```

#### `addField(FieldInterface $field): self`

[](#addfieldfieldinterface-field-self)

Adds a field to the form.

```
$field = new TextField('username', 'Username');
$form->addField($field);
```

#### `handle(): void`

[](#handle-void)

Handles the form submission.

```
$form->handle();
```

#### `isSubmitted(): bool`

[](#issubmitted-bool)

Checks if the form has been submitted.

```
$form->isSubmitted(); // Returns true or false
```

#### `isValid(): bool`

[](#isvalid-bool)

Checks if the form is valid.

```
$form->isValid(); // Returns true or false
```

#### `getValues(): array`

[](#getvalues-array)

Returns all form values.

```
$values = $form->getValues(); // Returns array of values
```

#### `getValue(string $fieldName): string|int|float|array|null`

[](#getvaluestring-fieldname-stringintfloatarraynull)

Returns a specific form value.

```
$value = $form->getValue('username'); // Returns value of 'username' field
```

### FormRenderer

[](#formrenderer)

#### `__construct(Terminal $terminal)`

[](#__constructterminal-terminal-1)

Constructor for the FormRenderer class.

```
$renderer = new FormRenderer(new Terminal());
```

#### `renderField(FieldInterface $field): string|array`

[](#renderfieldfieldinterface-field-stringarray)

Renders a field.

```
$field = new TextField('username', 'Username');
$output = $renderer->renderField($field); // Returns rendered field
```

#### `renderErrors(array $errors): void`

[](#rendererrorsarray-errors-void)

Renders the errors.

```
$renderer->renderErrors(['Error 1', 'Error 2']);
```

#### `clear(): void`

[](#clear-void-1)

Clears the terminal screen.

```
$renderer->clear();
```

### ValidatorInterface

[](#validatorinterface)

#### `validate(mixed $value): ?string`

[](#validatemixed-value-string)

Validates a value.

```
class CustomValidator implements ValidatorInterface
{
    public function validate($value): ?string
    {
        return $value === 'valid' ? null : 'Invalid value';
    }
}
```

### AbstractValidator

[](#abstractvalidator)

#### `__construct(string $errorMessage)`

[](#__constructstring-errormessage)

Constructor for the AbstractValidator class.

```
class CustomValidator extends AbstractValidator
{
    public function __construct()
    {
        parent::__construct('Invalid value');
    }

    public function validate($value): ?string
    {
        return $value === 'valid' ? null : $this->getErrorMessage();
    }
}
```

#### `getErrorMessage(): string`

[](#geterrormessage-string)

Returns the error message.

```
$validator = new CustomValidator();
$errorMessage = $validator->getErrorMessage(); // Returns 'Invalid value'
```

### ChoiceValidator

[](#choicevalidator)

#### `__construct(array $choices, bool $strict = true, string $errorMessage = "Selected value is not a valid choice.")`

[](#__constructarray-choices-bool-strict--true-string-errormessage--selected-value-is-not-a-valid-choice)

Constructor for the ChoiceValidator class.

```
$validator = new ChoiceValidator(['option1', 'option2']);
```

#### `validate(mixed $value): ?string`

[](#validatemixed-value-string-1)

Validates a value.

```
$error = $validator->validate('option1'); // Returns null (valid)
$error = $validator->validate('invalid'); // Returns error message (invalid)
```

### DateValidator

[](#datevalidator)

#### `__construct(string $format = 'Y-m-d', ?DateTimeInterface $minDate = null, ?DateTimeInterface $maxDate = null, ?string $errorMessage = null)`

[](#__constructstring-format--y-m-d-datetimeinterface-mindate--null-datetimeinterface-maxdate--null-string-errormessage--null)

Constructor for the DateValidator class.

```
$validator = new DateValidator('Y-m-d');
```

#### `validate(mixed $value): ?string`

[](#validatemixed-value-string-2)

Validates a value.

```
$error = $validator->validate('2022-01-01'); // Returns null (valid)
$error = $validator->validate('invalid-date'); // Returns error message (invalid)
```

### EmailValidator

[](#emailvalidator)

#### `__construct(string $errorMessage = "Please enter a valid email address.")`

[](#__constructstring-errormessage--please-enter-a-valid-email-address)

Constructor for the EmailValidator class.

```
$validator = new EmailValidator();
```

#### `validate(mixed $value): ?string`

[](#validatemixed-value-string-3)

Validates a value.

```
$error = $validator->validate('user@example.com'); // Returns null (valid)
$error = $validator->validate('invalid-email'); // Returns error message (invalid)
```

### IpAddressValidator

[](#ipaddressvalidator)

#### `__construct(bool $allowIPv4 = true, bool $allowIPv6 = true, bool $allowPrivate = true, bool $allowReserved = true, string $errorMessage = "Please enter a valid IP address.")`

[](#__constructbool-allowipv4--true-bool-allowipv6--true-bool-allowprivate--true-bool-allowreserved--true-string-errormessage--please-enter-a-valid-ip-address)

Constructor for the IpAddressValidator class.

```
$validator = new IpAddressValidator();
```

#### `validate(mixed $value): ?string`

[](#validatemixed-value-string-4)

Validates a value.

```
$error = $validator->validate('192.168.0.1'); // Returns null (valid)
$error = $validator->validate('invalid-ip'); // Returns error message (invalid)
```

### LengthValidator

[](#lengthvalidator)

#### `__construct(?int $min = null, ?int $max = null, ?string $errorMessage = null)`

[](#__constructint-min--null-int-max--null-string-errormessage--null)

Constructor for the LengthValidator class.

```
$validator = new LengthValidator(3, 20);
```

#### `validate(mixed $value): ?string`

[](#validatemixed-value-string-5)

Validates a value.

```
$error = $validator->validate('valid'); // Returns null (valid)
$error = $validator->validate(''); // Returns error message (invalid)
```

### NotEmptyValidator

[](#notemptyvalidator)

#### `__construct(string $errorMessage = "This value cannot be empty.")`

[](#__constructstring-errormessage--this-value-cannot-be-empty)

Constructor for the NotEmptyValidator class.

```
$validator = new NotEmptyValidator();
```

#### `validate(mixed $value): ?string`

[](#validatemixed-value-string-6)

Validates a value.

```
$error = $validator->validate('valid'); // Returns null (valid)
$error = $validator->validate(''); // Returns error message (invalid)
```

### NumericRangeValidator

[](#numericrangevalidator)

#### `__construct(?float $min = null, ?float $max = null, ?string $errorMessage = null)`

[](#__constructfloat-min--null-float-max--null-string-errormessage--null)

Constructor for the NumericRangeValidator class.

```
$validator = new NumericRangeValidator(1, 100);
```

#### `validate(mixed $value): ?string`

[](#validatemixed-value-string-7)

Validates a value.

```
$error = $validator->validate(50); // Returns null (valid)
$error = $validator->validate(200); // Returns error message (invalid)
```

### PatternValidator

[](#patternvalidator)

#### `__construct(string $pattern, string $errorMessage = "Value does not match required pattern.")`

[](#__constructstring-pattern-string-errormessage--value-does-not-match-required-pattern)

Constructor for the PatternValidator class.

```
$validator = new PatternValidator('/^[a-z]+$/');
```

#### `validate(mixed $value): ?string`

[](#validatemixed-value-string-8)

Validates a value.

```
$error = $validator->validate('valid'); // Returns null (valid)
$error = $validator->validate('123'); // Returns error message (invalid)
```

### RegexValidator

[](#regexvalidator)

#### `__construct(string $pattern, string $errorMessage = "This value is not valid.")`

[](#__constructstring-pattern-string-errormessage--this-value-is-not-valid)

Constructor for the RegexValidator class.

```
$validator = new RegexValidator('/^[a-z]+$/');
```

#### `validate(mixed $value): ?string`

[](#validatemixed-value-string-9)

Validates a value.

```
$error = $validator->validate('valid'); // Returns null (valid)
$error = $validator->validate('123'); // Returns error message (invalid)
```

Utils Classes
-------------

[](#utils-classes)

### ProgressBar

[](#progressbar)

#### `__construct(Terminal $terminal, int $total = 100, int $width = 50, string $completeChar = '=', string $incompleteChar = '-', string $color = Terminal::COLORS['green'])`

[](#__constructterminal-terminal-int-total--100-int-width--50-string-completechar---string-incompletechar----string-color--terminalcolorsgreen)

Constructor for the ProgressBar class.

```
$terminal = new Terminal();
$progressBar = new ProgressBar($terminal, 100, 50, '=', '-', 'green');
```

#### `start(): void`

[](#start-void)

Starts the progress bar.

```
$progressBar->start();
```

#### `advance(int $step = 1): void`

[](#advanceint-step--1-void)

Advances the progress bar by a specific amount.

```
$progressBar->advance(10);
```

#### `setProgress(int $current): void`

[](#setprogressint-current-void)

Sets the progress to a specific value.

```
$progressBar->setProgress(50);
```

#### `finish(): void`

[](#finish-void)

Finishes the progress bar.

```
$progressBar->finish();
```

### TableFormatter

[](#tableformatter)

#### `__construct(Terminal $terminal, string $headerColor = Terminal::COLORS['green'], string $borderColor = Terminal::COLORS['blue'], string $cellColor = Terminal::COLORS['white'], int $padding = 1)`

[](#__constructterminal-terminal-string-headercolor--terminalcolorsgreen-string-bordercolor--terminalcolorsblue-string-cellcolor--terminalcolorswhite-int-padding--1)

Constructor for the TableFormatter class.

```
$terminal = new Terminal();
$tableFormatter = new TableFormatter($terminal, 'green', 'blue', 'white', 1);
```

#### `renderTable(array $headers, array $rows): void`

[](#rendertablearray-headers-array-rows-void)

Formats and renders a table.

```
$headers = ['Name', 'Age', 'Country'];
$rows = [
    ['John', 25, 'USA'],
    ['Jane', 30, 'Canada'],
    ['Doe', 22, 'UK']
];

$tableFormatter->renderTable($headers, $rows);
```

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance71

Regular maintenance activity

Popularity11

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 66.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

3

Last Release

418d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/357d309912bbc5318d9877d1369987d2390c8e034b637e9f20671c28b09b5119?d=identicon)[mulertech](/maintainers/mulertech)

---

Top Contributors

[![mulertech](https://avatars.githubusercontent.com/u/57788787?v=4)](https://github.com/mulertech "mulertech (12 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (6 commits)")

---

Tags

phpcliterminaltools

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mulertech-mterm/health.svg)

```
[![Health](https://phpackages.com/badges/mulertech-mterm/health.svg)](https://phpackages.com/packages/mulertech-mterm)
```

###  Alternatives

[league/climate

PHP's best friend for the terminal. CLImate allows you to easily output colored text, special formats, and more.

1.9k14.0M273](/packages/league-climate)[nunomaduro/termwind

It's like Tailwind CSS, but for the console.

2.5k239.8M286](/packages/nunomaduro-termwind)[php-school/learn-you-php

An introduction to PHP's core features: i/o, http, arrays, exceptions and so on.

3192.0k](/packages/php-school-learn-you-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
