IDCard::assertValidIDCard()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 11
nc 6
nop 1
1
<?php
2
/*
3
 * This file is part of the Slince/China package.
4
 *
5
 * (c) Slince <[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
namespace China\IDCard;
12
13
class IDCard implements IDCardInterface
14
{
15
    /**
16
     * 身份证数字.
17
     *
18
     * @var number
19
     */
20
    protected $id;
21
22
    public function __construct($id)
23
    {
24
        static::assertValidIDCard($id);
25
        $this->id = $id;
26
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function __toString()
32
    {
33
        return $this->id;
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function isShortLength()
40
    {
41
        return strlen($this->id) === 15;
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function getLongNumber()
48
    {
49
        $id = $this->id;
50
        if ($this->isShortLength()) {
51
            $id = IDCardUtils::convertIDCard15to18($this->id);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression \China\IDCard\IDCardUtil...DCard15to18($this->id); of type false|string adds false to the return on line 54 which is incompatible with the return type declared by the interface China\IDCard\IDCardInterface::getLongNumber of type integer|double. It seems like you forgot to handle an error condition.
Loading history...
52
        }
53
54
        return $id;
55
    }
56
57
    /**
58
     * 身份证是否合法.
59
     *
60
     * @param string $id
61
     */
62
    public static function assertValidIDCard($id)
63
    {
64
        if (!is_numeric($id)) {
65
            throw new \InvalidArgumentException(sprintf('The id "%s" card contains the non-numeric characters', $id));
66
        }
67
        $length = strlen($id);
68
        if ($length !== 15 && $length !== 18) {
69
            throw new \InvalidArgumentException(sprintf('The id "%s" card length should be 15 numbers or 18 numbers, given %d', $id, $length));
70
        }
71
        $convertedId = $id;
72
        if ($length === 15) {
73
            $convertedId = IDCardUtils::convertIDCard15to18($id);
74
        }
75
        if (!IDCardUtils::check18IDCard($convertedId)) {
76
            throw new \InvalidArgumentException(sprintf('The Id card "%s" is invalid',  $id));
77
        }
78
    }
79
}