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