Completed
Pull Request — master (#1)
by Fabrice
06:06
created

FlowIdTrait   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 54
c 0
b 0
f 0
wmc 3
lcom 1
cbo 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __clone() 0 4 1
A getId() 0 18 2
1
<?php
2
3
/*
4
 * This file is part of NodalFlow.
5
 *     (c) Fabrice de Stefanis / https://github.com/fab2s/NodalFlow
6
 * This source file is licensed under the MIT license which you will
7
 * find in the LICENSE file or at https://opensource.org/licenses/MIT
8
 */
9
10
namespace fab2s\NodalFlow\Flows;
11
12
/**
13
 * Trait FlowIdTrait
14
 */
15
trait FlowIdTrait
16
{
17
    /**
18
     * This Flow / Node id
19
     *
20
     * @var string
21
     */
22
    protected $id;
23
24
    /**
25
     * Current nonce, fully valid within each thread
26
     *
27
     * @var int
28
     */
29
    protected static $nonce = 0;
30
31
    /**
32
     * We need to reset the id when being cloned
33
     * to guarantee immutable uniqueness
34
     */
35
    public function __clone()
36
    {
37
        $this->id = null;
38
    }
39
40
    /**
41
     * Return the immutable unique Flow / Node id
42
     * Since this method is not used in the actual
43
     * flow execution loop, but only when an interruption
44
     * is raised, it's not a performance issue to add an if.
45
     * And it's more convenient to lazy generate as this
46
     * trait does not need any init/construct logic.
47
     *
48
     * @return string immutable unique id
49
     */
50
    public function getId()
51
    {
52
        if ($this->id === null) {
53
            // would require more effort if we where to massively generate / store Flows
54
            $timeParts       = explode(' ', microtime(false));
55
56
            return $this->id = implode('.', array_map(function ($value) {
57
                return base_convert($value, 10, 36);
58
            }, [
59
                $timeParts[1],
60
                $timeParts[0] * 1000000,
61
                ++static::$nonce,
62
                mt_rand(0, 999999),
63
            ]));
64
        }
65
66
        return $this->id;
67
    }
68
}
69