FormKey.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Data\Form;
  7. /**
  8. * @api
  9. * @since 100.0.2
  10. */
  11. class FormKey
  12. {
  13. /**
  14. * Form key
  15. */
  16. const FORM_KEY = '_form_key';
  17. /**
  18. * @var \Magento\Framework\Math\Random
  19. */
  20. protected $mathRandom;
  21. /**
  22. * @var \Magento\Framework\Session\SessionManagerInterface
  23. */
  24. protected $session;
  25. /**
  26. * @var \Magento\Framework\Escaper
  27. * @since 100.0.3
  28. */
  29. protected $escaper;
  30. /**
  31. * @param \Magento\Framework\Math\Random $mathRandom
  32. * @param \Magento\Framework\Session\SessionManagerInterface $session
  33. * @param \Magento\Framework\Escaper $escaper
  34. */
  35. public function __construct(
  36. \Magento\Framework\Math\Random $mathRandom,
  37. \Magento\Framework\Session\SessionManagerInterface $session,
  38. \Magento\Framework\Escaper $escaper
  39. ) {
  40. $this->mathRandom = $mathRandom;
  41. $this->session = $session;
  42. $this->escaper = $escaper;
  43. }
  44. /**
  45. * Retrieve Session Form Key
  46. *
  47. * @return string A 16 bit unique key for forms
  48. */
  49. public function getFormKey()
  50. {
  51. if (!$this->isPresent()) {
  52. $this->set($this->mathRandom->getRandomString(16));
  53. }
  54. return $this->escaper->escapeHtmlAttr($this->session->getData(self::FORM_KEY));
  55. }
  56. /**
  57. * @return bool
  58. */
  59. public function isPresent()
  60. {
  61. return (bool)$this->session->getData(self::FORM_KEY);
  62. }
  63. /**
  64. * @param string $value
  65. * @return void
  66. */
  67. public function set($value)
  68. {
  69. $this->session->setData(self::FORM_KEY, $value);
  70. }
  71. }