Coder Social home page Coder Social logo

laravel-console-menu's Introduction

Static Analysis Latest Stable Version License

About Laravel Console Menu

Laravel Console Menu was created by, and is maintained by Nuno Maduro, and is a php-school/cli-menu wrapper for Laravel Console Commands.

Installation

Requires PHP 8.1+

Require Laravel Console Menu using Composer:

composer require nunomaduro/laravel-console-menu

Usage

Quick Setup

class MenuCommand extends Command
{
    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $option = $this->menu('Pizza menu', [
            'Freshly baked muffins',
            'Freshly baked croissants',
            'Turnovers, crumb cake, cinnamon buns, scones',
        ])->open();

        $this->info("You have chosen the option number #$option");
    }
}

Setup with a question

class MenuCommand extends Command
{
    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $option = $this->menu('Pizza menu')
                    ->addOption('mozzarella', 'Mozzarella')
                    ->addOption('chicken_parm', 'Chicken Parm')
                    ->addOption('sausage', 'Sausage')
                    ->addQuestion('Make your own', 'Describe your pizza...')
                    ->addOption('burger', 'Prefer burgers')
                    ->setWidth(80)
                    ->open();
        
        $this->info("You have chosen the text option: $option");
    }
}

Setup with advanced option, in this case, a password

class MenuCommand extends Command
{
    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $menu = $this->menu('Pizza menu')
                    ->addOption('mozzarella', 'Mozzarella')
                    ->addOption('chicken_parm', 'Chicken Parm')
                    ->addOption('sausage', 'Sausage')
                    ->addQuestion('Make your own', 'Describe your pizza...');
        
        $itemCallable = function (CliMenu $cliMenu) use ($menu) {
            $cliMenu->askPassword()
                ->setValidator(function ($password) {
                    return $password === 'secret';
                })
                ->setPromptText('Secret password?')
                ->ask();

            $menu->setResult('Free spice!');

            $cliMenu->close();
        };
        $menu->addItem('Add extra spice for free (password needed)', $itemCallable);


        $option = $menu->addOption('burger', 'Prefer burgers')
            ->setWidth(80)
            ->open();

        $this->info("You have chosen the text option: $option");
    }
}

Appearance

Available colors: black, red, green, yellow, blue, magenta, cyan, white.

  $this->menu($title, $options)
      ->setForegroundColour('green')
      ->setBackgroundColour('black')
      ->setWidth(200)
      ->setPadding(10)
      ->setMargin(5)
      ->setExitButtonText("Abort") // remove exit button with ->disableDefaultItems()
      ->setTitleSeparator('*-')
      ->addLineBreak('<3', 2)
      ->addStaticItem('AREA 2')
      ->open();

Check out the full documentation here.

Contributing

Thank you for considering to contribute to Laravel Console Menu. All the contribution guidelines are mentioned here.

You can have a look at the CHANGELOG for constant updates & detailed information about the changes. You can also follow the twitter account for latest announcements or just come say hi!: @enunomaduro

Support the development

Do you like this project? Support it by donating

License

Laravel Console Menu is an open-sourced software licensed under the MIT license.

laravel-console-menu's People

Contributors

aydinhassan avatar edgrosvenor avatar fridzema avatar ijpatricio avatar joaorobertopb avatar laravel-shift avatar nunomaduro avatar owenvoke avatar stylecibot 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  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

laravel-console-menu's Issues

How to inherit terminal color

Playing around with project and I see an issue which I am not sure how to handle. I know I can define the background color, but I am looking for a way to use the terminal background? I see it is using a default of light blue which is tough to read (see screenshot).

image

subMenu usage

Hi,

I try to add sub-menu, but failed.
I already took a look at php-school/cli-menu, but can't figure out how make it work.

I tried to add a subItem, a subOption, a subMenu but in the worst case it failed, in the best, it asks for a CliMenuBuilder or a local CliMenu…

I think ther is little lack of documentation here regarding the specific features usage or the way we can use the cli-menu behind the wrapper.

Could you help me, please ?

Testing Menus

Hey, I was wondering if anyone has hinted at testing these menus. I tried calling the command that shows the menu with $this->artisan(), but the menu shows up in the console and blocks.

I was thinking if we could add an API to it like

$this->artisan('command')
  ->expectMenu(
    fn (TestMenu $menu) => $menu->hasOption('something')->select('something')
  );

