Otp::isValid()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
/**
4
 * Copyright 2014 SURFnet bv
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\YubikeyApiClient;
20
21
use Surfnet\YubikeyApiClient\Exception\InvalidArgumentException;
22
23
class Otp
24
{
25
    const OTP_REGEXP_QWERTY = '/^((.*):)?(([cbdefghijklnrtuv]{0,16})([cbdefghijklnrtuv]{32}))$/i';
26
    const OTP_REGEXP_DVORAK = '/^((.*):)?(([jxe\.uidchtnbpygk]{0,16})([jxe\.uidchtnbpygk]{32}))$/i';
27
28
    /** @var string */
29
    public $otp;
30
31
    /** @var string */
32
    public $password;
33
34
    /** @var string */
35
    public $publicId;
36
37
    /** @var string */
38
    public $cipherText;
39
40
    /**
41
     * @param string $string
42
     * @return self
43
     * @throws InvalidArgumentException Thrown when the given string is not an OTP.
44
     */
45
    public static function fromString($string)
46
    {
47
        $otp = new self;
48
49
        if (!is_string($string)) {
50
            throw new InvalidArgumentException('Given OTP is not a string.');
51
        }
52
53
        if (preg_match(self::OTP_REGEXP_QWERTY, $string, $matches)) {
54
            $otp->otp = strtolower($matches[3]);
55
            $otp->password = $matches[2];
56
            $otp->publicId = strtolower($matches[4]);
57
            $otp->cipherText = strtolower($matches[5]);
58
        } elseif (preg_match(self::OTP_REGEXP_DVORAK, $string, $matches)) {
59
            $otp->otp = strtr(strtolower($matches[3]), 'jxe.uidchtnbpygk', 'cbdefghijklnrtuv');
60
            $otp->password = $matches[2];
61
            $otp->publicId = strtr(strtolower($matches[4]), 'jxe.uidchtnbpygk', 'cbdefghijklnrtuv');
62
            $otp->cipherText = strtr(strtolower($matches[5]), 'jxe.uidchtnbpygk', 'cbdefghijklnrtuv');
63
        } else {
64
            throw new InvalidArgumentException('Given string is not a valid OTP.');
65
        }
66
67
        return $otp;
68
    }
69
70
    /**
71
     * @param string $string
72
     * @return bool
73
     */
74
    public static function isValid($string)
75
    {
76
        return preg_match(self::OTP_REGEXP_QWERTY, $string, $matches)
77
            || preg_match(self::OTP_REGEXP_DVORAK, $string, $matches);
78
    }
79
}
80