PhraseBuilder.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Webman\Captcha;
  3. /**
  4. * Generates random phrase
  5. *
  6. * @author Gregwar <g.passault@gmail.com>
  7. */
  8. class PhraseBuilder implements PhraseBuilderInterface
  9. {
  10. /**
  11. * @var int
  12. */
  13. public $length;
  14. /**
  15. * @var string
  16. */
  17. public $charset;
  18. /**
  19. * Constructs a PhraseBuilder with given parameters
  20. */
  21. public function __construct($length = 5, $charset = 'abcdefghijklmnpqrstuvwxyz123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
  22. {
  23. $this->length = $length;
  24. $this->charset = $charset;
  25. }
  26. /**
  27. * Generates random phrase of given length with given charset
  28. */
  29. public function build($length = null, $charset = null)
  30. {
  31. if ($length !== null) {
  32. $this->length = $length;
  33. }
  34. if ($charset !== null) {
  35. $this->charset = $charset;
  36. }
  37. $phrase = '';
  38. $chars = str_split($this->charset);
  39. for ($i = 0; $i < $this->length; $i++) {
  40. $phrase .= $chars[array_rand($chars)];
  41. }
  42. return $phrase;
  43. }
  44. /**
  45. * "Niceize" a code
  46. */
  47. public function niceize($str)
  48. {
  49. return self::doNiceize($str);
  50. }
  51. /**
  52. * A static helper to niceize
  53. */
  54. public static function doNiceize($str)
  55. {
  56. return strtr(strtolower($str), '01', 'ol');
  57. }
  58. /**
  59. * A static helper to compare
  60. */
  61. public static function comparePhrases($str1, $str2)
  62. {
  63. return self::doNiceize($str1) === self::doNiceize($str2);
  64. }
  65. }