Completed
Push — master ( ea11b7...4be545 )
by Beñat
01:45
created

Pdo   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 0
dl 0
loc 52
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A query() 0 4 1
A insert() 0 9 1
A executeAtomically() 0 16 3
A execute() 0 7 1
1
<?php
2
3
/*
4
 * This file is part of the Shared Kernel library.
5
 *
6
 * Copyright (c) 2016-present LIN3S <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace LIN3S\SharedKernel\Infrastructure\Persistence\Sql;
15
16
/**
17
 * @author Beñat Espiña <[email protected]>
18
 */
19
final class Pdo
20
{
21
    public const DATE_FORMAT = 'Y-m-d H:i:s';
22
23
    private $pdo;
24
25
    public function __construct(\PDO $pdo)
26
    {
27
        $this->pdo = $pdo;
28
        $this->pdo->setAttribute($this->pdo::ATTR_ERRMODE, $this->pdo::ERRMODE_EXCEPTION);
29
    }
30
31
    public function query(string $sql, array $parameters) : array
32
    {
33
        return $this->execute($sql, $parameters)->fetchAll(\PDO::FETCH_ASSOC);
34
    }
35
36
    public function insert($table, $columns, $numberOfInsertions, callable $prepareData) : void
37
    {
38
        $rowPlaces = '(' . implode(', ', array_fill(0, count($columns), '?')) . ')';
39
        $allPlaces = implode(', ', array_fill(0, $numberOfInsertions, $rowPlaces));
40
41
        $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $columns) . ') VALUES ' . $allPlaces;
42
43
        $this->execute($sql, call_user_func($prepareData));
44
    }
45
46
    public function executeAtomically(callable $function)
47
    {
48
        $this->pdo->beginTransaction();
49
50
        try {
51
            $return = call_user_func($function, $this);
52
53
            $this->pdo->commit();
54
55
            return $return ?: true;
56
        } catch (\Exception | \Throwable $exception) {
57
            $this->pdo->rollback();
58
59
            throw $exception;
60
        }
61
    }
62
63
    public function execute(string $sql, array $parameters) : \PDOStatement
64
    {
65
        $statement = $this->pdo->prepare($sql);
66
        $statement->execute($parameters);
67
68
        return $statement;
69
    }
70
}
71