Completed
Push — master ( dd48d5...e540fe )
by Beñat
05:08
created

Pdo::count()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
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 count(string $sql, array $parameters = []) : int
37
    {
38
        return (int) $this->execute($sql, $parameters)->fetchColumn();
39
    }
40
41
    public function insert(string $table, array $parameters) : void
42
    {
43
        if (!is_array($parameters[array_keys($parameters)[0]])) {
44
            $parameters = [$parameters];
45
        }
46
47
        $values = [];
48
        foreach ($parameters as $parameter) {
49
            $values = array_merge($values, array_values($parameter));
50
        }
51
        $numberOfInsertions = count($parameters);
52
        $columns = array_keys($parameters[array_keys($parameters)[0]]);
53
        $rowPlaces = '(' . implode(', ', array_fill(0, count($columns), '?')) . ')';
54
        $allPlaces = implode(', ', array_fill(0, $numberOfInsertions, $rowPlaces));
55
56
        $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $columns) . ') VALUES ' . $allPlaces;
57
58
        $this->execute($sql, $values);
59
    }
60
61
    public function executeAtomically(callable $function)
62
    {
63
        $this->pdo->beginTransaction();
64
65
        try {
66
            $return = call_user_func($function, $this);
67
68
            $this->pdo->commit();
69
70
            return $return ?: true;
71
        } catch (\Exception | \Throwable $exception) {
72
            $this->pdo->rollback();
73
74
            throw $exception;
75
        }
76
    }
77
78
    public function execute(string $sql, array $parameters) : \PDOStatement
79
    {
80
        $statement = $this->pdo->prepare($sql);
81
        $statement->execute($parameters);
82
83
        return $statement;
84
    }
85
}
86