<?php

/*
 * This file is part of Sulu.
 *
 * (c) Sulu GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Bundle\SecurityBundle\Util;

/**
 * Generates a token.
 *
 * inspired by the FOSUserBundle's TokenGenerator
 *
 * Class TokenGenerator
 */
class TokenGenerator implements TokenGeneratorInterface
{
    private $useOpenSsl;

    public function __construct()
    {
        // determine whether to use OpenSSL
        if (\defined('PHP_WINDOWS_VERSION_BUILD') && \version_compare(\PHP_VERSION, '5.3.4', '<')) {
            $this->useOpenSsl = false;
        } elseif (!\function_exists('openssl_random_pseudo_bytes')) {
            $this->useOpenSsl = false;
        } else {
            $this->useOpenSsl = true;
        }
    }

    /**
     * Pulbic method to return the token.
     *
     * @returns String the token
     */
    public function generateToken()
    {
        return \rtrim(\strtr(\base64_encode($this->getRandomNumber()), '+/', '-_'), '=');
    }

    private function getRandomNumber()
    {
        $nbBytes = 32;
        // try OpenSSL
        if ($this->useOpenSsl) {
            $bytes = \openssl_random_pseudo_bytes($nbBytes, $strong);
            if (false !== $bytes && true === $strong) {
                return $bytes;
            }
        }

        return \hash('sha256', \uniqid(\mt_rand(), true), true);
    }
}
