Completed
Push — master ( a7b543...624617 )
by Beñat
02:02
created

Pdo::update()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 20
rs 9.2
cc 4
eloc 12
nc 5
nop 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A Pdo::executeAtomically() 0 16 3
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(string $table, array $parameters) : void
37
    {
38
        if (!is_array($parameters[0])) {
39
            $parameters = [$parameters];
40
        }
41
42
        $values = [];
43
        foreach ($parameters as $parameter) {
44
            $values = array_merge($values, array_values($parameter));
45
        }
46
        $numberOfInsertions = count($parameters);
47
        $columns = array_keys($parameters[0]);
48
        $rowPlaces = '(' . implode(', ', array_fill(0, count($columns), '?')) . ')';
49
        $allPlaces = implode(', ', array_fill(0, $numberOfInsertions, $rowPlaces));
50
51
        $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $columns) . ') VALUES ' . $allPlaces;
52
53
        $this->execute($sql, $values);
54
    }
55
56
    public function executeAtomically(callable $function)
57
    {
58
        $this->pdo->beginTransaction();
59
60
        try {
61
            $return = call_user_func($function, $this);
62
63
            $this->pdo->commit();
64
65
            return $return ?: true;
66
        } catch (\Exception | \Throwable $exception) {
67
            $this->pdo->rollback();
68
69
            throw $exception;
70
        }
71
    }
72
73
    public function execute(string $sql, array $parameters) : \PDOStatement
74
    {
75
        $statement = $this->pdo->prepare($sql);
76
        $statement->execute($parameters);
77
78
        return $statement;
79
    }
80
}
81