Skip to content

[WIP] adding DisableAutoMapping code to registration form #514

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 5 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
16 changes: 16 additions & 0 deletions src/Maker/MakeRegistrationForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Validator\Constraints\DisableAutoMapping;
use Symfony\Component\Validator\Validation;

/**
Expand Down Expand Up @@ -244,6 +245,21 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen
$this->fileManager->dumpFile($classDetails->getPath(), $userManipulator->getSourceCode());
}

if (class_exists(DisableAutoMapping::class)) {
$classDetails = new ClassDetails($userClass);
$userManipulator = new ClassSourceManipulator(
file_get_contents($classDetails->getPath())
);
$userManipulator->setIo($io);

$userManipulator->addValidationAnnotation(
'password',
DisableAutoMapping::class,
[]
);
$this->fileManager->dumpFile($classDetails->getPath(), $userManipulator->getSourceCode());
}

$generator->writeChanges();

$this->writeSuccessMessage($io);
Expand Down
9 changes: 9 additions & 0 deletions src/Security/UserClassBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use PhpParser\Node;
use Symfony\Bundle\MakerBundle\Util\ClassSourceManipulator;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints\DisableAutoMapping;

/**
* Adds logic to implement UserInterface to an existing User class.
Expand Down Expand Up @@ -190,6 +191,14 @@ private function addGetPassword(ClassSourceManipulator $manipulator, UserClassCo
],
[$propertyDocs]
);

if (class_exists(DisableAutoMapping::class)) {
$manipulator->addValidationAnnotation(
'password',
DisableAutoMapping::class,
[]
);
}
} else {
// add normal property
$manipulator->addProperty('password', [$propertyDocs]);
Expand Down
185 changes: 162 additions & 23 deletions src/Util/ClassSourceManipulator.php
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,78 @@ public function addAnnotationToClass(string $annotationClass, array $options)
$annotationClassAlias = $this->addUseStatementIfNecessary($annotationClass);
$docComment = $this->getClassNode()->getDocComment();

$docLines = $docComment ? explode("\n", $docComment->getText()) : [];
$commentText = $docComment ? $docComment->getText() : '';
$docComment = $this->addNewLineToComments(
$commentText,
$this->buildAnnotationLine('@'.$annotationClassAlias, $options)
);

$this->getClassNode()->setDocComment($docComment);
$this->updateSourceCodeFromNewStmts();
}

/**
* @param string $annotationClass Fully-qualified class name of annotation
* @param bool $preferNamespaceUse If true, then the system will prefer to
* add a use statement not specifically for
* this annotation class, but for the namespace
* that this annotation is in.
* @param string|null $preferredAlias Special alias to use for the use statement
* @throws \Exception
*/
public function addAnnotationToProperty(string $propertyName, string $annotationClass, array $options, bool $preferNamespaceUse = false, string $preferredAlias = null)
{
// look at only the namespace of the annotation
// check if that's already a use statement. If it is,
// use that with the \annotation
// else, add we need to add the use statement
// 1) Need a way to say if you prefer a use statement
// that is one level up, and what alias to use
// 2) else use the class name

if ($preferNamespaceUse) {
$namespacePieces = explode("\\", $annotationClass);
array_pop($namespacePieces); // remove last item
$targetUse = implode("\\", $namespacePieces);
} else {
$targetUse = $annotationClass;
}

$this->addUseStatementIfNecessary($targetUse, $preferredAlias);
// figure out which alias is now available thanks to the added use
$annotationClassAlias = $this->findUseableClassAlias($annotationClass);

$propertyNode = $this->findProperty($propertyName);

if (null === $propertyNode) {
throw new \Exception(sprintf('Property "%s" does not exist.', $propertyName));
}

$commentText = $propertyNode->getDocComment() ? $propertyNode->getDocComment()->getText() : '';
$docComment = $this->addNewLineToComments(
$commentText,
$this->buildAnnotationLine('@'.$annotationClassAlias, $options)
);

$propertyNode->setDocComment($docComment);
$this->updateSourceCodeFromNewStmts();
}

/**
* Helper to add a validation annotation that is aware of the preferred "as Assert" alias
*/
public function addValidationAnnotation(string $propertyName, string $annotationClass, array $options)
{
if (strpos($annotationClass, 'Symfony\Component\Validator\Constraints') !== 0) {
throw new \Exception('addValidationAnnotation is meant only for use with constraints in the Symfony\Component\Validator\Constraints namespace. Use addAnnotationToProperty() instead.');
}

$this->addAnnotationToProperty($propertyName, $annotationClass, $options, true, 'Assert');
}

