.
*/
/**
* Generates a password.
*
*
* echo Txp::get('\Textpattern\Password\Generator')->generate(16);
*
*
* @since 4.6.0
* @package Password
*/
namespace Textpattern\Password;
class Generator
{
/**
* Stores the character table.
*
* @var array
*/
protected $chars;
/**
* Gets the character table.
*
* @return array
*/
public function getCharacterTable()
{
if (!$this->chars) {
$this->chars = str_split(PASSWORD_SYMBOLS);
}
return $this->chars;
}
/**
* Generates a random password.
*
*
* echo Txp::get('\Textpattern\Password\Generator')->generate(16);
*
*
* @param int $length The length of the generated password
* @return string The password
*/
public function generate($length)
{
$pool = false;
$pass = '';
for ($i = 0; $i < $length; $i++) {
if (!$pool) {
$pool = $this->getCharacterTable();
}
$index = mt_rand(0, count($pool) - 1);
$pass .= $pool[$index];
unset($pool[$index]);
$pool = array_values($pool);
}
return $pass;
}
}