Completed
Push — master ( ad3690...aa72f7 )
by Hong
01:48
created

UtilityTrait::getTimestamp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 1
eloc 5
nc 1
nop 0
1
<?php
2
/**
3
 * Phossa Project
4
 *
5
 * PHP version 5.4
6
 *
7
 * @category  Library
8
 * @package   Phossa2\Uuid
9
 * @copyright Copyright (c) 2016 phossa.com
10
 * @license   http://mit-license.org/ MIT License
11
 * @link      http://www.phossa.com/
12
 */
13
/*# declare(strict_types=1); */
14
15
namespace Phossa2\Uuid\Traits;
16
17
use Phossa2\Uuid\Message\Message;
18
use Phossa2\Uuid\Exception\LogicException;
19
use Phossa2\Uuid\Interfaces\UuidInterface;
20
use Phossa2\Uuid\Interfaces\UtilityInterface;
21
22
/**
23
 * UtilityTrait
24
 *
25
 * @package Phossa2\Uuid
26
 * @author  Hong Zhang <[email protected]>
27
 * @see     UtilityInterface
28
 * @see     UuidInterface
29
 * @version 2.1.0
30
 * @since   2.0.0 added
31
 * @since   2.1.0 including SequenceTrait, updated info()
32
 */
33
trait UtilityTrait
34
{
35
    /**
36
     * epoch for this uuid lib
37
     *
38
     * @var    string
39
     * @access protected
40
     * @staticvar
41
     */
42
    protected static $epoch = '2016/01/01';
43
44
    /**
45
     * {@inheritDoc}
46
     */
47
    public static function isValid(/*# string */ $uuid)/*# : bool */
48
    {
49
        $pattern = '~^' . substr(self::VERSION, 0, 1) . '[0-9a-f]{31}$~';
50
        return is_string($uuid) && (bool) preg_match($pattern, $uuid);
51
    }
52
53
    /**
54
     * {@inheritDoc}
55
     */
56
    public static function info(/*# string */ $uuid)/*# : array */
57
    {
58
        if (static::isValid($uuid)) {
59
            return [
60
                'version' => substr($uuid, 0, 1),
61
                'type'    => substr($uuid, 1, 4),
62
                'time'    => static::toTimestamp(substr($uuid, 5, 15)),
63
                'shard'   => substr($uuid, 20, 4),
64
                'vendor'  => substr($uuid, 24, 4),
65
                'remain'  => substr($uuid, 28, 4)
66
            ];
67
        } else {
68
            throw new LogicException(
69
                Message::get(Message::UUID_INVALID, $uuid),
70
                Message::UUID_INVALID
71
            );
72
        }
73
    }
74
75
    /**
76
     * {@inheritDoc}
77
     */
78 View Code Duplication
    public static function encode(
79
        /*# string */ $uuid,
80
        /*# string */ $base = self::BASE56
81
    )/*# : string */ {
82
        if (static::isValid($uuid)) {
83
            return static::convertBase($uuid, self::BASE16, $base);
84
        }
85
        throw new LogicException(
86
            Message::get(Message::UUID_INVALID, $uuid),
87
            Message::UUID_INVALID
88
        );
89
    }
90
91
    /**
92
     * {@inheritDoc}
93
     */
94 View Code Duplication
    public static function decode(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
        /*# string */ $string,
96
        /*# string */ $base = self::BASE56
97
    )/*# : string */ {
98
        $uuid = static::convertBase($string, $base, self::BASE16);
99
        if (static::isValid($uuid)) {
100
            return $uuid;
101
        }
102
        throw new LogicException(
103
            Message::get(Message::UUID_DECODE_FAIL, $string),
104
            Message::UUID_DECODE_FAIL
105
        );
106
    }
107
108
    /**
109
     * Convert numerical string between bases
110
     *
111
     * @param  string $input
112
     * @param  string $fromBase
113
     * @param  string $toBase
114
     * @return string
115
     * @access protected
116
     * @static
117
     */
118
    protected static function convertBase(
119
        /*# string */ $input,
120
        /*# string */ $fromBase,
121
        /*# string */ $toBase
122
    )/*# : string */ {
123
        if ($fromBase === $toBase) {
124
            return $input;
125
        } elseif ($fromBase === self::BASE10) {
126
            return static::fromBase10($input, $toBase);
127
        } elseif ($toBase === self::BASE10) {
128
            return static::toBase10($input, $fromBase);
129
        } else {
130
            return static::fromBase10(static::toBase10($input, $fromBase), $toBase);
131
        }
132
    }
133
134
    /**
135
     * Convert to decimal string
136
     *
137
     * @param  string $input
138
     * @param  string $fromBase
139
     * @return string
140
     * @access protected
141
     */
142
    protected static function toBase10(
143
        /*# string */ $input,
144
        /*# string */ $fromBase
145
    )/*# string */ {
146
        $len = strlen($fromBase);
147
        $res = '0';
148
        foreach (str_split($input) as $char) {
149
            $res = bcadd((int) strpos($fromBase, $char), bcmul($res, $len));
150
        }
151
        return $res;
152
    }
153
154
    /**
155
     * Convert from decimal string
156
     *
157
     * @param  string $input
158
     * @param  string $toBase
159
     * @return string
160
     * @access protected
161
     */
162
    protected static function fromBase10(
163
        /*# string */ $input,
164
        /*# string */ $toBase
165
    )/*# string */ {
166
        $len = strlen($toBase);
167
        $res = '';
168
        do {
169
            $digit = bcmod($input, $len);
170
            $res = $toBase[(int) $digit] . $res;
171
            $input = bcdiv($input, $len, 0);
172
        } while ($input != '0');
173
        return $res;
174
    }
175
176
    /**
177
     * Reverse of getTimestamp(), convert 15-char string to unix time
178
     *
179
     * @param  string $hexString
180
     * @return int
181
     * @access protected
182
     * @static
183
     */
184
    protected static function toTimeStamp(/*# string */ $hexString)/*# : int */
185
    {
186
        $dec = bcdiv(static::toBase10($hexString, self::BASE16), 100000000, 0);
187
        return (int) ($dec + strtotime(static::$epoch));
188
    }
189
190
    /**
191
     * Time related part
192
     *
193
     * @return string 15-char string
194
     * @access protected
195
     */
196
    protected function getTimestamp()/*# : string */
197
    {
198
        $num = bcadd(
199
            bcmul((microtime(true) - strtotime(static::$epoch)), 100000000),
200
            $this->getSequence() % 10000
201
        );
202
        return substr('00' . static::fromBase10($num, self::BASE16), -15);
203
    }
204
205
    /**
206
     * Get a pseudo sequence number
207
     *
208
     * @return int
209
     * @access protected
210
     * @static
211
     */
212
    protected function getSequence()/*# : int */
213
    {
214
        static $seq = 0;
215
        return $seq++;
216
    }
217
}
218