Skip to content

Commit

Permalink
feature #1059 [make:reset-password] Translate exception reasons provi…
Browse files Browse the repository at this point in the history
…ded by ResetPasswordBundle (bocharsky-bw)

This PR was squashed before being merged into the 1.0-dev branch.

Discussion
----------

[make:reset-password] Translate exception reasons provided by ResetPasswordBundle

If there's `Symfony\Contracts\Translation\TranslatorInterface` service available in the project - Maker will generate a slightly different controller's code to inject translator service and translate exception reasons out of the box.

Available after: SymfonyCasts/reset-password-bundle#206

Commits
-------

b771178 [make:reset-password] Translate exception reasons provided by ResetPasswordBundle
  • Loading branch information
weaverryan committed Feb 16, 2022
2 parents c1a739e + b771178 commit 64b8399
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 8 deletions.
17 changes: 17 additions & 0 deletions src/Maker/MakeResetPassword.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,10 @@
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Yaml\Yaml;
use Symfony\Contracts\Translation\TranslatorInterface;
use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestInterface;
Expand Down Expand Up @@ -236,6 +238,18 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen
EntityManagerInterface::class,
];

// Namespace for ResetPasswordExceptionInterface was imported above
$problemValidateMessageOrConstant = \defined('SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE')
? 'ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE'
: "'There was a problem validating your password reset request'";
$problemHandleMessageOrConstant = \defined('SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE')
? 'ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE'
: "'There was a problem handling your password reset request'";

if ($isTranslatorAvailable = class_exists(Translator::class)) {
$useStatements[] = TranslatorInterface::class;
}

$generator->generateController(
$controllerClassNameDetails->getFullName(),
'resetPassword/ResetPasswordController.tpl.php',
Expand All @@ -253,6 +267,9 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen
'password_hasher_class_details' => ($passwordClassDetails = $generator->createClassNameDetails($passwordHasher, '\\')),
'password_hasher_variable_name' => str_replace('Interface', '', sprintf('$%s', lcfirst($passwordClassDetails->getShortName()))), // @legacy see passwordHasher conditional above
'use_password_hasher' => UserPasswordHasherInterface::class === $passwordHasher, // @legacy see passwordHasher conditional above
'problem_validate_message_or_constant' => $problemValidateMessageOrConstant,
'problem_handle_message_or_constant' => $problemHandleMessageOrConstant,
'translator_available' => $isTranslatorAvailable,
]
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,16 @@ public function __construct(ResetPasswordHelperInterface $resetPasswordHelper, E
* @Route("", name="app_forgot_password_request")
*/
<?php } ?>
public function request(Request $request, MailerInterface $mailer): Response
public function request(Request $request, MailerInterface $mailer<?php if ($translator_available): ?>, TranslatorInterface $translator<?php endif ?>): Response
{
$form = $this->createForm(<?= $request_form_type_class_name ?>::class);
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
return $this->processSendingPasswordResetEmail(
$form->get('<?= $email_field ?>')->getData(),
$mailer
$mailer<?php if ($translator_available): ?>,
$translator<?php endif ?><?= "\n" ?>
);
}

Expand Down Expand Up @@ -84,7 +85,7 @@ public function checkEmail(): Response
* @Route("/reset/{token}", name="app_reset_password")
*/
<?php } ?>
public function reset(Request $request, <?= $password_hasher_class_details->getShortName() ?> <?= $password_hasher_variable_name ?>, string $token = null): Response
public function reset(Request $request, <?= $password_hasher_class_details->getShortName() ?> <?= $password_hasher_variable_name ?><?php if ($translator_available): ?>, TranslatorInterface $translator<?php endif ?>, string $token = null): Response
{
if ($token) {
// We store the token in session and remove it from the URL, to avoid the URL being
Expand All @@ -103,8 +104,9 @@ public function reset(Request $request, <?= $password_hasher_class_details->getS
$user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
} catch (ResetPasswordExceptionInterface $e) {
$this->addFlash('reset_password_error', sprintf(
'There was a problem validating your reset request - %s',
$e->getReason()
'%s - %s',
<?php if ($translator_available): ?>$translator->trans(<?= $problem_validate_message_or_constant ?>, [], 'ResetPasswordBundle')<?php else: ?><?= $problem_validate_message_or_constant ?><?php endif ?>,
<?php if ($translator_available): ?>$translator->trans($e->getReason(), [], 'ResetPasswordBundle')<?php else: ?>$e->getReason()<?php endif ?><?= "\n" ?>
));

return $this->redirectToRoute('app_forgot_password_request');
Expand Down Expand Up @@ -138,7 +140,7 @@ public function reset(Request $request, <?= $password_hasher_class_details->getS
]);
}

private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer): RedirectResponse
private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer<?php if ($translator_available): ?>, TranslatorInterface $translator<?php endif ?>): RedirectResponse
{
$user = $this->entityManager->getRepository(<?= $user_class_name ?>::class)->findOneBy([
'<?= $email_field ?>' => $emailFormData,
Expand All @@ -157,8 +159,9 @@ private function processSendingPasswordResetEmail(string $emailFormData, MailerI
// Caution: This may reveal if a user is registered or not.
//
// $this->addFlash('reset_password_error', sprintf(
// 'There was a problem handling your password reset request - %s',
// $e->getReason()
// '%s - %s',
// <?php if ($translator_available): ?>$translator->trans(<?= $problem_handle_message_or_constant ?>, [], 'ResetPasswordBundle')<?php else: ?><?= $problem_handle_message_or_constant ?><?php endif ?>,
// <?php if ($translator_available): ?>$translator->trans($e->getReason(), [], 'ResetPasswordBundle')<?php else: ?>$e->getReason()<?php endif ?><?= "\n" ?>
// ));

return $this->redirectToRoute('app_check_email');
Expand Down
16 changes: 16 additions & 0 deletions tests/Maker/MakeResetPasswordTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,22 @@ public function getTestDetails()
}),
];

yield 'it_generates_with_translator_installed' => [$this->createResetPasswordTest()
->addExtraDependencies('symfony/translation')
->run(function (MakerTestRunner $runner) {
$this->makeUser($runner);

$output = $runner->runMaker([
'App\Entity\User',
'app_home',
'[email protected]',
'SymfonyCasts',
]);

$this->assertStringContainsString('Success', $output);
}),
];

yield 'it_generates_with_custom_config' => [$this->createResetPasswordTest()
->run(function (MakerTestRunner $runner) {
$runner->deleteFile('config/packages/reset_password.yaml');
Expand Down

0 comments on commit 64b8399

Please sign in to comment.