surgiie/console

此包已被废弃,不再维护。未建议替代包。

为 Laravel 或 Laravel Zero 命令提供基本命令和一组有用的特性/支持类。

安装: 362

依赖者: 3

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 1

开放问题: 0

类型:模板


README

Tests

LaravelLaravel Zero 命令提供基本命令和一组有用的支持特性/类。

安装

composer require surgiie/console

特性

合并数据

所有参数和选项合并到单个 $this->data 集合中,提供一个流畅的对象来提取和处理选项/参数数据。

<?php

namespace App\Console\Commands;

use Surgiie\Console\Command;

class ExampleCommand extends Command
{
    public function handle()
    {
        $this->data->get("some-arg-or-option", 'default');
    }
}

检查是否传入了选项

<?php

namespace App\Console\Commands;

use Surgiie\Console\Command;

class ExampleCommand extends Command
{
    protected $signature = "example {--iterations=}";

    public function handle()
    {
        // check if the user passed the --iterations flag in the command call.
        if($this->optionWasPassed("iterations")){

        }
    }
}

将值存储到缓存数组中以提高性能

当需要重复调用时,有助于将实例缓存到数组属性中。

protected function example()
{
    // get a value or store it in the cache array if it doesnt exist
    return $this->fromArrayCache('example', fn () => new Example);
}

验证

利用 Laravel 验证进行参数 & 选项验证

<?php

namespace App\Console\Commands;

use Surgiie\Console\Command;

class ExampleCommand extends Command
{

    protected $signature = "example {--iterations=}";

    public function rules()
    {
        return [
            'interations'=>'required|numeric'
        ];
    }

    public function messages()
    {
        // custom validation messages
        return ['...'];
    }

    public function attributes()
    {
        // custom validation attributes
        return ['...'];
    }
}

任意选项

允许您的命令接受非命令签名部分的任意选项

<?php
namespace App\Console\Commands;

use Surgiie\Console\Command;

class ExampleCommand extends Command
{

    public function arbitraryOptions()
    {
        return true;
    }

    public function handle()
    {
        // available if --something option is passed:
        $something = $this->arbitraryData->get("something")
    }
}

注意 任意选项以原样解析,不进行任何验证或转换,因此请确保在用于 shell 命令的任何值上运行 escapeshellarg 或进行验证。

参数 & 选项转换/格式化

在调用 handle 之前,使用验证规则语法轻松转换、格式化或清理输入和参数

protected function transformers() : array
{
    return [
        'some-option'=>['trim', 'ucwords']
    ];
}

protected function transformersAfterValidation() : array
{
    return [
        'some-option'=>['strtoupper']
    ];
}

*注意 - 更多信息,请参阅 surgiie/tranformer 的 README 文档。

注意 - 基本命令在自定义定义之前执行一些默认转换,如下所示

  • 所有名称中包含 "date" 的选项都将自动转换为 \Carbon\Carbon 实例。

检查需求

在调用 handle 之前提供需求列表

    public function requireSomethingOrFail(): string
    {
        // throw an exception:
        throw new FailedRequirementException("Failed to meet some requirment");
        // or return an error string:
        return "Failed to meet some requirement";
    }

    public function requirements(): array
    {
        return [
            'docker', //default for a string value checks if 'docker' is in $PATH with `which <value>`
            "requireSomethingOrFail", //unless the method exists on the class, it will call that instead
            function () { // can use callback that returns an error string
                $process = new Process(['docker', 'info']);

                $process->run();

                return $process->getOutput() == '' ? 'Docker is not running' : '';
            },
            // can use also class constants or instances that have __invoke method.
            new Example,
            Example::class
        ];
    }

注意 如果上述任何方法返回错误字符串或引发 FailedRequirementException,则不会调用 handle 方法。

此外,如果您需要自定义逻辑来检查字符串路径是否可用,您可以重写以下方法

/**
 * Check if a executable is in $PATH.
 *
 * @param string $requirement
 * @return string
 */
protected function checkWhichPath(string $requirement): string
{
    $process = (new Process(['which', $requirement]));

    $process->run();

    return $process->getOutput() == '' ? "This command requires $requirement." : '';
}

使用 Blade 引擎渲染文件

提供扩展的 Blade 引擎,可以编译任何文本文件

public function handle()
{
    $contents = $this->render('/some/file', ['var'=>'example']);
}

// set a custom path for compiled/cached files. Default is /tmp/.compiled or tests/.compiled when running unit tests
public function bladeCompiledPath(): string
{
    return '/custom/directory';
}

长时间运行的任务

为了给长时间运行的任务提供更好的视觉体验,您可以使用 runTask 方法

$this->runTask("Doing stuff", function($task){
    sleep(4); // simulating stuff.

    return true; // return whether task succeeded or not.

}, spinner: true); // show spinner while task is running.

注意 - 为了显示动画旋转器,必须安装 pcntl PHP 扩展。当此扩展不可用时,将显示旋转器的静态版本。

自定义任务完成文本

当任务完成时,您可以自定义显示的任务完成文本。

$this->runTask("Doing stuff", function($task){
    sleep(4); // simulating stuff.
}, finishedText: "Finished doing stuff");

自动调用成功/失败函数

根据 handle 的退出代码自动调用 成功失败 函数。

public function succeeded()
{
    // called when handle int is 0
    $this->components->info("It ran successfully");
}
public function failed()
{
    // called when handle int is 1
    $this->components->info("It didnt run successfully");
}