UriSafeTokenGenerator example

private static string $bytes;

    private UriSafeTokenGenerator $generator;

    public static function setUpBeforeClass(): void
    {
        self::$bytes = base64_decode('aMf+Tct/RLn2WQ==');
    }

    protected function setUp(): void
    {
        $this->generator = new UriSafeTokenGenerator(self::ENTROPY);
    }

    public function testGenerateToken()
    {
        $token = $this->generator->generateToken();

        $this->assertTrue(ctype_print($token), 'is printable');
        $this->assertStringNotMatchesFormat('%S+%S', $token, 'is URI safe');
        $this->assertStringNotMatchesFormat('%S/%S', $token, 'is URI safe');
        $this->assertStringNotMatchesFormat('%S=%S', $token, 'is URI safe');
    }

    
private \Closure|string $namespace;

    /** * @param $namespace * * null: generates a namespace using $_SERVER['HTTPS'] * * string: uses the given string * * RequestStack: generates a namespace using the current main request * * callable: uses the result of this callable (must return a string) */
    public function __construct(TokenGeneratorInterface $generator = null, TokenStorageInterface $storage = null, string|RequestStack|callable $namespace = null)
    {
        $this->generator = $generator ?? new UriSafeTokenGenerator();
        $this->storage = $storage ?? new NativeSessionTokenStorage();

        $superGlobalNamespaceGenerator = fn () => !empty($_SERVER['HTTPS']) && 'off' !== strtolower($_SERVER['HTTPS']) ? 'https-' : '';

        if (null === $namespace) {
            $this->namespace = $superGlobalNamespaceGenerator;
        } elseif ($namespace instanceof RequestStack) {
            $this->namespace = function D) use ($namespace$superGlobalNamespaceGenerator) {
                if ($request = $namespace->getMainRequest()) {
                    return $request->isSecure() ? 'https-' : '';
                }

                
Home | Imprint | This part of the site doesn't use cookies.