SecurityDataCollector.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace Symfony\Component\HttpKernel\DataCollector;
  3. use Symfony\Component\Security\SecurityContext;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. /*
  7. * This file is part of the Symfony framework.
  8. *
  9. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  10. *
  11. * This source file is subject to the MIT license that is bundled
  12. * with this source code in the file LICENSE.
  13. */
  14. /**
  15. * SecurityDataCollector.
  16. *
  17. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  18. */
  19. class SecurityDataCollector extends DataCollector
  20. {
  21. protected $context;
  22. public function __construct(SecurityContext $context = null)
  23. {
  24. $this->context = $context;
  25. }
  26. /**
  27. * {@inheritdoc}
  28. */
  29. public function collect(Request $request, Response $response, \Exception $exception = null)
  30. {
  31. if (null === $this->context) {
  32. $this->data = array(
  33. 'enabled' => false,
  34. 'authenticated' => false,
  35. 'user' => '',
  36. 'roles' => array(),
  37. );
  38. } elseif (null === $token = $this->context->getToken()) {
  39. $this->data = array(
  40. 'enabled' => true,
  41. 'authenticated' => false,
  42. 'user' => '',
  43. 'roles' => array(),
  44. );
  45. } else {
  46. $this->data = array(
  47. 'enabled' => true,
  48. 'authenticated' => $token->isAuthenticated(),
  49. 'user' => (string) $token->getUser(),
  50. 'roles' => array_map(function ($role){ return $role->getRole();}, $token->getRoles()),
  51. );
  52. }
  53. }
  54. /**
  55. * Checks if security is enabled.
  56. *
  57. * @return Boolean true if security is enabled, false otherwise
  58. */
  59. public function isEnabled()
  60. {
  61. return $this->data['enabled'];
  62. }
  63. /**
  64. * Gets the user.
  65. *
  66. * @return string The user
  67. */
  68. public function getUser()
  69. {
  70. return $this->data['user'];
  71. }
  72. /**
  73. * Gets the roles of the user.
  74. *
  75. * @return array The roles
  76. */
  77. public function getRoles()
  78. {
  79. return $this->data['roles'];
  80. }
  81. /**
  82. * Checks if the user is authenticated or not.
  83. *
  84. * @return Boolean true if the user is authenticated, false otherwise
  85. */
  86. public function isAuthenticated()
  87. {
  88. return $this->data['authenticated'];
  89. }
  90. /**
  91. * {@inheritdoc}
  92. */
  93. public function getName()
  94. {
  95. return 'security';
  96. }
  97. }