• Stars
    star
    365
  • Rank 116,851 (Top 3 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 10 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Use Symfony forms for Console command input

Symfony Console Form

By Matthias Noback

This package contains a Symfony bundle and some tools which enable you to use Symfony Form types to define and interactively process user input from the CLI.

Installation

composer require matthiasnoback/symfony-console-form

Enable Matthias\SymfonyConsoleForm\Bundle\SymfonyConsoleFormBundle in the kernel of your Symfony application.

    <?php
    // app/AppKernel.php

    public function registerBundles()
    {
        $bundles = array(
            // ...
            new Matthias\SymfonyConsoleForm\Bundle\SymfonyConsoleFormBundle(),
        );
    }

Usage

Follow the steps below or just clone this project, then run:

php test/console.php form:demo

Set up the form

<?php

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\Country;
use Symfony\Component\Validator\Constraints\Email;

class DemoType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'name',
                'text',
                [
                    'label' => 'Your name',
                    'required' => true,
                    'data' => 'Matthias'
                ]
            )
            ...
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(['data_class' => 'Matthias\SymfonyConsoleForm\Tests\Data\Demo']);
    }

    public function getName()
    {
        return 'test';
    }
}

The corresponding Demo class looks like this:

<?php

class Demo
{
    public $name;
    ...
}

Create the console command; use the form helper

<?php

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Matthias\SymfonyConsoleForm\Console\Helper\FormHelper;

class TestCommand extends Command
{
    protected function configure()
    {
        $this->setName('form:demo');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $formHelper = $this->getHelper('form');
        /** @var FormHelper $formHelper */

        $formData = $formHelper->interactUsingForm(DemoType::class, $input, $output);

        // $formData is the valid and populated form data object/array
        ...
    }
}

When you provide command-line options with the names of the form fields, those values will be used as default values.

If you add the --no-interaction option when running the command, it will submit the form using the input options you provided.

If the submitted data is invalid the command will fail.

Using simpler forms with custom names

<?php

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Matthias\SymfonyConsoleForm\Console\Helper\FormHelper;

class TestCommand extends Command
{
    protected function configure()
    {
        $this->setName('form:demo');
        $this->addOption('custom-option', null, InputOption::VALUE_OPTIONAL, 'Your custom option', 'option1')
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $formHelper = $this->getHelper('form');
        /** @var FormHelper $formHelper */

        $formData = $formHelper->interactUsingNamedForm('custom-option', ChoiceType::class, $input, $output, [
            'label' => 'Your label',
            'help' => 'Additional information to help the interaction',
            'choices' => [
                'Default value label' => 'option1',
                'Another value Label' => 'option2',
            ]
        ]);

        // $formData will be "option1" or "option2" and option "--custom-option" will be used as default value
        ...
    }
}

Nested Forms

If you have a complex compound form, you can define options and reference form children using square brackets:

<?php

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Matthias\SymfonyConsoleForm\Console\Helper\FormHelper;

class TestCommand extends Command
{
    protected function configure()
    {
        $this
            ->addOption('user[username]', null, InputOption::VALUE_OPTIONAL)
            ->addOption('user[email]', null, InputOption::VALUE_OPTIONAL)
            ->addOption('user[address][street]', null, InputOption::VALUE_OPTIONAL)
            ->addOption('user[address][city]', null, InputOption::VALUE_OPTIONAL)
            ->addOption('acceptTerms', null, InputOption::VALUE_OPTIONAL)
        ;
    }
    ...
}

TODO

  • Maybe: provide a way to submit a form at once, possibly using a JSON-encoded array
  • Add more functional tests
  • Show form label of root form
  • Show nesting in form hierarchy using breadcrumbs
  • When these things have been provided, release this as a package (or multiple packages for stand-alone use)

More Repositories

1

TalisORM

An ORM for "ORMless" persistance of DDD-inspired domain models
PHP
166
star
2

random-disaster-bundle

ProjectBundle a.k.a. RandomDisasterBundle
PHP
115
star
3

live-code-coverage

Generate code coverage reports on a live server
PHP
113
star
4

symfony-service-definition-validator

A set of tools for validating Symfony service definitions.
PHP
89
star
5

convenient-immutability

Make objects initially inconsistent, yet eventually immutable
PHP
78
star
6

php-ast-inspector

Kind of a step-debugger for your Abstract Syntax Tree
PHP
62
star
7

symfony-bundle-plugins

Allow Symfony bundles to have plugins
PHP
57
star
8

naive-serializer

A naive JSON serializer which recursively converts an object graph to and from JSON, without any configuration or custom code.
PHP
52
star
9

badges

Package which will receive many nice badges
PHP
49
star
10

layers-ports-and-adapters-workshop

Sandbox project for the "Advanced Web Application Architecture" training.
PHP
47
star
11

building-autonomous-services-workshop

Code and assignments for the "Building Autonomous Services" workshop module.
PHP
42
star
12

microsoft-translator

PHP library for making calls to the Microsoft Translator V3 API
PHP
39
star
13

phpunit-asynchronicity

Library for asserting things that happen asynchronously with PHPUnit
PHP
35
star
14

decoupling-from-infrastructure-workshop

Sandbox project for the "Decoupling from infrastructure" workshop
PHP
35
star
15

broadway-serialization

Serialization helpers for Broadway
PHP
28
star
16

hexagonal-architecture-workshop

PHP
28
star
17

php-workshop-tools

A set of useful utilities for PHP workshop code bases that I would otherwise write again and again.
PHP
25
star
18

behat-local-code-coverage-extension

Behat extension for generating (local) code coverage data.
PHP
24
star
19

