Git Product home page Git Product logo

yii-console's Introduction

Yii Console


Latest Stable Version Total Downloads Build status Code Coverage Scrutinizer Quality Score Mutation testing badge static analysis type-coverage

Yii Console package provides a console that could be added to an application. This console is based on Symfony Console. The following extra features are added:

  • lazy command loader;
  • SymfonyEventDispatcher class that allows to use any PSR-14 compatible event dispatcher with Symfony console;
  • ErrorListener for logging console errors to any PSR-3 compatible logger;
  • console command serve that runs PHP built-in web server;
  • raises events ApplicationStartup and ApplicationShutdown in console application;
  • class ExitCode that contains constants for defining console command exit codes;
  • ConsoleBufferedOutput that wraps ConsoleOutput and buffers console output.

Requirements

  • PHP 8.0 or higher.

Installation

The package could be installed with composer:

composer require yiisoft/yii-console

General usage

In case you use one of Yii 3 standard application templates, console could be accessed as ./yii <command>.

If not, then in the simplest use case in your console entry script do the following:

#!/usr/bin/env php
<?php

declare(strict_types=1);

use Yiisoft\Di\Container;
use Yiisoft\Di\ContainerConfig;
use Yiisoft\Yii\Console\Application;
use Yiisoft\Yii\Console\CommandLoader;

require_once __DIR__ . '/vendor/autoload.php';

$app = new Application();

$app->setCommandLoader(new CommandLoader(
    // Any container implementing `Psr\Container\ContainerInterface` for example:
    new Container(ContainerConfig::create()),
    // An array with command names as keys and service IDs as values:
    ['my/custom' => MyCustomCommand::class],
));

$app->run();

Since \Yiisoft\Yii\Console\CommandLoader uses lazy loading of commands, it's necessary to specify the name and description in static properties when creating a command:

use Symfony\Component\Console\Command\Command;
use Yiisoft\Yii\Console\ExitCode;

final class MyCustomCommand extends Command
{
    protected static $defaultName = 'my:custom';
    protected static $defaultDescription = 'Description of my custom command.';
    
    protected function configure(): void
    {
        // ...
    }
    
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        // ...
        return ExitCode::OK;
    }
}

Run the console entry script with your command:

your-console-entry-script my/custom

When naming commands use : as a separator. For example: user:create, user:delete, etc.

Since the package is based on Symfony Console component, refer to its documentation for details on how to use the binary and create your own commands.

Aliases and hidden commands

To configure commands, set the names and aliases in \Yiisoft\Yii\Console\CommandLoader configuration. Names and aliases from the command class itself are always ignored.

The command can be marked as hidden by prefixing its name with |.

'yiisoft/yii-console' => [
    'commands' => [
        'hello' => Hello::class, // name: 'hello', aliases: [], hidden: false
        'start|run|s|r' => Run::class, // name: 'start', aliases: ['run', 's', 'r'], hidden: false
        '|hack|h' => Hack::class, // name: 'hack', aliases: ['h'], hidden: true
    ],
],

Runs PHP built-in web server

You can start local built-in web development server using the command:

./yii serve

Your application will be accessible in your web browser at http://localhost:8080 by default. To configure default settings, set the options in \Yiisoft\Yii\Console\CommandLoader configuration.

'yiisoft/yii-console' => [
    'serve' => [
        'appRootPath' => null,
        'options' => [
            'address' => '127.0.0.1',
            'port' => '8080',
            'docroot' => 'public',
            'router' => 'public/index.php',
        ],
    ],
],

Alternatively, you can pass the settings through the console options. To see the available options, run ./yii serve --help

Documentation

Support

If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack

License

The Yii Console is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

yii-console's People

Contributors

arhell avatar damasco avatar dependabot-preview[bot] avatar dependabot[bot] avatar devanych avatar dood- avatar ezoterik avatar fantom409 avatar githubjeka avatar hamrak avatar hiqsol avatar luizcmarin avatar nex-otaku avatar roxblnfk avatar rustamwin avatar samdark avatar sankaest avatar schmunk42 avatar stylecibot avatar terabytesoftw avatar thenotsoft avatar tomaszkane avatar viktorprogger avatar vjik avatar xepozz avatar yiiliveext avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii-console's Issues

Feature: Decorator over symfony/console logger

We need to make a decorator for \Psr\Log\LoggerInterface that will pass log into \Symfony\Component\Console\Logger\ConsoleLogger and original logger.

