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:crud|voter] generate classes with final keyword #1539

Open
wants to merge 3 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
2 changes: 2 additions & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ public function getConfigTreeBuilder(): TreeBuilder
$rootNode
->children()
->scalarNode('root_namespace')->defaultValue('App')->end()
->booleanNode('generate_final_classes')->defaultTrue()->end()
->booleanNode('generate_final_entities')->defaultFalse()->end()
->end()
;

Expand Down
7 changes: 7 additions & 0 deletions src/DependencyInjection/MakerExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ public function load(array $configs, ContainerBuilder $container): void
$doctrineHelperDefinition = $container->getDefinition('maker.doctrine_helper');
$doctrineHelperDefinition->replaceArgument(0, $rootNamespace.'\\Entity');

$componentGeneratorDefinition = $container->getDefinition('maker.template_component_generator');
$componentGeneratorDefinition
->replaceArgument(0, $config['generate_final_classes'])
->replaceArgument(1, $config['generate_final_entities'])
->replaceArgument(2, $rootNamespace)
;

$container->registerForAutoconfiguration(MakerInterface::class)
->addTag(MakeCommandRegistrationPass::MAKER_TAG);
}
Expand Down
6 changes: 6 additions & 0 deletions src/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\MakerBundle\Exception\RuntimeCommandException;
use Symfony\Bundle\MakerBundle\Util\ClassNameDetails;
use Symfony\Bundle\MakerBundle\Util\ClassSource\Model\ClassData;
use Symfony\Bundle\MakerBundle\Util\PhpCompatUtil;
use Symfony\Bundle\MakerBundle\Util\TemplateComponentGenerator;

