Skip to content

[make:crud] Rename add method of repository to save. #1169

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

Closed
wants to merge 14 commits into from
Closed
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
4 changes: 2 additions & 2 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ jobs:
image: dunglas/mercure
env:
SERVER_NAME: :1337
MERCURE_PUBLISHER_JWT_KEY: '!ChangeMe!'
MERCURE_SUBSCRIBER_JWT_KEY: '!ChangeMe!'
MERCURE_PUBLISHER_JWT_KEY: '!ChangeThisMercureHubJWTSecretKey!'
MERCURE_SUBSCRIBER_JWT_KEY: '!ChangeThisMercureHubJWTSecretKey!'
MERCURE_EXTRA_DIRECTIVES: |
anonymous
cors_origins *
Expand Down
1 change: 1 addition & 0 deletions src/Maker/MakeResetPassword.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
* @author Antoine Michelet <jean.marcel.michelet@gmail.com>
*
* @internal
*
* @final
*/
class MakeResetPassword extends AbstractMaker
Expand Down
99 changes: 99 additions & 0 deletions src/Maker/MakeTwigComponent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php

/*
* This file is part of the Symfony MakerBundle package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* 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\Generator;
use Symfony\Bundle\MakerBundle\InputConfiguration;
use Symfony\Bundle\MakerBundle\Str;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

/**
* @author Kevin Bond <kevinbond@gmail.com>
*/
final class MakeTwigComponent extends AbstractMaker
{
public static function getCommandName(): string
{
return 'make:twig-component';
}

public static function getCommandDescription(): string
{
return 'Creates a twig (or live) component';
}

public function configureCommand(Command $command, InputConfiguration $inputConfig): void
{
$command
->setDescription(self::getCommandDescription())
->addArgument('name', InputArgument::OPTIONAL, 'The name of your twig component (ie <fg=yellow>NotificationComponent</>)')
->addOption('live', null, InputOption::VALUE_NONE, 'Whether to create a live twig component (requires <fg=yellow>symfony/ux-live-component</>)')
;
}

public function configureDependencies(DependencyBuilder $dependencies): void
{
$dependencies->addClassDependency(AsTwigComponent::class, 'symfony/ux-twig-component');
}

public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator): void
{
$name = $input->getArgument('name');
$live = $input->getOption('live');

if ($live && !class_exists(AsLiveComponent::class)) {
throw new \RuntimeException('You must install symfony/ux-live-component to create a live component (composer require symfony/ux-live-component)');
}

$factory = $generator->createClassNameDetails(
$name,
'Twig\\Components',
'Component'
);

$shortName = Str::asSnakeCase(Str::removeSuffix($factory->getShortName(), 'Component'));

$generator->generateClass(
$factory->getFullName(),
sprintf('%s/../Resources/skeleton/twig/%s', __DIR__, $live ? 'LiveComponent.tpl.php' : 'Component.tpl.php'),
[
'live' => $live,
'short_name' => $shortName,
]
);
$generator->generateTemplate(
"components/{$shortName}.html.twig",
sprintf('%s/../Resources/skeleton/twig/%s', __DIR__, 'component_template.tpl.php')
);

$generator->writeChanges();

$this->writeSuccessMessage($io);
$io->newLine();
$io->writeln(" To render the component, use {{ component('{$shortName}') }}.");
$io->newLine();
}

public function interact(InputInterface $input, ConsoleStyle $io, Command $command): void
{
if (!$input->getOption('live')) {
$input->setOption('live', $io->confirm('Make this a live component?', class_exists(AsLiveComponent::class)));
}
}
}
4 changes: 4 additions & 0 deletions src/Resources/config/makers.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
<tag name="maker.command" />
</service>

<service id="maker.maker.make_twig_component" class="Symfony\Bundle\MakerBundle\Maker\MakeTwigComponent">
<tag name="maker.command" />
</service>

<service id="maker.maker.make_controller" class="Symfony\Bundle\MakerBundle\Maker\MakeController">
<argument type="service" id="maker.php_compat_util" />
<tag name="maker.command" />
Expand Down
14 changes: 7 additions & 7 deletions src/Resources/skeleton/crud/controller/Controller.tpl.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function index(EntityManagerInterface $entityManager): Response
<?php endif ?>

