Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[make:event] Add command for making Event class #1574

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 143 additions & 0 deletions src/Maker/MakeEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
<?php

/*
* This file is part of the Symfony MakerBundle package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\MakerBundle\Maker;

use Symfony\Bundle\MakerBundle\ConsoleStyle;
use Symfony\Bundle\MakerBundle\DependencyBuilder;
use Symfony\Bundle\MakerBundle\Doctrine\DoctrineHelper;
use Symfony\Bundle\MakerBundle\Generator;
use Symfony\Bundle\MakerBundle\InputConfiguration;
use Symfony\Bundle\MakerBundle\Validator;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Question\Question;
use Symfony\Contracts\EventDispatcher\Event;

/**
* @author Ippei Sumida <[email protected]>
*/
class MakeEvent extends AbstractMaker
{
public function __construct(
private readonly DoctrineHelper $doctrineHelper,
) {
}

public static function getCommandName(): string
{
return 'make:event';
}

public static function getCommandDescription(): string
{
return 'Create a event class.';
}

public function configureCommand(Command $command, InputConfiguration $inputConfig): void
{
$command
->addArgument('name', InputArgument::OPTIONAL, 'The name of the event class (e.g. <fg=yellow>OrderPlacedEvent</>)')
->setHelp(file_get_contents(__DIR__.'/../Resources/help/MakeEvent.txt'))
;
}

public function configureDependencies(DependencyBuilder $dependencies): void
{
$dependencies
->addClassDependency(Event::class, 'event-dispatcher')
;
}

public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator): void
{
$name = $input->getArgument('name');
if (null === $name) {
$name = $io->ask('Event class name (e.g. <fg=yellow>OrderPlacedEvent</>)', null, [Validator::class, 'notBlank']);
}
$eventClassNameDetails = $generator->createClassNameDetails(
$name,
'Event\\',
'Event'
);

$fields = [];
$useClasses = [];
while (true) {
$newField = $this->askForNextField($io);
if (null === $newField) {
break;
}
$fields[] = $newField;
$useClass = match (true) {
class_exists($this->doctrineHelper->getEntityNamespace().'\\'.$newField['type']) => $this->doctrineHelper->getEntityNamespace().'\\'.$newField['type'],
class_exists($newField['type']) => $newField['type'],

default => null,
};
if (
$useClass
&& !\in_array($useClass, $useClasses, true)
) {
$useClasses[] = $useClass;
}
}

asort($useClasses);
$generator->generateClass(
$eventClassNameDetails->getFullName(),
'event/Event.tpl.php',
[
'event_class_name' => $eventClassNameDetails->getShortName(),
'fields' => $fields,
'useClasses' => $useClasses,
]
);

$generator->writeChanges();

$this->writeSuccessMessage($io);

$io->text([
'Next: Open your event and add your logic.',
'Find the documentation at <fg=yellow>https://symfony.com/doc/current/event_dispatcher.html</>',
]);
}

/**
* @return array{'name': string, 'type': string, 'nullable': bool}|null
*/
public function askForNextField(ConsoleStyle $io): ?array
{
$fieldName = $io->ask('Field name (press <fg=yellow>enter</> to stop adding fields)', null);
if (null === $fieldName) {
return null;
}

$question = new Question('Field type (e.g. <fg=yellow>string</>)', 'string');
$autocompleteValues = ['string', 'int', 'float', 'bool', 'array', 'object', 'callable', 'iterable', 'void', \DateTime::class, \DateTimeImmutable::class];
$autocompleteValues = array_merge($autocompleteValues, $this->doctrineHelper->getEntitiesForAutocomplete());
$question->setAutocompleterValues($autocompleteValues);
$question->setValidator([Validator::class, 'notBlank']);
$fieldType = $io->askQuestion($question);

$visibility = $io->choice('Field visibility (public, protected, private)', ['public', 'private', 'protected'], 'public');
$nullable = $io->confirm('Can this field be null (nullable)', false);

return [
'name' => $fieldName,
'type' => $fieldType,
'visibility' => $visibility,
'nullable' => $nullable,
];
}
}
4 changes: 4 additions & 0 deletions src/Resources/config/makers.xml
Original file line number Diff line number Diff line change
Expand Up @@ -170,5 +170,9 @@
<argument type="service" id="maker.generator" />
<tag name="maker.command" />
</service>
<service id="maker.maker.make_event" class="Symfony\Bundle\MakerBundle\Maker\MakeEvent">
<argument type="service" id="maker.doctrine_helper" />
<tag name="maker.command" />
</service>
</services>
</container>
5 changes: 5 additions & 0 deletions src/Resources/help/MakeEvent.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
The <info>%command.name%</info> command generates a new event:

<info>php %command.full_name% OrderPlacedEvent</info>

If the argument is missing, the command will ask for the class name interactively.
17 changes: 17 additions & 0 deletions src/Resources/skeleton/event/Event.tpl.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?= "<?php\n" ?>

namespace <?= $namespace; ?>;

use Symfony\Contracts\EventDispatcher\Event;
<?php foreach ($useClasses as $useClass): ?>
use <?= $useClass; ?>;
<?php endforeach; ?>

final class <?= $class_name ?> extends Event
{
public function __construct(
<?php foreach ($fields as $field): ?>
<?= $field['visibility'] ?> readonly <?php if ($field['nullable']): ?>?<?php endif; ?><?= $field['type'] ?> $<?= $field['name'] ?>,
<?php endforeach; ?>
) {}
}
70 changes: 70 additions & 0 deletions tests/Maker/MakeEventTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

/*
* This file is part of the Symfony MakerBundle package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\MakerBundle\Tests\Maker;

use Symfony\Bundle\MakerBundle\Maker\MakeEvent;
use Symfony\Bundle\MakerBundle\Test\MakerTestCase;
use Symfony\Bundle\MakerBundle\Test\MakerTestRunner;

class MakeEventTest extends MakerTestCase
{
private const EXPECTED_EVENT_PATH = __DIR__.'/../../tests/fixtures/make-event/tests/Event/';

protected function getMakerClass(): string
{
return MakeEvent::class;
}

public function getTestDetails(): \Generator
{
yield 'it_makes_event' => [$this->createMakerTest()
->run(function (MakerTestRunner $runner) {
$runner->runMaker(
[
// event class name
'FooEvent',
// first property name
'id',
// first property type
'int',
// first property visibility
'public',
// first property nullable
'no',
// second property name
'name',
// second property type
'string',
// second property visibility
'private',
// second property nullable
'yes',
// third property name
'createdAt',
// third property type
'DateTimeInterface',
// third property visibility
'protected',
// third property nullable
'no',
'',
]
);

self::assertFileEquals(
self::EXPECTED_EVENT_PATH.'FooEvent.php',
$runner->getPath('src/Event/FooEvent.php')
);
}),
];
}
}
15 changes: 15 additions & 0 deletions tests/fixtures/make-event/tests/Event/FooEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace App\Event;

use Symfony\Contracts\EventDispatcher\Event;

final class FooEvent extends Event
{
public function __construct(
public readonly int $id,
private readonly ?string $name,
protected readonly DateTimeInterface $createdAt,
) {
}
}
Loading