(not sure if any of this is possible yet, just thinking of how I'd like to test it if it was possible)

Include w/ Laravel Zero by default?

Nice package, curious if you are going to include out of box w/ Laravel Zero, or leave it up to users to include (I know I will include everytime)

setResult usage

Hi,

I can't figure out how I can use the setResult method.

I miss an addCheckbox method so here is my workaround

$menu = $this->menu("Pick your items");

$selected = collect([]);

$list = collect(['Mozarella', 'Mushroom', 'Origan', 'Emmental']);
$list->each(function ($item) use ($menu, &$selected) {
    $menu->addCheckboxItem(ucfirst($item), function ($menu) use ($item, $selected) {
        $selected->push($item);
        $menu->setResult($selected);
    });
});

$items = $menu->open();

Unfortunately, this does not work because $menu is a CLIMenu instance instead of a Menu one:

Call to undefined method PhpSchool\CliMenu\CliMenu::setResult()

How are we supposed to use the Menu::setResult method ?

Set width to 100%

Hi!

Currently I'm experimenting with this package in combination with Laravel-Zero (awesome work on both them btw πŸ‘ !) but I had a small question, I'm trying to build a menu which has a full height and full width. However I already saw that cli-menu doesn't support setting the height of a menu, so that's out of the question. But I am currently doing the following to achieve a full width menu;

Code example:

        $option = $this->menu('Pizza menu', [
            'Freshly baked muffins',
            'Freshly baked croissants',
            'Turnovers, crumb cake, cinnamon buns, scones',
        ])
            ->setWidth($this->menu()->getTerminal()->getWidth())
            ->open();

Is there a more readable way of achieving the same result ? If not, would you accept a PR which the same result with the following syntax?

Proposed syntax:

        $option = $this->menu('Pizza menu', [
            'Freshly baked muffins',
            'Freshly baked croissants',
            'Turnovers, crumb cake, cinnamon buns, scones',
        ])
            ->setFullWidth()
            ->open();

Add `separator` line support in options

Give something like, display the hyphen as a separator

$options = ['Item1','Item2','-','Item3'];

Currently, the only way to accomplish this is to use something like str_repeat('-',80)

However, this breaks if you have set the width using setWidth (see related issue)

Call to Undefined Method

Hey Nuno

When working with menus in Zero I'm getting this error:

Call to undefined method NunoMaduro\LaravelConsoleMenu\Menu::setUnselectedMarker()

I don't need it, I was just testing out different settings via the Zero docs for menus. But I thought you should know.

PHP version requirement

Hehe, readme says "works with 7.0+"

  Problem 1
    - This package requires php 7.1.0 but your PHP version (7.1.12) does not satisfy that requirement.

Default background and and white foreground, bad hightlight color

When using defaultBackgroundColor (uses the color of terminal) and a white foreground, the highlight text color is white (should be either default or something other than white. I am looking for something like highlightColor

        $option = $this->menu('Select :', ['item 1,item 2'])
            ->setBackgroundColour('default')
            ->setForegroundColour('white')
            ->setExitButtonText('None')
            ->setWidth(60)
            ->open();

produces

image

Sub-menus and go-back

Would it be possible to add support for menu depths? So you could create sub-menus with the ability to go back to the main menu?

If option item text is greater than width, it has syntax error

Using the following

$options = ['Item 1',str_repeat('-', 80),'Item 3'];
$option = $this->menu('Select', $options)
   ->setWidth(40);

produces the following error

 Whoops\Exception\ErrorException  : str_repeat(): Second argument has to be greater than or equal to 0

  at /Users/merickson/docker/localenv/m4-tools/vendor/php-school/cli-menu/src/CliMenu.php: 319
  315:                 str_repeat(' ', $this->style->getMargin()),
  316:                 $setColour,
  317:                 str_repeat(' ', $this->style->getPadding()),
  318:                 $row,
  319:                 str_repeat(' ', $this->style->getRightHandPadding(mb_strlen(s::stripAnsiEscapeSequence($row)))),
  320:                 $unsetColour,
  321:                 str_repeat(' ', $this->style->getMargin())
  322:             );
  323:         }, $rows);
  324:     }

  Exception trace:

  1   str_repeat(" ")
      /Users/merickson/docker/localenv/m4-tools/vendor/php-school/cli-menu/src/CliMenu.php : 319

  2   PhpSchool\CliMenu\CliMenu::PhpSchool\CliMenu\{closure}("  --------------------------------------------------------------------------------")
      [internal] : 0

  Please use the argument -v to see more details.


Support cli-menu 4.0?

In order to make this package really useful for me, I need it to support php-school/cli-menu ^4.0. I've forked this package and am working with it locally and so far, it seems like it won't take anything more than a version bump in composer.json. I'll fix anything I encounter within the scope of what I'm working on, but I might not cover every single edge case. I'm happy to PR it when I'm done if you're interested. But will just keep it to myself if you'd rather not mess with the newer version.

Submenu Issues

I'm having issues with Submenus.

For some reason every time I create a subMenu, it jumps directly to the submenu instead of the main menu.

I think it must be some compatibility issue. Any plans to update the dependency to cli-menu 3.1?

Method menu does not exist.

Hi,
I have just created a new console command:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class Test extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $option = $this->menu('Pizza menu', [
            'Freshly baked muffins',
            'Freshly baked croissants',
            'Turnovers, crumb cake, cinnamon buns, scones',
        ])->open();

        $this->info("You have chosen the option number #$option");
    }
}

and I doesn't seem to work.

This is the error that I'm getting:

root@tpt:/var/www/html/tpt# php artisan test

In Macroable.php line 96:
                               
  Method menu does not exist.

Any idea what's wrong ?

Strange display error

Hi,

after upgrading to 2.0, I have some strange displaying bug:
image

I use the following code:
$option = $this->menu('Install ' . $sTitle . '?', [ 'yes', 'no', ])->disableDefaultItems()->open();

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.