<?= $generator->generateRouteForControllerMethod('/new', sprintf('%s_new', $route_name), ['GET', 'POST']) ?>
<?php if (isset($repository_full_class_name) && $generator->repositoryHasAddRemoveMethods($repository_full_class_name)) { ?>
<?php if (isset($repository_full_class_name) && $generator->repositoryHasSaveAndRemoveMethods($repository_full_class_name)) { ?>
public function new(Request $request, <?= $repository_class_name ?> $<?= $repository_var ?>): Response
<?php } else { ?>
public function new(Request $request, EntityManagerInterface $entityManager): Response
Expand All @@ -39,9 +39,9 @@ public function new(Request $request, EntityManagerInterface $entityManager): Re
$form = $this->createForm(<?= $form_class_name ?>::class, $<?= $entity_var_singular ?>);
$form->handleRequest($request);

<?php if (isset($repository_full_class_name) && $generator->repositoryHasAddRemoveMethods($repository_full_class_name)) { ?>
<?php if (isset($repository_full_class_name) && $generator->repositoryHasSaveAndRemoveMethods($repository_full_class_name)) { ?>
if ($form->isSubmitted() && $form->isValid()) {
$<?= $repository_var ?>->add($<?= $entity_var_singular ?>, true);
$<?= $repository_var ?>->save($<?= $entity_var_singular ?>, true);

return $this->redirectToRoute('<?= $route_name ?>_index', [], Response::HTTP_SEE_OTHER);
}
Expand Down Expand Up @@ -76,7 +76,7 @@ public function show(<?= $entity_class_name ?> $<?= $entity_var_singular ?>): Re
}

<?= $generator->generateRouteForControllerMethod(sprintf('/{%s}/edit', $entity_identifier), sprintf('%s_edit', $route_name), ['GET', 'POST']) ?>
<?php if (isset($repository_full_class_name) && $generator->repositoryHasAddRemoveMethods($repository_full_class_name)) { ?>
<?php if (isset($repository_full_class_name) && $generator->repositoryHasSaveAndRemoveMethods($repository_full_class_name)) { ?>
public function edit(Request $request, <?= $entity_class_name ?> $<?= $entity_var_singular ?>, <?= $repository_class_name ?> $<?= $repository_var ?>): Response
<?php } else { ?>
public function edit(Request $request, <?= $entity_class_name ?> $<?= $entity_var_singular ?>, EntityManagerInterface $entityManager): Response
Expand All @@ -85,7 +85,7 @@ public function edit(Request $request, <?= $entity_class_name ?> $<?= $entity_va
$form = $this->createForm(<?= $form_class_name ?>::class, $<?= $entity_var_singular ?>);
$form->handleRequest($request);

<?php if (isset($repository_full_class_name) && $generator->repositoryHasAddRemoveMethods($repository_full_class_name)) { ?>
<?php if (isset($repository_full_class_name) && $generator->repositoryHasSaveAndRemoveMethods($repository_full_class_name)) { ?>
if ($form->isSubmitted() && $form->isValid()) {
$<?= $repository_var ?>->add($<?= $entity_var_singular ?>, true);

Expand Down Expand Up @@ -113,13 +113,13 @@ public function edit(Request $request, <?= $entity_class_name ?> $<?= $entity_va
}

<?= $generator->generateRouteForControllerMethod(sprintf('/{%s}', $entity_identifier), sprintf('%s_delete', $route_name), ['POST']) ?>
<?php if (isset($repository_full_class_name) && $generator->repositoryHasAddRemoveMethods($repository_full_class_name)) { ?>
<?php if (isset($repository_full_class_name) && $generator->repositoryHasSaveAndRemoveMethods($repository_full_class_name)) { ?>
public function delete(Request $request, <?= $entity_class_name ?> $<?= $entity_var_singular ?>, <?= $repository_class_name ?> $<?= $repository_var ?>): Response
<?php } else { ?>
public function delete(Request $request, <?= $entity_class_name ?> $<?= $entity_var_singular ?>, EntityManagerInterface $entityManager): Response
<?php } ?>
{
<?php if (isset($repository_full_class_name) && $generator->repositoryHasAddRemoveMethods($repository_full_class_name)) { ?>
<?php if (isset($repository_full_class_name) && $generator->repositoryHasSaveAndRemoveMethods($repository_full_class_name)) { ?>
if ($this->isCsrfTokenValid('delete'.$<?= $entity_var_singular ?>->get<?= ucfirst($entity_identifier) ?>(), $request->request->get('_token'))) {
$<?= $repository_var ?>->remove($<?= $entity_var_singular ?>, true);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class <?= $class_name ?> extends WebTestCase<?= "\n" ?>
protected function setUp(): void
{
$this->client = static::createClient();
$this->manager = (static::getContainer()->get('doctrine'))->getManager();
$this->manager = static::getContainer()->get('doctrine')->getManager();
$this->repository = $this->manager->getRepository(<?= $entity_class_name; ?>::class);

foreach ($this->repository->findAll() as $object) {
Expand Down
2 changes: 1 addition & 1 deletion src/Resources/skeleton/crud/test/Test.tpl.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class <?= $class_name ?> extends WebTestCase<?= "\n" ?>
protected function setUp(): void
{
$this->client = static::createClient();
$this->repository = (static::getContainer()->get('doctrine'))->getRepository(<?= $entity_class_name; ?>::class);
$this->repository = static::getContainer()->get('doctrine')->getRepository(<?= $entity_class_name; ?>::class);

foreach ($this->repository->findAll() as $object) {
$this->repository->remove($object, true);
Expand Down
2 changes: 1 addition & 1 deletion src/Resources/skeleton/doctrine/Repository.tpl.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public function __construct(ManagerRegistry $registry)
parent::__construct($registry, <?= $entity_class_name; ?>::class);
}

public function add(<?= $entity_class_name ?> $entity, bool $flush = false): void
public function save(<?= $entity_class_name ?> $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);

Expand Down
10 changes: 10 additions & 0 deletions src/Resources/skeleton/twig/Component.tpl.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?= "<?php\n" ?>

namespace <?= $namespace; ?>;

use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent('<?= $short_name; ?>')]
final class <?= $class_name."\n" ?>
{
}
12 changes: 12 additions & 0 deletions src/Resources/skeleton/twig/LiveComponent.tpl.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?= "<?php\n" ?>

namespace <?= $namespace; ?>;

use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent('<?= $short_name; ?>')]
final class <?= $class_name."\n" ?>
{
use DefaultActionTrait;
}
3 changes: 3 additions & 0 deletions src/Resources/skeleton/twig/component_template.tpl.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<div{{ attributes }}>
<!-- component html -->
</div>
1 change: 1 addition & 0 deletions src/Resources/skeleton/validator/Constraint.tpl.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

/**
* @Annotation
*
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
*/
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
Expand Down
35 changes: 34 additions & 1 deletion src/Test/MakerTestDetails.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ final class MakerTestDetails
private string $rootNamespace = 'App';
private int $requiredPhpVersion = 80000;
private array $requiredPackageVersions = [];
private int $blockedPhpVersionUpper = 0;
private int $blockedPhpVersionLower = 0;

public function __construct(
private MakerInterface $maker,
Expand Down Expand Up @@ -73,6 +75,22 @@ public function setRequiredPhpVersion(int $version): self
return $this;
}

/**
* Skip a test from running between a range of PHP Versions.
*
* @param int $lowerLimit Versions below this value will be allowed
* @param int $upperLimit Versions above this value will be allowed
*
* @internal
*/
public function setSkippedPhpVersions(int $lowerLimit, int $upperLimit): self
{
$this->blockedPhpVersionUpper = $upperLimit;
$this->blockedPhpVersionLower = $lowerLimit;

return $this;
}

public function addRequiredPackageVersion(string $packageName, string $versionConstraint): self
{
$this->requiredPackageVersions[] = ['name' => $packageName, 'version_constraint' => $versionConstraint];
Expand Down Expand Up @@ -118,7 +136,22 @@ public function getDependencyBuilder(): DependencyBuilder

public function isSupportedByCurrentPhpVersion(): bool
{
return \PHP_VERSION_ID >= $this->requiredPhpVersion;
$hasPhpVersionConstraint = $this->blockedPhpVersionLower > 0 && $this->blockedPhpVersionUpper > 0;
$isSupported = false;

if (!$hasPhpVersionConstraint) {
$isSupported = true;
}

if (\PHP_VERSION_ID > $this->blockedPhpVersionUpper) {
$isSupported = true;
}

if (\PHP_VERSION_ID < $this->blockedPhpVersionLower) {
$isSupported = true;
}

return $isSupported && \PHP_VERSION_ID >= $this->requiredPhpVersion;
}

public function getRequiredPackageVersions(): array
Expand Down
1 change: 1 addition & 0 deletions src/Test/MakerTestKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ protected function configureContainer(ContainerBuilder $c, LoaderInterface $load
'router' => [
'utf8' => true,
],
'http_method_override' => false,
]);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Test/MakerTestRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ public function configureDatabase(bool $createSchema = true): void
{
$this->replaceInFile(
'.env',
'postgresql://symfony:ChangeMe@127.0.0.1:5432/app?serverVersion=13&charset=utf8',
'postgresql://app:!ChangeMe!@127.0.0.1:5432/app?serverVersion=14&charset=utf8',
getenv('TEST_DATABASE_DSN')
);

Expand Down
1 change: 1 addition & 0 deletions src/Util/ComposeFileManipulator.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
* @author Jesse Rushlow <jr@rushlow.dev>
*
* @internal
*
* @final
*/
class ComposeFileManipulator
Expand Down
4 changes: 2 additions & 2 deletions src/Util/TemplateComponentGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ public function getPropertyType(ClassNameDetails $classNameDetails): ?string
/**
* @throws ReflectionException
*/
public function repositoryHasAddRemoveMethods(string $repositoryFullClassName): bool
public function repositoryHasSaveAndRemoveMethods(string $repositoryFullClassName): bool
{
$reflectedComponents = new ReflectionClass($repositoryFullClassName);

return $reflectedComponents->hasMethod('add') && $reflectedComponents->hasMethod('remove');
return $reflectedComponents->hasMethod('save') && $reflectedComponents->hasMethod('remove');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public function __construct(ManagerRegistry $registry)
parent::__construct($registry, UserXml::class);
}

public function add(UserXml $entity, bool $flush = false): void
public function save(UserXml $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public function __construct(ManagerRegistry $registry)
parent::__construct($registry, XOther::class);
}

public function add(XOther $entity, bool $flush = false): void
public function save(XOther $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);

Expand Down
5 changes: 5 additions & 0 deletions tests/Maker/MakeResetPasswordTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ protected function getMakerClass(): string
public function getTestDetails(): \Generator
{
yield 'it_generates_with_normal_setup' => [$this->createMakerTest()
->setSkippedPhpVersions(80100, 80109)
->run(function (MakerTestRunner $runner) {
$this->makeUser($runner);

Expand Down Expand Up @@ -81,6 +82,7 @@ public function getTestDetails(): \Generator
];

yield 'it_generates_with_translator_installed' => [$this->createMakerTest()
->setSkippedPhpVersions(80100, 80109)
->addExtraDependencies('symfony/translation')
->run(function (MakerTestRunner $runner) {
$this->makeUser($runner);
Expand All @@ -97,6 +99,7 @@ public function getTestDetails(): \Generator
];

yield 'it_generates_with_custom_config' => [$this->createMakerTest()
->setSkippedPhpVersions(80100, 80109)
->run(function (MakerTestRunner $runner) {
$runner->deleteFile('config/packages/reset_password.yaml');
$runner->writeFile(
Expand Down Expand Up @@ -131,6 +134,7 @@ public function getTestDetails(): \Generator
];

yield 'it_amends_configuration' => [$this->createMakerTest()
->setSkippedPhpVersions(80100, 80109)
->run(function (MakerTestRunner $runner) {
$runner->modifyYamlFile('config/packages/reset_password.yaml', function (array $config) {
$config['symfonycasts_reset_password']['lifetime'] = 9999;
Expand All @@ -157,6 +161,7 @@ public function getTestDetails(): \Generator
];

yield 'it_generates_with_custom_user' => [$this->createMakerTest()
->setSkippedPhpVersions(80100, 80109)
->run(function (MakerTestRunner $runner) {
$this->makeUser($runner, 'emailAddress', 'UserCustom', false);

Expand Down
Loading