Expand Down Expand Up @@ -54,6 +55,11 @@ public function __construct(
*/
public function generateClass(string $className, string $templateName, array $variables = []): string
{
if (\array_key_exists('class_data', $variables) && $variables['class_data'] instanceof ClassData) {
$classData = $this->templateComponentGenerator->configureClass($variables['class_data']);
$className = $classData->getFullClassName();
}

$targetPath = $this->fileManager->getRelativePathForFutureClass($className);

if (null === $targetPath) {
Expand Down
67 changes: 34 additions & 33 deletions src/Maker/MakeCrud.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
use Symfony\Bundle\MakerBundle\Maker\Common\CanGenerateTestsTrait;
use Symfony\Bundle\MakerBundle\Renderer\FormTypeRenderer;
use Symfony\Bundle\MakerBundle\Str;
use Symfony\Bundle\MakerBundle\Util\UseStatementGenerator;
use Symfony\Bundle\MakerBundle\Util\ClassSource\Model\ClassData;
use Symfony\Bundle\MakerBundle\Validator;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Component\Console\Command\Command;
Expand Down Expand Up @@ -147,6 +147,21 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen
++$iter;
} while (class_exists($formClassDetails->getFullName()));

$controllerClassData = ClassData::create(
class: sprintf('Controller\%s', $this->controllerClassName),
suffix: 'Controller',
extendsClass: AbstractController::class,
useStatements: [
$entityClassDetails->getFullName(),
$formClassDetails->getFullName(),
$repositoryClassName,
AbstractController::class,
Request::class,
Response::class,
Route::class,
],
);

$entityVarPlural = lcfirst($this->inflector->pluralize($entityClassDetails->getShortName()));
$entityVarSingular = lcfirst($this->inflector->singularize($entityClassDetails->getShortName()));

Expand All @@ -156,25 +171,15 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen
$routeName = Str::asRouteName($controllerClassDetails->getRelativeNameWithoutSuffix());
$templatesPath = Str::asFilePath($controllerClassDetails->getRelativeNameWithoutSuffix());

$useStatements = new UseStatementGenerator([
$entityClassDetails->getFullName(),
$formClassDetails->getFullName(),
$repositoryClassName,
AbstractController::class,
Request::class,
Response::class,
Route::class,
]);

if (EntityManagerInterface::class !== $repositoryClassName) {
$useStatements->addUseStatement(EntityManagerInterface::class);
$controllerClassData->addUseStatement(EntityManagerInterface::class);
}

$generator->generateController(
$controllerClassDetails->getFullName(),
$controllerClassData->getFullClassName(),
'crud/controller/Controller.tpl.php',
array_merge([
'use_statements' => $useStatements,
'class_data' => $controllerClassData,
'entity_class_name' => $entityClassDetails->getShortName(),
'form_class_name' => $formClassDetails->getShortName(),
'route_path' => Str::asRoutePath($controllerClassDetails->getRelativeNameWithoutSuffix()),
Expand Down Expand Up @@ -242,37 +247,33 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen
}

if ($this->shouldGenerateTests()) {
$testClassDetails = $generator->createClassNameDetails(
$entityClassDetails->getRelativeNameWithoutSuffix(),
'Test\\Controller\\',
'ControllerTest'
$testClassData = ClassData::create(
class: sprintf('Tests\Controller\%s', $entityClassDetails->getRelativeNameWithoutSuffix()),
suffix: 'ControllerTest',
extendsClass: WebTestCase::class,
useStatements: [
$entityClassDetails->getFullName(),
WebTestCase::class,
KernelBrowser::class,
$repositoryClassName,
EntityRepository::class,
],
);

$useStatements = new UseStatementGenerator([
$entityClassDetails->getFullName(),
WebTestCase::class,
KernelBrowser::class,
$repositoryClassName,
]);

$useStatements->addUseStatement(EntityRepository::class);

if (EntityManagerInterface::class !== $repositoryClassName) {
$useStatements->addUseStatement(EntityManagerInterface::class);
$testClassData->addUseStatement(EntityManagerInterface::class);
}

$generator->generateFile(
'tests/Controller/'.$testClassDetails->getShortName().'.php',
$generator->generateClass(
$testClassData->getFullClassName(),
'crud/test/Test.EntityManager.tpl.php',
[
'use_statements' => $useStatements,
'class_data' => $testClassData,
'entity_full_class_name' => $entityClassDetails->getFullName(),
'entity_class_name' => $entityClassDetails->getShortName(),
'entity_var_singular' => $entityVarSingular,
'route_path' => Str::asRoutePath($controllerClassDetails->getRelativeNameWithoutSuffix()),
'route_name' => $routeName,
'class_name' => Str::getShortClassName($testClassDetails->getFullName()),
'namespace' => Str::getNamespace($testClassDetails->getFullName()),
'form_fields' => $entityDoctrineDetails->getFormFields(),
'repository_class_name' => EntityManagerInterface::class,
'form_field_prefix' => strtolower(Str::asSnakeCase($entityTwigVarSingular)),
Expand Down
20 changes: 14 additions & 6 deletions src/Maker/MakeVoter.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,13 @@
use Symfony\Bundle\MakerBundle\DependencyBuilder;
use Symfony\Bundle\MakerBundle\Generator;
use Symfony\Bundle\MakerBundle\InputConfiguration;
use Symfony\Bundle\MakerBundle\Util\ClassSource\Model\ClassData;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;

/**
* @author Javier Eguiluz <javier.eguiluz@gmail.com>
Expand Down Expand Up @@ -46,16 +49,21 @@ public function configureCommand(Command $command, InputConfiguration $inputConf

public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator): void
{
$voterClassNameDetails = $generator->createClassNameDetails(
$input->getArgument('name'),
'Security\\Voter\\',
'Voter'
$voterClassData = ClassData::create(
class: sprintf('Security\Voter\%s', $input->getArgument('name')),
suffix: 'Voter',
extendsClass: Voter::class,
useStatements: [
TokenInterface::class,
Voter::class,
UserInterface::class,
]
);

$generator->generateClass(
$voterClassNameDetails->getFullName(),
$voterClassData->getFullClassName(),
'security/Voter.tpl.php',
[]
['class_data' => $voterClassData]
);

$generator->writeChanges();
Expand Down
3 changes: 3 additions & 0 deletions src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@
</service>

<service id="maker.template_component_generator" class="Symfony\Bundle\MakerBundle\Util\TemplateComponentGenerator">
<argument /> <!-- generate_final_classes -->
<argument /> <!-- generate_final_entities -->
<argument /> <!-- root_namespace -->
</service>
</services>
</container>
6 changes: 3 additions & 3 deletions src/Resources/skeleton/crud/controller/Controller.tpl.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<?= "<?php\n" ?>

namespace <?= $namespace ?>;
namespace <?= $class_data->getNamespace() ?>;

<?= $use_statements; ?>
<?= $class_data->getUseStatements(); ?>

#[Route('<?= $route_path ?>')]
class <?= $class_name ?> extends AbstractController
<?= $class_data->getClassDeclaration() ?>
{
<?= $generator->generateRouteForControllerMethod('/', sprintf('%s_index', $route_name), ['GET']) ?>
<?php if (isset($repository_full_class_name)): ?>
Expand Down
4 changes: 2 additions & 2 deletions src/Resources/skeleton/crud/test/Test.EntityManager.tpl.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@

namespace <?= $namespace ?>;

<?= $use_statements; ?>
<?= $class_data->getUseStatements(); ?>

class <?= $class_name ?> extends WebTestCase<?= "\n" ?>
<?= $class_data->getClassDeclaration() ?>
{
private KernelBrowser $client;
private EntityManagerInterface $manager;
Expand Down
10 changes: 4 additions & 6 deletions src/Resources/skeleton/security/Voter.tpl.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
<?= "<?php\n" ?>

namespace <?= $namespace; ?>;
namespace <?= $class_data->getNamespace(); ?>;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
<?= $class_data->getUseStatements(); ?>

class <?= $class_name ?> extends Voter
<?= $class_data->getClassDeclaration() ?>
{
public const EDIT = 'POST_EDIT';
public const VIEW = 'POST_VIEW';
Expand All @@ -16,7 +14,7 @@ protected function supports(string $attribute, mixed $subject): bool
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::EDIT, self::VIEW])
&& $subject instanceof \App\Entity\<?= str_replace('Voter', null, $class_name) ?>;
&& $subject instanceof \App\Entity\<?= str_replace('Voter', null, $class_data->getClassName()) ?>;
}

protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
Expand Down
117 changes: 117 additions & 0 deletions src/Util/ClassSource/Model/ClassData.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?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\Util\ClassSource\Model;

use Symfony\Bundle\MakerBundle\Str;
use Symfony\Bundle\MakerBundle\Util\UseStatementGenerator;

/**
* @author Jesse Rushlow <jr@rushlow.dev>
*
* @internal
*/
final class ClassData
{
private function __construct(
private string $className,
private string $namespace,
public readonly ?string $extends,
public readonly bool $isEntity,
private UseStatementGenerator $useStatementGenerator,
private bool $isFinal = true,
private string $rootNamespace = 'App',
) {
}

public static function create(string $class, ?string $suffix = null, ?string $extendsClass = null, bool $isEntity = false, array $useStatements = []): self
{
$className = Str::getShortClassName($class);

if (null !== $suffix && !str_ends_with($className, $suffix)) {
$className = Str::asClassName(sprintf('%s%s', $className, $suffix));
}

$useStatements = new UseStatementGenerator($useStatements);

if ($extendsClass) {
$useStatements->addUseStatement($extendsClass);
}

return new self(
className: Str::asClassName($className),
namespace: Str::getNamespace($class),
extends: null === $extendsClass ? null : Str::getShortClassName($extendsClass),
isEntity: $isEntity,
useStatementGenerator: $useStatements,
);
}

public function getClassName(): string
{
return $this->className;
}

public function getNamespace(): string
{
if (empty($this->namespace)) {
return $this->rootNamespace;
}

return sprintf('%s\%s', $this->rootNamespace, $this->namespace);
}

public function getFullClassName(): string
{
return sprintf('%s\%s', $this->getNamespace(), $this->className);
}

public function setRootNamespace(string $rootNamespace): self
{
$this->rootNamespace = $rootNamespace;

return $this;
}

public function getClassDeclaration(): string
{
$extendsDeclaration = '';

if (null !== $this->extends) {
$extendsDeclaration = sprintf(' extends %s', $this->extends);
}

return sprintf('%sclass %s%s',
$this->isFinal ? 'final ' : '',
$this->className,
$extendsDeclaration,
);
}

public function setIsFinal(bool $isFinal): self
{
$this->isFinal = $isFinal;

return $this;
}

public function addUseStatement(array|string $useStatement): self
{
$this->useStatementGenerator->addUseStatement($useStatement);

return $this;
}

public function getUseStatements(): string
{
return (string) $this->useStatementGenerator;
}
}
Loading
Loading