What steps will reproduce the problem?

  1. Create console command
  2. Inject \Psr\Log\LoggerInterface into command
  3. Do $this->logger->info('This text should be visible in console'); in execute() method

What is the expected result?

I have output in console:

This text should be visible in console

What do you get instead?

Nothing happend

Replace unnecessary `goto`-statements in Console::prompt() and Console::select()

Actually, my previous PR with some tests for Console helper was inspired exactly by this discovery: one day I looked Yii2 helpers, and suddenly found some... rare syntax in PHP, let's say it that way.
I agree that sometimes it's not so bad to use goto, but I think it's not such case, and perhaps it's better to replace it with cycles.

https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseConsole.php#L799
https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseConsole.php#L872

I can make PR, if you share my opinion, after accepting my tests PR.

New project must rebuild config

What steps will reproduce the problem?

Create new project. Add console command.

What is the expected result?

Console command is available.

What do you get instead?

Console command is not available, until configuration rebuild.

Additional info

Design for configuration rebuild is now (as of 2020-11-12):

  1. Configuration rebuilds every request and every console command in "dev" environment by default.
  2. Configuration DO NOT rebuilds in "prod" environment by default.
  3. New project is created in "dev" environment mode.

Current console package implementation treats non-set variable YII_ENV as "prod" environment, therefore you have "prod" environment mode right after you have created new project.

Q A
Version 3.0 :)
PHP version 7.4
Operating system WSL2

[Feature request] Repeating the header in console table widget

It would be nice if the column headers would be repeated every x data rows, so you don't loose track which column is which. x could be linked to the window height.

I think about something like this:

+---------------+----------+-----------+------------+------------+
| name          | can read | can write | can update | can delete |
+---------------+----------+-----------+------------+------------+
| john.doe      |    1     |     0     |    0       |    0       |
+---------------+----------+-----------+------------+------------+
<about x rows>
+---------------+----------+-----------+------------+------------+
| name          | can read | can write | can update | can delete |
+---------------+----------+-----------+------------+------------+
| jane.doe      |    1     |     1     |    1       |    1       |
+---------------+----------+-----------+------------+------------+

After update happened error

Hello I have an error after last update

PHP Fatal error:  Uncaught Yiisoft\Definitions\Exception\NotFoundException: No definition or class found or resolvable for Psr\EventDispatcher\EventDispatcherInterface while building Yiisoft\Yii\Console\SymfonyEventDispatcher -> Psr\EventDispatcher\EventDispatcherInterface. in .../vendor/yiisoft/di/src/Container.php:406

Here is potential place of error:

<?php

declare(strict_types=1);

use Symfony\Component\Console\CommandLoader\CommandLoaderInterface;
use Symfony\Component\Console\Input\InputOption;
use Yiisoft\Definitions\Reference;
use Yiisoft\Yii\Console\Application;
use Yiisoft\Yii\Console\CommandLoader;
use Yiisoft\Yii\Console\SymfonyEventDispatcher;

/** @var array $params */

return [
    CommandLoaderInterface::class => [
        'class' => CommandLoader::class,
        '__construct()' => [
            'commandMap' => $params['yiisoft/yii-console']['commands'],
        ],
    ],

    Application::class => [
        'class' => Application::class,
        '__construct()' => [
            Reference::to(SymfonyEventDispatcher::class),
            $params['yiisoft/yii-console']['name'],
            $params['yiisoft/yii-console']['version'],
        ],
        'setAutoExit()' => [$params['yiisoft/yii-console']['autoExit']],
        'setCommandLoader()' => [Reference::to(CommandLoaderInterface::class)],
        'addOptions()' => [
            new InputOption(
                'config',
                null,
                InputOption::VALUE_REQUIRED,
                'Set alternative configuration name'
            ),
        ],
    ],
];

Shortcuts do not work

With : separator you can run command doctrine:migrations:diff by d:mi:di.
This do not work for / separator. E.g. debug/reset can't be executed by d/r

update irc link

What steps will reproduce the problem?

What is the expected result?

What do you get instead?

Additional info

Q A
Version 1.0.?
PHP version
Operating system

update src folder links

What steps will reproduce the problem?

http=>https

What is the expected result?

What do you get instead?

Additional info

Q A
Version 1.0.?
PHP version
Operating system

cebe/markdown should be in require, not require-dev

