Completed
Push — master ( 89191a...ad3690 )
by Hong
01:49
created

SequenceTrait::toTimeStamp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
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
/**
18
 * SequenceTrait
19
 *
20
 * Time & sequence related stuff
21
 *
22
 * @package Phossa2\Uuid
23
 * @author  Hong Zhang <[email protected]>
24
 * @version 2.1.0
25
 * @since   2.1.0 added
26
 */
27
trait SequenceTrait
28
{
29
    use UtilityTrait;
30
31
    /**
32
     * epoch for this uuid lib
33
     *
34
     * @var    string
35
     * @access protected
36
     * @staticvar
37
     */
38
    protected static $epoch = '2016/01/01';
39
40
    /**
41
     * Time related part
42
     *
43
     * @return string 15-char string
44
     * @access protected
45
     */
46
    protected function getTimestamp()/*# : string */
47
    {
48
        $num = bcadd(
49
            bcmul((microtime(true) - strtotime(static::$epoch)), 100000000),
50
            $this->getSequence() % 10000
51
        );
52
        return substr('00' . static::fromBase10($num, self::BASE16), -15);
53
    }
54
55
    /**
56
     * Reverse of getTimestamp(), convert 15-char string to unix time
57
     *
58
     * @param  string $hexValue
59
     * @return int
60
     * @access protected
61
     * @static
62
     */
63
    protected static function toTimeStamp(/*# string */ $hexValue)/*# : int */
64
    {
65
        $dec = bcdiv(static::toBase10($hexValue, self::BASE16), 100000000, 0);
66
        return (int) ($dec + strtotime(static::$epoch));
67
    }
68
69
    /**
70
     * Get a pseudo sequence number
71
     *
72
     * @return int
73
     * @access protected
74
     * @static
75
     */
76
    protected function getSequence()/*# : int */
77
    {
78
        static $seq = 0;
79
        return $seq++;
80
    }
81
}
82