aboutsummaryrefslogtreecommitdiff
path: root/tests/_support/Helper/StudipDb.php
blob: 8188be1dbaf575e6aa137c382e93126cf09f28b4 (plain)
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
<?php

namespace Helper;

use Codeception\Exception\ModuleConfigException;
use Codeception\Exception\ModuleException;

require_once 'lib/classes/StudipPDO.php';

class StudipDb extends \Codeception\Module
{
    /**
     * @api
     */
    public ?\StudipPdo $dbh;

    protected array $config = [];

    protected array $requiredFields = ['dsn', 'user', 'password'];

    /**
     * @SuppressWarnings(PHPMD.CamelCaseMethodName)
     */
    public function _initialize()
    {
        $this->checkConfig('dsn', 'DB_STUDIP_HOST');
        $this->checkConfig('dsn', 'DB_STUDIP_DATABASE');
        $this->checkConfig('user', 'DB_STUDIP_USER');
        $this->checkConfig('password', 'DB_STUDIP_PASSWORD');

        $this->connect();
    }

    private function checkConfig($configKey, $name)
    {
        if (str_contains($this->config[$configKey], '%' . $name . '%')) {
            throw new ModuleConfigException(__CLASS__, 'You have to provide a '.$name.' either as ENV variable or in config_local.inc.php!');
        }
    }

    private function connect()
    {
        try {
            $this->dbh = null;
            $this->dbh = new \StudipPDO($this->config['dsn'], $this->config['user'], $this->config['password']);
        } catch (\PDOException $e) {
            throw new ModuleException(__CLASS__, $e->getMessage().' while creating PDO connection');
        }
    }

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     * @SuppressWarnings(PHPMD.CamelCaseMethodName)
     */
    public function _before(\Codeception\TestInterface $test)
    {
        $this->dbh->beginTransaction();
    }

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     * @SuppressWarnings(PHPMD.CamelCaseMethodName)
     */
    public function _after(\Codeception\TestInterface $test)
    {
        $this->dbh->rollBack();
    }
}