mbp:github-dashboard didou$ ./vendor/bin/yii message/config-template --help
Exception 'Error' with message 'Class 'cebe\markdown\Parser' not found'

in /Users/didou/yii3/github-dashboard/vendor/yiisoft/yii-console/src/Markdown.php:24

Simplify configuration, make it merge-able

Current configuration:

<?php

return [
    'app' => function (\Psr\Container\ContainerInterface $container) {
        $app = new \Yiisoft\Yii\Console\Application();
        $loader = new \Symfony\Component\Console\CommandLoader\ContainerCommandLoader($container, [
            'serve' => 'serve',
        ]);
        $app->setCommandLoader($loader);
        return $app;
    },

    // commands
    'serve' => \Yiisoft\Yii\Console\Command\Serve::class,
];

Issues:

  1. Have to add serve in two places.
  2. app config is not merge-able.

Change 'app' to Application::class in config

Current version

return [
     'app' => function () {
           ...
     },
]

and in yii

$container->get('app')->run();

After:

return [
     Application::class => function () {
           ...
     },
]

and in yii

$container->get(Application::class)->run();

XDebug doesn't work

What steps will reproduce the problem?

  1. Enable XDebug profiling
  2. Set breakpoint
  3. Run XDEBUG_TRIGGER=yes php -dxdebug.mode=debug yii serve in console
  4. Run code where you set breakpoint

What is the expected result?

IDE catches the running at needed line

What do you get instead?

IDE doesn't catch nothing

Supposed solution

The problem is located on https://github.com/yiisoft/yii-console/blob/master/src/Command/Serve.php#L97
That command should consider arguments what was passed to original process.

yii\console\widgets\Table improved: add some rows

What steps will reproduce the problem?

I must set all of rows in one piece

    public function setRows(array $rows)
    {
        $this->_rows = array_map('array_values', $rows);
        return $this;
    }

I wish to add row-by-row in my iterator's...

Error Help controllers actions list

This is (I think) an error also in Yii2 console.

Help controller actions list is wrong because \yii\console\Application has wrong controllerNamespace that returns wrong list here:

$controllerPath = $module->getControllerPath();

schermata 2019-01-13 alle 00 11 18

This is the test match list:

help
help/index
help/list
help/list-action-options
help/usage
magic/e-tag
magic/e-tag/delete
magic/e-tag/list-e-tags
magic/subFolder/sub
magic/subFolder/sub/test

but if we look at controllers folder list :

schermata 2019-01-13 alle 00 18 22

Show full path to file in error message

The console error message only contains the filename, for example "In GroupManager.php line 131:".

I would like you to add the full path to the file in order to better understand the package of the file.

Find a way not to instantiate every command when getting a command list

Currently Symfony console instantiates every command when making a list. That means all the dependencies are instantiated as well. Some of these such as Cycle, are making SQL queries.

Overall, instantiating every command isn't needed since what we need is some meta-data that seems to be OK as static.

TODO:

  • Support static $defaultDescription property. #124
  • Document it.
  • Apply to yii-cycle.
  • Apply to debug.
  • Apply to migrations.
  • Apply to router/list (demo).
  • Apply to user/create (demo).

add application-base init commands

What steps will reproduce the problem?

Install a project template, people complaining about too complicated setup.

What is the expected result?

Example commands

$ yii init
Querying application bases...
[1] yii-base-web
[2] yii-base-api
[3] yii-base-cli
Which one(s) do you want to install?

What do you get instead?

Copy and paste command from docs.

Console::stdOut and testing

What steps will reproduce the problem?

Create a console command that does echo.
Try to create an automated test for it.

public function actionEcho($str) {
    $this->stdOut($str);
}

What is the expected result?

I should be able to test my code.
I should not be getting output on screen when running my tests.

What do you get instead?