private function addNewLineToComments(string $existingCommentsText, string $newDocLine): Doc
{
$docLines = $existingCommentsText ? explode("\n", $existingCommentsText) : [];
if (0 === \count($docLines)) {
$docLines = ['/**', ' */'];
} elseif (1 === \count($docLines)) {
Expand All @@ -285,12 +356,10 @@ public function addAnnotationToClass(string $annotationClass, array $options)
$docLines,
\count($docLines) - 1,
0,
' * '.$this->buildAnnotationLine('@'.$annotationClassAlias, $options)
' * '.$newDocLine
);

$docComment = new Doc(implode("\n", $docLines));
$this->getClassNode()->setDocComment($docComment);
$this->updateSourceCodeFromNewStmts();
return new Doc(implode("\n", $docLines));
}

private function addCustomGetter(string $propertyName, string $methodName, $returnType, bool $isReturnTypeNullable, array $commentLines = [], $typeCast = null)
Expand Down Expand Up @@ -689,7 +758,7 @@ private function getConstructorNode()
/**
* @return string The alias to use when referencing this class
*/
public function addUseStatementIfNecessary(string $class): string
public function addUseStatementIfNecessary(string $class, string $desiredAlias = null): string
{
$shortClassName = Str::getShortClassName($class);
if ($this->isInSameNamespace($class)) {
Expand All @@ -700,6 +769,82 @@ public function addUseStatementIfNecessary(string $class): string

$targetIndex = null;
$addLineBreak = false;
if (null !== $alias = $this->getAliasForExistingUseStatement($class, $targetIndex, $addLineBreak)) {
return $alias;
}

if (null === $targetIndex) {
throw new \Exception('Could not find a class!');
}

$newUserBuilder = (new Builder\Use_($class, Node\Stmt\Use_::TYPE_NORMAL));
$newAlias = $shortClassName;
if (null !== $desiredAlias) {
$newUserBuilder->as($desiredAlias);
$newAlias = $desiredAlias;
}

$newUseNode = $newUserBuilder->getNode();
array_splice(
$namespaceNode->stmts,
$targetIndex,
0,
$addLineBreak ? [$newUseNode, $this->createBlankLineNode(self::CONTEXT_OUTSIDE_CLASS)] : [$newUseNode]
);

$this->updateSourceCodeFromNewStmts();

return $newAlias;
}

/**
* Given a FQCN, this returns how that class should be referenced
* in the code based on an assumed "use" statement that already
* exists for it.
*
* This is primarily for supporting when there is a use statement
* for a namespace already, instead of a class:
*
* use Symfony\Component\Validator\Constraints as Assert;
*
* In this case, if we want to reference Symfony\...\Constraints\NotBlank,
* then this function would return Assert\NotBlank.
*/
private function findUseableClassAlias(string $targetClass)
{
$pieces = explode("\\", $targetClass);
$partsNeededForClassAlias = [];
while (count($pieces) > 0) {
$alias = $this->getAliasForExistingUseStatement(implode("\\", $pieces));

if (null !== $alias) {
$partsNeededForClassAlias[] = $alias;

return implode("\\", array_reverse($partsNeededForClassAlias));
}

// remove last item
$partsNeededForClassAlias[] = array_pop($pieces);
}

throw new \Exception(sprintf('Could not find any use statements that alias to any part of the class "%s"', $targetClass));
}

/**
* @param string $class Class or namespace to check for a use
* @param int|null $targetIndex Returns index where this use statement *should* be placed alphabetically
* @param bool $addLineBreak If a line break should be added after a new use statement
* @return string|null Null if the class/namespace has no use statement
*/
private function getAliasForExistingUseStatement(string $class, &$targetIndex = null, bool &$addLineBreak = false)
{
$shortClassName = Str::getShortClassName($class);
if ($this->isInSameNamespace($class)) {
return $shortClassName;
}

$namespaceNode = $this->getNamespaceNode();

$lastUseStmtIndex = null;
foreach ($namespaceNode->stmts as $index => $stmt) {
if ($stmt instanceof Node\Stmt\Use_) {
Expand Down Expand Up @@ -747,21 +892,7 @@ public function addUseStatementIfNecessary(string $class): string
}
}

if (null === $targetIndex) {
throw new \Exception('Could not find a class!');
}

$newUseNode = (new Builder\Use_($class, Node\Stmt\Use_::TYPE_NORMAL))->getNode();
array_splice(
$namespaceNode->stmts,
$targetIndex,
0,
$addLineBreak ? [$newUseNode, $this->createBlankLineNode(self::CONTEXT_OUTSIDE_CLASS)] : [$newUseNode]
);

$this->updateSourceCodeFromNewStmts();

return $shortClassName;
return null;
}

private function updateSourceCodeFromNewStmts()
Expand Down Expand Up @@ -1174,14 +1305,22 @@ private function getMethodIndex(string $methodName)
}

private function propertyExists(string $propertyName)
{
return null !== $this->findProperty($propertyName);
}

/**
* @return Node\Stmt\Property|null
*/
private function findProperty(string $propertyName)
{
foreach ($this->getClassNode()->stmts as $i => $node) {
if ($node instanceof Node\Stmt\Property && $node->props[0]->name->toString() === $propertyName) {
return true;
return $node;
}
}

return false;
return null;
}

private function writeNote(string $note)
Expand Down
Loading