devsrealm/tonics-console 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

devsrealm/tonics-console

Composer 安装命令:

composer require devsrealm/tonics-console

包简介

Tonics Console is a PHP-based command-line argument processing library. It allows you to easily parse and handle command-line arguments in your PHP applications.

README 文档

README

Tonics Console is a PHP-based command-line argument processing library. It allows you to easily parse and handle command-line arguments in your PHP applications.

Installation

To install Tonics Console, you can use Composer:

composer require devsrealm/tonics-console

Usage

Basic Example

Here's a basic example of how to use the ProcessCommandLineArgs class to parse command-line arguments:

<?php

require 'vendor/autoload.php';

use Devsrealm\TonicsConsole\ProcessCommandLineArgs;

$args = ['--name=John', '--age=30', '-v'];

$processArgs = new ProcessCommandLineArgs($args);

if ($processArgs->passes()) {
    $parsedArgs = $processArgs->getProcessArgs();
    print_r($parsedArgs);
} else {
    echo "No valid arguments passed.";
}

Output

The above code will output:

Array
(
    [--name] => John
    [--age] => 30
    [-v] => 
)

Here is an additional example demonstrating how to use the ProcessCommandLineArgs class to handle different types of command-line arguments:

Advanced Example

This example shows how to handle both required and optional arguments, as well as how to check if the arguments were passed correctly.

<?php

require 'vendor/autoload.php';

use Devsrealm\TonicsConsole\ProcessCommandLineArgs;

$args = ['--name=John', '--age=30', '-v', '--email=john.doe@example.com'];

$processArgs = new ProcessCommandLineArgs($args);

if ($processArgs->passes()) {
    $parsedArgs = $processArgs->getProcessArgs();
    
    echo "Parsed Arguments:\n";
    print_r($parsedArgs);
    
    // Access individual arguments
    $name = $parsedArgs['--name'] ?? 'Unknown';
    $age = $parsedArgs['--age'] ?? 'Unknown';
    $email = $parsedArgs['--email'] ?? 'Unknown';
    $verbose = isset($parsedArgs['-v']);
    
    echo "\nDetails:\n";
    echo "Name: $name\n";
    echo "Age: $age\n";
    echo "Email: $email\n";
    echo "Verbose Mode: " . ($verbose ? 'Enabled' : 'Disabled') . "\n";
} else {
    echo "No valid arguments passed.";
}

Output

The above code will output:

Parsed Arguments:
Array
(
    [--name] => John
    [--age] => 30
    [-v] =>
    [--email] => john.doe@example.com
)

Details:
Name: John
Age: 30
Email: john.doe@example.com
Verbose Mode: Enabled

This example demonstrates how to parse and access individual command-line arguments, including handling optional flags like -v.

Advanced Features

  • Repeated keys (both required --key and optional -k) are supported. A single occurrence remains a string (backward compatible); multiple occurrences become an array.
  • Wildcard matching for required patterns: commands can declare --env* to match any --env:subcommand key.
  • ArgsHelper utility provides convenient methods for checking and retrieving arguments.

Repeated Keys Example

php console --env:manage --file=.env.local --set=DB_HOST=localhost --set=DB_USER=root -I=path1 -I=path2 -v

Parsed structure snippet:

Array
(
    [--env:manage] =>
    [--file] => .env.local
    [--set] => Array
        (
            [0] => DB_HOST=localhost
            [1] => DB_USER=root
        )

    [-I] => Array
        (
            [0] => path1
            [1] => path2
        )

    [-v] =>
)

Wildcard Required Patterns in Commands

A command can express its requirements with wildcards:

use Devsrealm\TonicsConsole\Interfaces\ConsoleCommand;

class EnvManageCommand implements ConsoleCommand
{
    public function required(): array
    {
        // Accepts any --env:* subcommand
        return ['--env*'];
    }

    public function run(array $commandOptions): void
    {
        // ...
    }
}

ArgsHelper Quick Reference

use Devsrealm\TonicsConsole\Helpers\ArgsHelper;

// presence checks (wildcard supported)
ArgsHelper::has($args, '--env*');

// get exact or wildcard map
$value = ArgsHelper::get($args, '--file', 'default');
$envMap = ArgsHelper::get($args, '--env*'); // [ '--env:manage' => '', '--env:list' => '', ... ]

// always return array for a key (promote scalar/flag to array)
$sets = ArgsHelper::getAsArray($args, '--set');

// treat empty-string flags as boolean true
$verbose = ArgsHelper::valueOrFlag($args, '-v', true, false);

// filter by patterns
$envArgs = ArgsHelper::filter($args, '--env*');

// validate required patterns (supports wildcards)
$missing = ArgsHelper::require($args, ['--env*', '--file']);

Optional Description Interface

For commands that want to expose metadata without affecting behavior, implement:

use Devsrealm\TonicsConsole\Interfaces\DescribedConsoleCommand;
  • name(): string
  • description(): string
  • usage(): string

Command Specificity and Matching

When multiple commands have overlapping requirements, the console automatically matches the most specific command first (the one with the most required arguments). This ensures correct behavior when you have commands with subset/superset requirements.

Example:

// Generic command
class MigrateAll implements ConsoleCommand
{
    public function required(): array
    {
        return ['--migrate:all'];
    }
    
    public function run(array $commandOptions): void
    {
        // Runs basic migration
    }
}

// More specific command
class MigrateAllFresh implements ConsoleCommand
{
    public function required(): array
    {
        return ['--migrate:all', '--fresh'];
    }
    
    public function run(array $commandOptions): void
    {
        // Runs fresh migration
    }
}

When you run:

php console --migrate:all --fresh

The system will match MigrateAllFresh (2 required args) instead of MigrateAll (1 required arg), ensuring the correct command executes regardless of registration order.

When you run:

php console --migrate:all

The system will match MigrateAll since MigrateAllFresh is missing the --fresh requirement.

Class Details

ProcessCommandLineArgs

This class is responsible for processing command-line arguments.

Constructor

public function __construct(array $args)
  • $args: An array of command-line arguments.

Methods

  • processArgs($args): array

    Filters and processes the command-line arguments.

  • passes(): bool

    Checks if there are any valid arguments passed.

  • getProcessArgs(): array

    Returns the processed arguments.

Testing with Kahlan

Specs are located in the spec/ directory. Run the test suite with:

vendor/bin/kahlan

Kahlan coverage/reporters are not required for this project; the default output is sufficient.

License

This project is licensed under the MIT License. See the LICENSE file for details.

devsrealm/tonics-console 适用场景与选型建议

devsrealm/tonics-console 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3.48k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 11 月 11 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 devsrealm/tonics-console 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 devsrealm/tonics-console 我们能提供哪些服务?
定制开发 / 二次开发

基于 devsrealm/tonics-console 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 3.48k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 1
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-11-11