Created
September 12, 2016 10:34
-
-
Save max-dark/79d6df4b7f35986bf54dd55dbb7e4fbd to your computer and use it in GitHub Desktop.
password generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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