for testing and deploying your application
for finding and fixing issues
for empowering human code reviews
<?php
namespace BWC\Share\Security\TokenGenerator;
use Psr\Log\LoggerInterface;
class TokenGenerator implements TokenGeneratorInterface
{
/** @var bool */
private $useOpenSsl;
public function __construct(LoggerInterface $logger = null)
$this->logger = $logger;
logger
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
class MyClass { } $x = new MyClass(); $x->foo = true;
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:
class MyClass { public $foo; } $x = new MyClass(); $x->foo = true;
// 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')) {
if (null !== $this->logger) {
$this->logger->notice('It is recommended that you enable the "openssl" extension for random number generation.');
}
} else {
$this->useOpenSsl = true;
public function generateToken()
return base_convert(bin2hex($this->getRandomNumber()), 16, 36);
private function getRandomNumber()
$nbBytes = 32;
// try OpenSSL
if ($this->useOpenSsl) {
$bytes = openssl_random_pseudo_bytes($nbBytes, $strong);
if (false !== $bytes && true === $strong) {
return $bytes;
$this->logger->info('OpenSSL did not produce a secure random number.');
return hash('sha256', uniqid(mt_rand(), true), true);
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: