Completed
Push — 4.11 ( d3252b...dccaa9 )
by Steve
33s queued 25s
created

Utf8TestHelper::isMySqlGte80()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 7
rs 10
1
<?php
2
3
namespace SilverStripe\Tests\ORM\Utf8;
4
5
use SilverStripe\Dev\TestOnly;
6
use SilverStripe\ORM\DB;
7
8
class Utf8TestHelper implements TestOnly
9
{
10
    private ?string $dbVersion = null;
11
12
    public function getUpdatedUtfCharsetForCurrentDB(string $charset): string
13
    {
14
        if ($charset !== 'utf8') {
15
            return $charset;
16
        }
17
        return $this->isMySqlGte80() || $this->isMariaDBGte106() ? 'utf8mb3' : 'utf8';
18
    }
19
20
    public function getUpdatedUtfCollationForCurrentDB(string $collation): string
21
    {
22
        if ($collation === 'utf8_general_ci') {
23
            return $this->isMariaDBGte106() ? 'utf8mb3_general_ci' : 'utf8_general_ci';
24
        }
25
        if ($collation === 'utf8_unicode_520_ci') {
26
            return $this->isMariaDBGte106() ? 'utf8mb3_unicode_520_ci' : 'utf8_unicode_520_ci';
27
        }
28
        return $collation;
29
    }
30
31
    /**
32
     * MySQL has used utf8 as an alias for utf8mb3
33
     * Beginning with MySQL 8.0.28, utf8mb3 is used
34
     * https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-utf8mb3.html
35
     */
36
    private function isMySqlGte80(): bool
37
    {
38
        // Example MySQL version: 8.0.29
39
        if (preg_match('#^([0-9]+)\.[0-9]+\.[0-9]+$#', $this->getDBVersion(), $m)) {
40
            return (int) $m[1] >= 8;
41
        }
42
        return false;
43
    }
44
45
    /**
46
     * Until MariaDB 10.5, utf8mb3 was an alias for utf8.
47
     * From MariaDB 10.6, utf8 is by default an alias for utf8mb3
48
     * https://mariadb.com/kb/en/unicode/
49
     */
50
    private function isMariaDBGte106(): bool
51
    {
52
        // Example mariadb version: 5.5.5-10.6.8-mariadb-1:10.6.8+maria~focal
53
        if (preg_match('#([0-9]+)\.([0-9]+)\.[0-9]+-mariadb#', $this->getDBVersion(), $m)) {
54
            return (int) $m[1] >= 11 || ((int) $m[1] >= 10 && (int) $m[2] >= 6);
55
        }
56
        return false;
57
    }
58
59
    private function getDBVersion(): string
60
    {
61
        if (is_null($this->dbVersion)) {
62
            $this->dbVersion = strtolower(DB::get_conn()->getVersion());
63
        }
64
        return $this->dbVersion;
65
    }
66
}
67