Completed
Push — master ( 0ec757...511d0a )
by
unknown
89:40 queued 75:27
created

SqliteGateway   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 57
rs 10
c 0
b 0
f 0
wmc 4
lcom 1
cbo 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getColumnNextIntegerValue() 0 16 1
A getLastInsertedId() 0 11 2
1
<?php
2
3
/**
4
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
5
 * @license For full copyright and license information view LICENSE file distributed with this source code.
6
 */
7
declare(strict_types=1);
8
9
namespace eZ\Publish\Core\Persistence\Legacy\SharedGateway\DatabasePlatform;
10
11
use Doctrine\DBAL\Connection;
12
use Doctrine\DBAL\FetchMode;
13
use eZ\Publish\Core\Base\Exceptions\DatabaseException;
14
use eZ\Publish\Core\Persistence\Legacy\SharedGateway\Gateway;
15
16
final class SqliteGateway implements Gateway
17
{
18
    /**
19
     * Error code 7 for a fatal error - taken from an existing driver implementation.
20
     */
21
    private const FATAL_ERROR_CODE = 7;
22
23
    /** @var \Doctrine\DBAL\Connection */
24
    private $connection;
25
26
    /** @var \Doctrine\DBAL\Platforms\AbstractPlatform */
27
    private $databasePlatform;
28
29
    /** @var int[] */
30
    private $lastInsertedIds = [];
31
32
    /**
33
     * @throws \Doctrine\DBAL\DBALException
34
     */
35
    public function __construct(Connection $connection)
36
    {
37
        $this->connection = $connection;
38
        $this->databasePlatform = $connection->getDatabasePlatform();
39
    }
40
41
    public function getColumnNextIntegerValue(
42
        string $tableName,
43
        string $columnName,
44
        string $sequenceName
45
    ): ?int {
46
        $query = $this->connection->createQueryBuilder();
47
        $query
48
            ->select($this->databasePlatform->getMaxExpression($columnName))
49
            ->from($tableName);
50
51
        $lastId = (int)$query->execute()->fetch(FetchMode::COLUMN);
52
53
        $this->lastInsertedIds[$sequenceName] = $lastId + 1;
54
55
        return $this->lastInsertedIds[$sequenceName];
56
    }
57
58
    /**
59
     * @throws \eZ\Publish\Core\Base\Exceptions\DatabaseException if the sequence has no last value
60
     */
61
    public function getLastInsertedId(string $sequenceName): int
62
    {
63
        if (!isset($this->lastInsertedIds[$sequenceName])) {
64
            throw new DatabaseException(
65
                "Sequence '{$sequenceName}' is not yet defined in this session",
66
                self::FATAL_ERROR_CODE
67
            );
68
        }
69
70
        return $this->lastInsertedIds[$sequenceName];
71
    }
72
}
73