浏览代码

re-added a __toString method for debugging purposes

Johannes Schmitt 14 年之前
父节点
当前提交
70867f06e9

+ 16 - 0
src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php

@@ -204,4 +204,20 @@ abstract class AbstractToken implements TokenInterface
     {
         $this->attributes[$name] = $value;
     }
+
+    /**
+     * {@inheritDoc}
+     */
+    public function __toString()
+    {
+        $class = get_class($this);
+        $class = substr($class, strrpos($class, '\\')+1);
+
+        $roles = array();
+        foreach ($this->roles as $role) {
+            $roles[] = $role->getRole();
+        }
+
+        return sprintf('%s(user="%s", authenticated=%s, roles="%s")', $class, $this->getUsername(), json_encode($this->authenticated), implode(', ', $roles));
+    }
 }

+ 9 - 0
src/Symfony/Component/Security/Core/Authentication/Token/TokenInterface.php

@@ -21,6 +21,15 @@ use Symfony\Component\Security\Core\User\UserInterface;
  */
 interface TokenInterface extends \Serializable
 {
+    /**
+     * Returns a string representation ofthe Token.
+     *
+     * This is only to be used for debugging purposes.
+     *
+     * @return string
+     */
+    function __toString();
+
     /**
      * Returns the user roles.
      *

+ 2 - 2
src/Symfony/Component/Security/Http/Firewall/AbstractPreAuthenticatedListener.php

@@ -55,7 +55,7 @@ abstract class AbstractPreAuthenticatedListener implements ListenerInterface
         $request = $event->get('request');
 
         if (null !== $this->logger) {
-            $this->logger->debug(sprintf('Checking secure context token: %s', $this->securityContext->getToken()->getUserName()));
+            $this->logger->debug(sprintf('Checking secure context token: %s', $this->securityContext->getToken()));
         }
 
         list($user, $credentials) = $this->getPreAuthenticatedData($request);
@@ -74,7 +74,7 @@ abstract class AbstractPreAuthenticatedListener implements ListenerInterface
             $token = $this->authenticationManager->authenticate(new PreAuthenticatedToken($user, $credentials, $this->providerKey));
 
             if (null !== $this->logger) {
-                $this->logger->debug(sprintf('Authentication success: %s', $token->getUserName()));
+                $this->logger->debug(sprintf('Authentication success: %s', $token));
             }
             $this->securityContext->setToken($token);
 

+ 6 - 0
tests/Symfony/Tests/Component/Security/Core/Authentication/Token/UsernamePasswordTokenTest.php

@@ -49,4 +49,10 @@ class UsernamePasswordTokenTest extends \PHPUnit_Framework_TestCase
         $token->eraseCredentials();
         $this->assertEquals('', $token->getCredentials());
     }
+
+    public function testToString()
+    {
+        $token = new UsernamePasswordToken('foo', '', 'foo', array('A', 'B'));
+        $this->assertEquals('UsernamePasswordToken(user="foo", authenticated=true, roles="A, B")', (string) $token);
+    }
 }