Due to the fact BaseConsole::stdOut uses fwrite(\STDOUT it is hard to properly test the output.

Additional info

Incorrect controller path detection

What steps will reproduce the problem?

1, Folder structure

- App
  -- Commands
      --- HelloController.php
- config
   -- common.php
   -- console.php
   -- params.php
...
- vendor
- composer.json

2, composer.json

 { 
...
 "extra": {
        "branch-alias": {
            "dev-master": "3.0.x-dev"
        },
        "config-plugin": {
            "params": ["config/params.php"],
            "common": ["config/common.php"],
            "console": [
                "$common",
                "config/console.php"
            ]
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "App",
            "Lib\\": "Lib"
        }
    },
}
...
  1. config parts

console.php

return [
    'app' => [
        'controllerNamespace' => 'App\Commands', // (Also trying with App\Commands::class)
    ],
];

common.php

return [
   'app' => [
        'basePath' => dirname(__DIR__) . '/App',
    ],
   ....
]

When i run
/vendor/bin/yii hello/index - all correct, it works

When i run
/vendor/bin/yii help - gotcha error

Error: Invalid path alias: @/App/Commands

Also if i add in my HelloController@actionIndex print app->controllerPath, error also reproduced

public function actionIndex(): int
    {
        $this->stdout('Hello, Yii3'.PHP_EOL, Console::FG_PURPLE); //It`s normal
        // With this line  error reproduced
        $this->stdout($this->app->controllerPath.PHP_EOL, Console::FG_PURPLE);

        return ExitCode::OK;
    }

What is the expected result?

alias should be '@App/Commands'

What do you get instead?

Error: Invalid path alias: @/App/Commands

Additional info

Q A
Yii version 3.0.? -latest dev-master
PHP version 7.3
Operating system ArchLinux

How about add way to create alias for console command options within value of this option?

@bscheshirwork commented on Oct 15, 2018, 8:42 AM UTC:

What steps will reproduce the problem?

I try to improve alias -y #16787 but I can't use this construction

What is the expected result?

Way to create alias within value of option

What do you get instead?

not implemented

Additional info

Fr example we can use syntax of 2-element array

['aliasKey' => ['commandOption', 'optionValue']]

we can replace

| | public function optionAliases() |
| | { |
| | return array_merge(parent::optionAliases(), [ |
| | 'C' => 'comment', |
| | 'f' => 'fields', |
| | 'p' => 'migrationPath', |
| | 't' => 'migrationTable', |
| | 'F' => 'templateFile', |
| | 'P' => 'useTablePrefix', |
| | 'c' => 'compact', |
| | ]); |
| | } |

| | $params[$optionAliases[$name]] = $value; |

->

    public function optionAliases()
    {
        return array_merge(parent::optionAliases(), [
            'C' => 'comment',
            'f' => 'fields',
            'p' => 'migrationPath',
            't' => 'migrationTable',
            'F' => 'templateFile',
            'P' => 'useTablePrefix',
            'c' => 'compact',
            'y' => ['-interactive', 0],
        ]);
    }
                        if (is_array($optionAliases[$name])) {
                            $params[array_shift($optionAliases[$name])] = array_shift($optionAliases[$name]);
                        } else {
                            $params[$optionAliases[$name]] = $value;
                        }

How about this?

Q A
Yii version dev
PHP version 7.2.10
Operating system alpine3.8

This issue was moved by samdark from yiisoft/yii2#16788.

Default options for ./yii serve must be configurable

When I develop different projects, there is a need to run them at the same time. I need to configure for each project its own port for ./yii serve command.

Class \Yiisoft\Yii\Console\Command\Serve is finalized and DEFAULT_PORT is private const. I can't extend it and redeclare DEFAULT_PORT.

I can write script serve with simple content ./yii serve --port=8081 etc. and ignore it by git. But this solution looks like a crutch

./yii serve not works in windows PHP 8.0, PHP 8.1.

https://github.com/yii-extension/simple-app/actions/runs/1452155844

  1. ErrorCest: See error page.
    Test tests\acceptance\ErrorCest.php:testErrorPage

[GuzzleHttp\Exception\ConnectException] cURL error 7: Failed to connect to localhost port 8080: Connection refused (see
https://curl.haxx.se/libcurl/c/libcurl-errors.html) for http://localhost:8080/about

Scenario Steps:

  1. $I->amOnPage("/about") at tests\acceptance\ErrorCest.php:14
  2. // I am going to go to the error page

#1 D:\a\simple-app\simple-app\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:210
#2 D:\a\simple-app\simple-app\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:158
#3 D:\a\simple-app\simple-app\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:110
#4 D:\a\simple-app\simple-app\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php:47
#5 D:\a\simple-app\simple-app\vendor\guzzlehttp\guzzle\src\PrepareBodyMiddleware.php:35
#6 D:\a\simple-app\simple-app\vendor\guzzlehttp\guzzle\src\Middleware.php:37
#7 D:\a\simple-app\simple-app\vendor\guzzlehttp\guzzle\src\RedirectMiddleware.php:55
#8 D:\a\simple-app\simple-app\vendor\guzzlehttp\guzzle\src\Middleware.php:63
#9 D:\a\simple-app\simple-app\vendor\guzzlehttp\guzzle\src\HandlerStack.php:75
#10 D:\a\simple-app\simple-app\vendor\guzzlehttp\guzzle\src\Client.php:331

With the integrated PHP server curl does not fail.

"list <namespace>" command does not work

For example ./yii list debug:

2023-02-10 13:23:45.064400 [error][application] Symfony\Component\Console\Exception\NamespaceNotFoundException: There are no commands defined in the "debug" namespace. in /var/www/app/vendor/symfony/console/Application.php:632 while running console command "list".

Message context:

exception: Symfony\Component\Console\Exception\NamespaceNotFoundException: There are no commands defined in the "debug" namespace. in /var/www/app/vendor/symfony/console/Application.php:632
Stack trace:
#0 /var/www/app/vendor/symfony/console/Descriptor/ApplicationDescription.php(87): Symfony\Component\Console\Application->findNamespace('debug')
#1 /var/www/app/vendor/symfony/console/Descriptor/ApplicationDescription.php(64): Symfony\Component\Console\Descriptor\ApplicationDescription->inspectApplication()
#2 /var/www/app/vendor/symfony/console/Descriptor/TextDescriptor.php(185): Symfony\Component\Console\Descriptor\ApplicationDescription->getCommands()
#3 /var/www/app/vendor/symfony/console/Descriptor/Descriptor.php(43): Symfony\Component\Console\Descriptor\TextDescriptor->describeApplication(Object(Yiisoft\Yii\Console\Application), Array)
#4 /var/www/app/vendor/symfony/console/Helper/DescriptorHelper.php(65): Symfony\Component\Console\Descriptor\Descriptor->describe(Object(Yiisoft\Yii\Console\Output\ConsoleBufferedOutput), Object(Yiisoft\Yii\Console\Application), Array)
#5 /var/www/app/vendor/symfony/console/Command/ListCommand.php(71): Symfony\Component\Console\Helper\DescriptorHelper->describe(Object(Yiisoft\Yii\Console\Output\ConsoleBufferedOutput), Object(Yiisoft\Yii\Console\Application), Array)
#6 /var/www/app/vendor/symfony/console/Command/Command.php(312): Symfony\Component\Console\Command\ListCommand->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Yiisoft\Yii\Console\Output\ConsoleBufferedOutput))
#7 /var/www/app/vendor/symfony/console/Application.php(1040): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Yiisoft\Yii\Console\Output\ConsoleBufferedOutput))
#8 /var/www/app/vendor/symfony/console/Application.php(314): Symfony\Component\Console\Application->doRunCommand(Object(Symfony\Component\Console\Command\ListCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Yiisoft\Yii\Console\Output\ConsoleBufferedOutput))
#9 /var/www/app/vendor/symfony/console/Application.php(168): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Yiisoft\Yii\Console\Output\ConsoleBufferedOutput))
#10 /var/www/app/vendor/yiisoft/yii-runner-console/src/ConsoleApplicationRunner.php(62): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Yiisoft\Yii\Console\Output\ConsoleBufferedOutput))
#11 /var/www/app/yii(11): Yiisoft\Yii\Runner\Console\ConsoleApplicationRunner->run()
#12 {main}
time: 1676035425.064434
memory: 5885920
category: 'application'

How about add alias -y to migrate commands?

@bscheshirwork commented on Oct 15, 2018, 7:44 AM UTC:

What steps will reproduce the problem?

I must typing --interactive=0 or confirm command each time
This keyword is not so short...

What is the expected result?

I expect the sugar alias options -y for applying migration's command

What do you get instead?

non-autocomplited --interactive=0 only

Additional info

https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php#L51-L54

Q A
Yii version dev
PHP version
Operating system

This issue was moved by samdark from yiisoft/yii2#16787.

Fatal errors exit silently

Running console command, if a fatal error happens, I get no error message.

This behavior is annoying and makes it harder to debug problems.

What steps will reproduce the problem?

Run console command with fatal bug, for example missing argument in some constructor call.

What is the expected result?

Eror is displayed in console output

What do you get instead?

No error messages, just silently exit with error code 1

Additional info

Q A
Version dev-master
PHP version 7.4.6
Operating system Windows

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.