Passed
Push — master ( 612632...9e8075 )
by Dedipyaman
08:57
created

AlphaNumeric::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of Phypes <https://github.com/2DSharp/Phypes>.
4
 *
5
 * (c) Dedipyaman Das <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
12
namespace Phypes\Rule\String;
13
14
use Phypes\Error\RuleError;
15
use Phypes\Error\RuleErrorCode;
16
use Phypes\Result\Failure;
17
use Phypes\Result\Result;
18
use Phypes\Result\Success;
19
use Phypes\Rule\Rule;
20
21
class AlphaNumeric implements Rule
22
{
23
    // TODO: Add AlphaNumeric test
24
    /**
25
     * Special characters excused within the alphanum value
26
     * Handy for username validations
27
     * @var array $allowedSpecialChars
28
     */
29
    private $allowedSpecialChars;
30
31
    /**
32
     * AlphaNumeric constructor.
33
     * @param array $allowedSpecialChars
34
     */
35
    public function __construct($allowedSpecialChars = [])
36
    {
37
        $this->allowedSpecialChars = $allowedSpecialChars;
38
    }
39
40
    public function validate($data): Result
41
    {
42
        if (ctype_alnum(str_replace($this->allowedSpecialChars, '', $data)))
43
            return new Success();
44
        else
45
            return new Failure(new RuleError(RuleErrorCode::NOT_ALNUM, 'String is not Alphanumeric.'));
46
    }
47
}