Completed
Push — master ( 21fef4...f7e2e6 )
by Tomasz
05:34
created

DoctrineConfig::acquireDbId()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 29
ccs 19
cts 19
cp 1
rs 8.8571
cc 2
eloc 19
nc 2
nop 0
crap 2
1
<?php
2
3
/*
4
 * To change this license header, choose License Headers in Project Properties.
5
 * To change this template file, choose Tools | Templates
6
 * and open the template in the editor.
7
 */
8
9
namespace Gendoria\CruftFlake\Config;
10
11
use Doctrine\DBAL\Connection;
12
use Doctrine\DBAL\Schema\Schema;
13
use Doctrine\DBAL\Types\Type;
14
use Exception;
15
use RuntimeException;
16
17
/**
18
 * Configuration using doctrine DBAL.
19
 *
20
 * @author Tomasz Struczyński <[email protected]>
21
 */
22
class DoctrineConfig implements ConfigInterface
23
{
24
25
    /**
26
     * Default table name.
27
     * 
28
     * @var string
29
     */
30
    const DEFAULT_TABLE_NAME = "gendoria_cruftflake_id";
31
32
    /**
33
     * Doctrine connection.
34
     * 
35
     * @var Connection
36
     */
37
    private $connection;
38
    
39
    /**
40
     * Session TTL.
41
     * 
42
     * @var integer
43
     */
44
    private $sessionTTL;
45
46
    /**
47
     * Last successfull check.
48
     * 
49
     * @var integer|null
50
     */
51
    private $lastSuccessfullCheck = null;
52
53
    /**
54
     * Database table name.
55
     * 
56
     * @var string
57
     */
58
    private $tableName = self::DEFAULT_TABLE_NAME;
59
    
60
    /**
61
     * Machine ID.
62
     * 
63
     * @var integer
64
     */
65
    private $machineId;    
66
67 11
    function __construct(Connection $connection, $sessionTTL = 600, $tableName = self::DEFAULT_TABLE_NAME)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
68
    {
69 11
        $this->connection = $connection;
70 11
        $this->sessionTTL = $sessionTTL;
71 11
        $this->tableName = $tableName;
72 11
    }
73
74
    /**
75
     * Class destructor. 
76
     * 
77
     * Clears session in DBAL.
78
     */
79 11
    public function __destruct()
80
    {
81 11
        $this->destroySession();
82 11
    }
83
84
    /**
85
     * {@inheritdoc}
86
     */
87 10
    public function getMachine()
88
    {
89 10
        if ($this->machineId === null) {
90
            try {
91 10
                $this->machineId = $this->acquireMachineId();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->acquireMachineId() can also be of type boolean. However, the property $machineId is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
92 10
            } catch (\RuntimeException $e) {
93 1
                throw $e;
94 1
            } catch (\Exception $e) {
95 1
                throw new \RuntimeException("Cannot acquire machine ID", 500, $e);
96
            }
97 9
        }
98 9
        return $this->machineId;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->machineId; of type boolean|integer adds the type boolean to the return on line 98 which is incompatible with the return type declared by the interface Gendoria\CruftFlake\Conf...igInterface::getMachine of type integer.
Loading history...
99
    }
100
101
    /**
102
     * Configuration heartbeat. 
103
     * 
104
     * Heartbeat connects periodically to database to renew session and check its validity.
105
     * 
106
     * @return bool True, if configuration data had been changed during heartbeat.
107
     * 
108
     * @throws RuntimeException Thrown, when we could not create new session and it was needed.
109
     */
110 4
    public function heartbeat()
111
    {
112
        //If we have last successfull check recently new, we don't have to do anything
113 4
        if ($this->lastSuccessfullCheck !== null && time() - $this->lastSuccessfullCheck < $this->sessionTTL / 2) {
114 1
            return false;
115
        }
116
        
117
        //If we don't yet have machine ID, nothing happens.
118 4
        if ($this->machineId === null) {
119 1
            return false;
120
        }
121
        
122
        try {
123 3
            $tmpSuccessfullCheck = time();
124 3
            $qb = $this->connection->createQueryBuilder();
125 3
            $qb->update($this->tableName)
126 3
                ->set('last_access', $tmpSuccessfullCheck)
127 3
                ->where('machine_id = ?')
128 3
                ->setParameter(0, $this->machineId)
129
                ;
130 3
            $rows = $qb->execute();
131
            //Perform garbage collection
132 2
            $this->gc();
133 2
            if ($rows == 0) {
134 1
                $this->machineId = null;
135 1
                $this->lastSuccessfullCheck = null;
136 1
                return true;
137
            }
138 1
            $this->lastSuccessfullCheck = $tmpSuccessfullCheck;
139 1
            return false;
140 1
        } catch (Exception $e) {
141 1
            throw new RuntimeException("Counld not connect to database", 500, $e);
142
        }
143
    }
144
145
    /**
146
     * Return machine ID from DBAL.
147
     * 
148
     * @return integer
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|integer?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
149
     * @throws RuntimeException
150
     */
151 10
    private function acquireMachineId()
152
    {
153 10
        $this->gc();
154
155 9
        $time = time();
156 9
        $possibleMachineId = $this->acquireDbId();
157
        
158 9
        if ($possibleMachineId > 1023) {
159 1
            throw new \RuntimeException("Cannot acquire machine ID - too many machines present");
160
        } else {
161 9
            $this->connection->insert($this->tableName, array(
162 9
                'machine_id' => $possibleMachineId,
163 9
                'last_access' => $time,
164 9
            ));
165 9
            return $possibleMachineId;
166
        }
167
    }
168
    
169
    /**
170
     * Acquire next ID from database.
171
     * 
172
     * @return boolean|integer
173
     */
174 9
    private function acquireDbId()
175
    {
176 9
        $qbFirst = $this->connection->createQueryBuilder();
177 9
        $qbFirst->select('c1.machine_id AS machine_id')
178 9
            ->from($this->tableName, 'c1')
179 9
            ->where('c1.machine_id=0')
180 9
            ->orderBy('c1.machine_id', 'ASC')
181 9
            ->setMaxResults(1)
182
            ;
183
        //Either the table is empty, or it does not have first ID present.
184 9
        if ($qbFirst->execute()->fetchColumn() === false) {
185 9
            return 0;
186
        }
187
        
188
        //We have at least one ID in database, we should find next one.
189 4
        $qb = $this->connection->createQueryBuilder();
190 4
        $qb->select('c1.machine_id+1 AS machine_id')
191 4
            ->from($this->tableName, 'c1')
192 4
            ->leftJoin('c1', $this->tableName, 'c2', 'c1.machine_id+1 = c2.machine_id')
193 4
            ->leftJoin('c1', $this->tableName, 'c3', 'c1.machine_id-1 = c2.machine_id')
194 4
            ->where('c2.machine_id IS NULL')
195
            //->orWhere('c3.machine_id IS NULL AND c1.machine_id=1')
196 4
            ->orderBy('c1.machine_id', 'ASC')
197 4
            ->setMaxResults(1)
198
            ;
199
        
200 4
        $id = $qb->execute()->fetchColumn();
201 4
        return $id;
202
    }
203
204
    /**
205
     * Destroy session.
206
     */
207 11
    private function destroySession()
208
    {
209
        //Nothing to destroy
210 11
        if ($this->machineId === null) {
211 4
            return;
212
        }
213
        
214
        try {
215 8
            $qb = $this->connection->createQueryBuilder()
216 8
                ->delete($this->tableName)
217 8
                ->where('machine_id = ?')
218 8
                ->setParameter(0, $this->machineId);
219 8
            $qb->execute();
220 8
        } catch (\Exception $e) {
221
            //Nothing can be done here, we'll fail silently
222
        }
223 8
    }
224
225
    /**
226
     * Create database table.
227
     */
228 11
    public static function createTable(Connection $connection, $tableName = self::DEFAULT_TABLE_NAME)
229
    {
230 11
        $schema = new Schema();
231 11
        $myTable = $schema->createTable($tableName);
232 11
        $myTable->addColumn("machine_id", Type::INTEGER, array("unsigned" => true));
233 11
        $myTable->addColumn("last_access", Type::BIGINT, array("unsigned" => true));
234 11
        $myTable->setPrimaryKey(array("machine_id"));
235 11
        $sql = $schema->toSql($connection->getDatabasePlatform());
236 11
        foreach ($sql as $statement) {
237 11
            $connection->exec($statement);
238 11
        }
239 11
    }
240
    
241
    /**
242
     * Garbage collector: remove unused sessions.
243
     */
244 10
    private function gc()
245
    {
246 10
        $lastAccess = time() - $this->sessionTTL;
247 10
        $qb = $this->connection->createQueryBuilder();
248 10
        $qb->delete($this->tableName)
249 10
            ->where('last_access < ?')
250 10
            ->setParameter(0, $lastAccess);
251 10
        $qb->execute();
252
    }
253
}