PHPackages                             mikhailovlab/php-fluent-console - 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. [Framework](/categories/framework)
4. /
5. mikhailovlab/php-fluent-console

ActiveLibrary[Framework](/categories/framework)

mikhailovlab/php-fluent-console
===============================

Wrapper library for working with the command line using the query builder.

1.0.0(11mo ago)72.6k↓80%31MITPHPPHP ^8.0

Since Jun 30Pushed 11mo ago3 watchersCompare

[ Source](https://github.com/MikhailovLab/php-fluent-console)[ Packagist](https://packagist.org/packages/mikhailovlab/php-fluent-console)[ RSS](/packages/mikhailovlab-php-fluent-console/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependenciesVersions (2)Used By (1)

PhpFluentConsole
================

[](#phpfluentconsole)

**PhpFluentConsole** is a command line library for working with a fluent interface. It provides flexible capabilities for creating and executing command processes, as well as support for various encodings, such as CP866, CP1251, UTF-8 and others, which is especially useful when working with Cyrillic in Windows. The library also includes a system for filtering arguments, as well as capabilities for flexible output parsing using regular expressions.

**PhpFluentConsole** — это библиотека для работы с командной строкой через текучий интерфейс. Она предоставляет гибкие возможности для создания и выполнения командных процессов, а также поддержку различных кодировок, таких как CP866, CP1251, UTF-8 и другие, что особенно полезно при работе с кириллицей в Windows. Библиотека также включает систему фильтрации аргументов, а также возможности для гибкого парсинга вывода с использованием регулярных выражений.

---

Features
--------

[](#features)

- **Flexible command construction**: The library allows you to dynamically generate commands via a fluent interface, which makes it easily extensible and suitable for creating other libraries or services on top of it.
- **Regular expressions for output**: You can filter command output using regular expressions to search for specific strings or to identify errors in the output.
- **Encoding support**: The library supports various output encodings, including Windows encodings such as CP866 and CP1251, which is useful for handling Cyrillic in the command line correctly.
- **Flexible error handling**: You can customize the error output to suit your requirements - either output the command return code or search for errors using regular expressions.
- **Security**: Carefully check the input data, as uncontrolled input can lead to security issues, such as command injection.

Особенности
-----------

[](#особенности)

- **Гибкое построение команд**: Библиотека позволяет динамически генерировать команды через текучий интерфейс, что делает ее легко расширяемой и подходящей для создания других библиотек или сервисов поверх нее.
- **Регулярные выражения для вывода**: Вы можете фильтровать вывод команд с использованием регулярных выражений для поиска конкретных строк или для определения ошибок в выводе.
- **Поддержка кодировок**: Библиотека поддерживает различные кодировки вывода, включая кодировки для Windows, такие как CP866 и CP1251, что полезно для корректной работы с кириллицей в командной строке.
- **Гибкая обработка ошибок**: Вы можете настроить вывод ошибок, чтобы он соответствовал вашим требованиям — либо выводить код возврата команды, либо искать ошибки с помощью регулярных выражений.
- **Безопасность**: Внимательно проверяйте входные данные, так как неконтролируемый ввод может привести к проблемам безопасности, например, к инъекциям команд.

---

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

[](#installation)

Установка
---------

[](#установка)

```
composer require mikhailovlab/php-fluent-console

```

Method descriptions
-------------------

[](#method-descriptions)

Описание методов
----------------

[](#описание-методов)

- Sets the command to execute.
- Устанавливает команду для выполнения.

```
public function setCommand(string $cmd): self
```

- Adds an argument or part of a command.
- Добавляет аргумент или часть команды.

```
public function addKey(string $key): self
```

- Sets the encoding for output. For example, '866' to display Cyrillic in Windows.
- Устанавливает кодировку для вывода. Например, '866' для отображения кириллицы в Windows.

```
public function encoding(?string $encoding = null): self
```

- Sets a flag that the encoding should be converted back. The method is useful for returning the output in the original encoding for working with cmd.
- Устанавливает флаг, что нужно выполнить обратную конвертацию кодировки. Метод полезен для возврата вывода в исходной кодировке для работы с cmd.

```
public function decoding(): self
```

- Returns the current command.
- Возвращает текущую команду.

```
public function getCommand(): string
```

- Executes the command and returns true if the return code is 0.
- Выполняет команду и возвращает true, если код возврата равен 0.

```
public function run(): bool
```

- Get the output after executing the command.
- Получить вывод после выполнения команды.

```
public function getOutput(): array
```

- Get the return code of the command execution.
- Получить код возврата выполнения команды.

```
public function getReturnCode(): int
```

- Checks output for errors using a regular expression.
- Проверяет вывод на наличие ошибки по регулярному выражению.

```
public function hasError(string $pattern): bool
```

- Gets all output lines that match a regular expression.
- Получает все строки вывода, совпавшие с регулярным выражением.

```
public function getMatches(string|array $patterns): array
```

#### Example 1

[](#example-1)

- Getting an IP address in the Windows operating system
- Получаем ip адерс в операционной системе windows

```
$cli = new ConsoleRunner();
$cli->setCommand('ipconfig')
    ->addKey('/all');

if ($cli->run()) {
    print_r($cli->getOutput());
    exit();
}

exit('Error, code: ' . $cli->getReturnCode());
```

#### Example 2

[](#example-2)

- List digital signature containers (CSP)
- Список контейнеров с электронными подписями

```
$cli = new ConsoleRunner();
$cli->setCommand('csptest')
    ->addKey('-keyset')
    ->addKey('-enum_cont')
    ->addKey('-verifycontext')
    ->addKey('-fqcn');

if ($cli->run()) {
    // Filter output lines matching the pattern (e.g., container names)
    print_r($cli->getMatches('#\\\\.*#'));
    exit();
}

$pattern = '/\[ErrorCode:\s*(0x[0-9A-Fa-f]+)\]/';
exit('Error code: ' . $cli->getMatches($pattern)[0]);
```

#### Example 3

[](#example-3)

- We can inherit from the main class and instead of specifying methods via addKey we can call them dynamically using the magic method \_\_call
- Мы можем наследоваться от главного класса и вместо указания методов через addKey вызывать их динамически используя магический метод \_\_call

```
class customRunner extends ConsoleRunner
{
    private $methods = [
        'keyset',
        'enum_cont',
        'verifycontext',
        'fqcn'
    ];

    public function __call(string $name, array $arguments): self
    {
        if (in_array($name, $this->methods)) {
            $this->addKey('-' . $name);

            if (!empty($arguments)) {
                foreach ($arguments as $arg) {
                    $this->addKey((string) $arg);
                }
            }

            return $this;
        }

        throw new \BadMethodCallException("Method $name is not supported");
    }

}

try{
    $cli = new customRunner()
        ->setCommand('csptest')
        ->keyset()
        ->enum_cont()
        ->verifycontext()
        ->fqcn();

    if ($cli->run()) {
        print_r($cli->getMatches('#\\\\.*#'));
        exit();
    }

    $pattern = '/\[ErrorCode:\s*(0x[0-9A-Fa-f]+)\]/';
    exit('Error code: ' . $cli->getMatches($pattern)[0]);

}catch (Exception $e){
    exit($e->getMessage());
}
```

- This approach allows us to create flexible bindings and libraries without having to study the documentation.
- Такой подход позволяет нам создавать гибкие обвязки и библиотеки, не отвлекаясь на изучение документации.

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance50

Moderate activity, may be stable

Popularity27

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Unknown

Total

1

Last Release

358d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/91b602332c97ac634466d8088527c49f1b5d5c63833d0435849dea42e974d2ca?d=identicon)[MikhailovLab](/maintainers/MikhailovLab)

---

Top Contributors

[![MikhailovLab](https://avatars.githubusercontent.com/u/65474984?v=4)](https://github.com/MikhailovLab "MikhailovLab (14 commits)")

---

Tags

cliframeworkweb servicequery buildercmdmikhailovlab

### Embed Badge

![Health badge](/badges/mikhailovlab-php-fluent-console/health.svg)

```
[![Health](https://phpackages.com/badges/mikhailovlab-php-fluent-console/health.svg)](https://phpackages.com/packages/mikhailovlab-php-fluent-console)
```

###  Alternatives

[mikhailovlab/crypto-pro-builder

Библиотека для работы с КриптоПро через CLI, позволяет гибко строить команды через цепочки вызовов, использовать динамические методы и адаптировать функционал под свои нужды.

142.5k](/packages/mikhailovlab-crypto-pro-builder)

PHPackages © 2026

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