CustomUserMessageAuthenticationException.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Security\Core\Exception;
  11. /**
  12. * An authentication exception where you can control the message shown to the user.
  13. *
  14. * Be sure that the message passed to this exception is something that
  15. * can be shown safely to your user. In other words, avoid catching
  16. * other exceptions and passing their message directly to this class.
  17. *
  18. * @author Ryan Weaver <ryan@knpuniversity.com>
  19. */
  20. class CustomUserMessageAuthenticationException extends AuthenticationException
  21. {
  22. private $messageKey;
  23. private $messageData = [];
  24. public function __construct(string $message = '', array $messageData = [], int $code = 0, \Throwable $previous = null)
  25. {
  26. parent::__construct($message, $code, $previous);
  27. $this->setSafeMessage($message, $messageData);
  28. }
  29. /**
  30. * Set a message that will be shown to the user.
  31. *
  32. * @param string $messageKey The message or message key
  33. * @param array $messageData Data to be passed into the translator
  34. */
  35. public function setSafeMessage(string $messageKey, array $messageData = [])
  36. {
  37. $this->messageKey = $messageKey;
  38. $this->messageData = $messageData;
  39. }
  40. public function getMessageKey()
  41. {
  42. return $this->messageKey;
  43. }
  44. public function getMessageData()
  45. {
  46. return $this->messageData;
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function __serialize(): array
  52. {
  53. return [parent::__serialize(), $this->messageKey, $this->messageData];
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function __unserialize(array $data): void
  59. {
  60. [$parentData, $this->messageKey, $this->messageData] = $data;
  61. $parentData = \is_array($parentData) ? $parentData : unserialize($parentData);
  62. parent::__unserialize($parentData);
  63. }
  64. }