high-quality-bundles-project

The "Symfony Standard Edition" adapted for my High Quality Bundles workshop
PHP
23
star
20

behat-expect-exception

The missing Behat feature: expecting exceptions.
PHP
22
star
21

simple-bus

Warning: this project has been moved to its own organization and the package has been split. Please take a look at its new location:
PHP
22
star
22

leanpub-api-client

PHP
22
star
23

recipes-for-decoupling-phpstan-rules

Repository containing all the PHPStan rules from the book "Recipes for Decoupling"
PHP
21
star
24

doctrine-orm-value-object

A library for using value objects inside Doctrine entities
PHP
20
star
25

php-duck-typing

A simple library for duck-typing in PHP 7.
PHP
18
star
26

tactical-ddd-workshop

Code and assignments for the "Tactical DDD" workshop module.
PHP
18
star
27

LazyServicesBundle

PHP
17
star
28

php-for-the-web

The source code for the book "PHP for the Web - Learning PHP without a framework"
PHP
16
star
29

behat-remote-code-coverage-extension

Behat extension for generating (remote) code coverage data.
PHP
13
star
30

php-parser-instantiation-printer

For printing the code needed to instantiate the given PHP-Parser nodes
PHP
13
star
31

aggregate-design-workshop

Sandbox project for my Domain-Driven Aggregate Design workshop
PHP
12
star
32

domstreamwrapper

A PHP stream wrapper for modifying DOM node values using traditional file manipulation functions
PHP
10
star
33

cqrs-and-event-sourcing-workshop

Code and assignments for the "CQRS & Event Sourcing" workshop module.
PHP
10
star
34

code-sniffer-sniff-dsl

DSL for writing sniffs for PHP_CodeSniffer
PHP
10
star
35

ConsoleCommandGeneratorBundle

Bundle for generating Symfony2 commands
PHP
9
star
36

nginx-multi-host-docker

Docker Compose setup for multi-hostname Let's Encrypt-secured websites.
Shell
9
star
37

docker-swarm-workshop

An introduction to Docker Swarm
Shell
9
star
38

leanpub-sampler

A simple script for generating samples for Leanpub books
PHP
9
star
39

practicing-domain-driven-entity-and-value-object-design

Sandbox project for the "Domain-Driven Entity and Value Object Design" training.
PHP
8
star
40

workshop-unit-testing

Accompanying project for my PHPUnit workshop
PHP
8
star
41

phpstan-twig-analysis

PHP
7
star
42

docker-compose-workshop

An introduction to Docker Compose
PHP
7
star
43

symfony-controller-annotation

Helper library for creating event listeners that influence a Symfony application flow based on annotations
PHP
7
star
44

docker-workshop

Getting started with Docker
PHP
7
star
45

php-coding-dojo

Empty project which can be used in a PHP and PHPUnit-oriented coding dojo
PHP
7
star
46

service-integration-workshop

Code and assignments for the "Integration Bounded Contexts" workshop module.
PHP
6
star
47

advanced-testing-workshop

Code and assignments for the "Advanced Testing" workshop module.
PHP
6
star
48

testing-playground

Playground for (unit/integration/acceptance) testing-oriented workshops.
PHP
6
star
49

living-documentation

A framework for living documentation for PHP projects (very much a work in progress).
PHP
5
star
50

modeling-exercises

Modeling exercises
PHP
4
star
51

symfony-decoupling-workshop

Sandbox project for the Symfony decoupling workshop
PHP
4
star
52

tail-event-stream

A simple, tail-based event stream
PHP
4
star
53

symfony-console-integration-test

This project is a demo of an integration test for a Symfony console command
PHP
4
star
54

phpstan-workshop

Sandbox project for the PHPStan workshop
PHP
4
star
55

MicrosoftTranslatorBundle

Symfony2 bundle for the microsoft-translator PHP library
PHP
4
star
56

doctrine-dbal-test-service-provider

Service provider for tests in need of a Doctrine DBAL connection
PHP
3
star
57

gherkin-features-html-exporter

An exporter for Gherkin feature files to HTML, written in PHP
PHP
3
star
58

test-first-application-development-workshop

Sandbox project for the "Test-Driven Application Development" training.
PHP
3
star
59

make-workshop

Assignments and source files for the Make workshop
Dockerfile
2
star
60

amqp-integration-patterns

For now: a playground
PHP
2
star
61

static-analysis-and-automated-refactoring-workshop

Sandbox environment for the "Static Analysis and Automated Refactoring" workshop
PHP
2
star
62

the-page-class

An exercise in refactoring legacy code
PHP
2
star
63

symfony-dependency-injection-workshop

Sandbox project for a Symfony Dependency Injection workshop
PHP
2
star
64

phpunit-test-service-container

Simple service container for PHPUnit tests
PHP
2
star
65

mail-comments-common

PHP
2
star
66

RomanNumeralsKataJava

Java
1
star
67

MicrosoftTranslatorServiceProvider

Silex service provider for using the Microsoft Translator V2 API
PHP
1
star
68

churn-php-visualization

HTML
1
star
69

MarsRoverKata

Mars rover kata in Java for the Java Beginners Meetup.
Java
1
star
70

moving-forward-with-legacy-code-workshop

Sandbox project accompanying the "Moving Forward With Legacy Code" workshop
PHP
1
star
71

doctrine-orm-value-object-bundle

PHP
1
star
72

decoupling-workshop

Sandbox project for the Principles of Decoupling workshop
PHP
1
star
73

doctrine-orm-test-service-provider

Service provider for tests in need of a Doctrine entity manager
PHP
1
star