Completed
Push — master ( 316baf...2178d1 )
by Raffael
67:25 queued 62:39
created

Engine::uuidv4()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 11
cp 0
rs 9.504
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * tubee.io
7
 *
8
 * @copyright   Copryright (c) 2017-2019 gyselroth GmbH (https://gyselroth.com)
9
 * @license     GPL-3.0 https://opensource.org/licenses/GPL-3.0
10
 */
11
12
namespace Tubee\V8;
13
14
use Psr\Log\LoggerInterface;
15
use V8Js;
16
17
class Engine extends V8Js
18
{
19
    protected $__result;
20
21
    /**
22
     * Create v8 engine with some default functionality.
23
     */
24 27
    public function __construct(LoggerInterface $logger)
25
    {
26 27
        parent::__construct('core', [], [], true, '');
27 27
        $this->logger = $logger;
28 27
        $this->registerFunctions();
29 27
        $this->setMemoryLimit(50000000);
30 27
    }
31
32
    public function result($result)
33
    {
34
        $this->__result = $result;
35
    }
36
37 2
    public function getLastResult()
38
    {
39 2
        $result = $this->__result;
40 2
        $this->__result = null;
41
42 2
        return $result;
43
    }
44
45
    /**
46
     * Convert to UTF16.
47
     */
48
    public function utf16(string $string): string
49
    {
50
        $len = strlen($string);
51
        $new = '';
52
53
        for ($i = 0; $i < $len; ++$i) {
54
            $new .= "{$string[$i]}\000";
55
        }
56
57
        return $new;
58
    }
59
60
    /**
61
     * Create UUIDv4.
62
     */
63
    public function uuidv4(): string
64
    {
65
        return sprintf(
66
            '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
67
            // 32 bits for "time_low"
68
            mt_rand(0, 0xffff),
69
            mt_rand(0, 0xffff),
70
71
            // 16 bits for "time_mid"
72
            mt_rand(0, 0xffff),
73
74
            // 16 bits for "time_hi_and_version",
75
            // four most significant bits holds version number 4
76
            mt_rand(0, 0x0fff) | 0x4000,
77
78
            // 16 bits, 8 bits for "clk_seq_hi_res",
79
            // 8 bits for "clk_seq_low",
80
            // two most significant bits holds zero and one for variant DCE1.1
81
            mt_rand(0, 0x3fff) | 0x8000,
82
83
            // 48 bits for "node"
84
            mt_rand(0, 0xffff),
85
            mt_rand(0, 0xffff),
86
            mt_rand(0, 0xffff)
87
        );
88
    }
89
90
    /**
91
     * Register functions.
92
     */
93 27
    protected function registerFunctions(): void
94
    {
95 27
        $this->crypt = [
96 27
            'hash' => function ($algo, $data, $raw_output = false) {
97
                return hash($algo, $data, $raw_output);
98 27
            },
99
        ];
100 27
    }
101
}
102