-
Notifications
You must be signed in to change notification settings - Fork 6
/
SQLite.php
95 lines (77 loc) 路 2.56 KB
/
SQLite.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
namespace Lloople\PHPUnitExtensions\Runners;
use Exception;
use Lloople\PHPUnitExtensions\Time;
use PDO;
use PHPUnit\Runner\AfterTestHook;
class SQLite implements AfterTestHook
{
protected $connection = null;
protected $credentials = [
'database' => 'phpunit_results.db',
'table' => 'default',
];
public function __construct(array $credentials = [])
{
try {
$this->credentials = array_merge($this->credentials, $credentials);
$this->connect();
if (! $this->tableExists()) {
$this->createTable();
}
} catch (Exception $e) {
echo "SQLite Runner skipped: {$e->getMessage()}" . PHP_EOL;
}
}
public function executeAfterTest(string $test, float $time): void
{
if ($this->connection === null) {
return;
}
try {
$this->insert($test, $time);
} catch (Exception $e) {
echo "SQLite Runner skipped: {$e->getMessage()}" . PHP_EOL;
$this->connection = null;
}
}
protected function insert(string $test, float $time): void
{
[$class, $method] = explode('::', $test);
$this->connection
->prepare(
"INSERT INTO `{$this->credentials['table']}` (time, method, class, name)
VALUES(:time, :method, :class, :name)
ON CONFLICT(name) DO UPDATE SET time = :time;"
)
->execute([
'time' => new Time($time),
'method' => $method,
'class' => $class,
'name' => $test,
]);
}
protected function connect(): void
{
$this->connection = new PDO("sqlite:{$this->credentials['database']}");
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
protected function tableExists(): bool
{
$query = $this->connection->prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=:table;");
$query->execute(['table' => $this->credentials['table']]);
return $query->fetch() !== false;
}
protected function createTable(): void
{
$this->connection->prepare(
"CREATE TABLE {$this->credentials['table']} (
`time` float DEFAULT NULL,
`name` varchar(255) NOT NULL,
`method` varchar(255) DEFAULT NULL,
`class` varchar(255) DEFAULT NULL,
PRIMARY KEY (`name`)
);"
)->execute();
}
}