Skip to content

Instantly share code, notes, and snippets.

@max-dark
Created September 12, 2016 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max-dark/79d6df4b7f35986bf54dd55dbb7e4fbd to your computer and use it in GitHub Desktop.
Save max-dark/79d6df4b7f35986bf54dd55dbb7e4fbd to your computer and use it in GitHub Desktop.
password generator
<?php
/**
* @copyright Copyright (C) 2016 Max Dark maxim.dark@gmail.com
* @license MIT; see LICENSE.txt
*/
namespace Tools{
/**
* Class Password
* @package Tools
*/
class Password
{
/**
* Generate password
*
* @param bool $use_digs
* @param bool $use_small
* @param bool $use_big
* @param bool $use_special
* @param int $length must be > 0
*
* @return string
* @throws \Exception
*/
public static function generate($use_digs, $use_small, $use_big, $use_special, $length)
{
$chars = [];
$length = intval($length);
if ($length < 1) {
throw new \Exception('length must be > 0');
}
if ($use_digs) {
$chars = self::append($chars, range('0', '9'));
}
if ($use_small) {
$chars = self::append($chars, range('a', 'z'));
}
if ($use_big) {
$chars = self::append($chars, range('A', 'Z'));
}
if ($use_special) {
$chars = self::append($chars, self::charsOf('~`!@#$%^&*()-_=+\\|<,>./?:;"\''));
}
if (empty($chars)) {
throw new \Exception('All options is empty');
}
$result = [];
for ($i = 0; $i < $length; ++$i) {
shuffle($chars);
$result[] = $chars[0];
}
return implode('', $result);
}
/**
* append $tail to $head
*
* @param array $head
* @param array $tail
*
* @return array
*/
private static function append($head, $tail)
{
array_splice($head, count($head), null, $tail);
return $head;
}
/**
* split utf-8 string to array of chars
*
* @param string $str
* @return array
*/
private static function charsOf($str)
{
return preg_split('/(?<!^)(?!$)/u', $str);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment