Skip to content

Commit 3d4346c

Browse files
committed
feat: add TableName class
1 parent 0bb7a31 commit 3d4346c

File tree

2 files changed

+108
-0
lines changed

2 files changed

+108
-0
lines changed

system/Database/TableName.php

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <[email protected]>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\Database;
15+
16+
/**
17+
* Represents a single table name.
18+
*
19+
* @see \CodeIgniter\Database\TableNameTest
20+
*/
21+
final class TableName
22+
{
23+
/**
24+
* @param string $raw Raw real table name
25+
* @param string $escaped Escaped real table name
26+
*/
27+
public function __construct(
28+
private string $raw,
29+
private string $escaped
30+
) {
31+
}
32+
33+
/**
34+
* @param string $name A single database name w/o alias
35+
* @param bool $actualName Set true if $name is the actual table name.
36+
*/
37+
public static function create(string $name, BaseConnection $db, bool $actualName = false): self
38+
{
39+
if ($actualName === false) {
40+
$name = $db->DBPrefix . $name;
41+
}
42+
43+
return new self($name, $db->escapeIdentifier($name));
44+
}
45+
46+
public function getEscaped(): string
47+
{
48+
return $this->escaped;
49+
}
50+
51+
public function __toString(): string
52+
{
53+
return $this->raw;
54+
}
55+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <[email protected]>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\Database;
15+
16+
use CodeIgniter\Test\CIUnitTestCase;
17+
18+
/**
19+
* @internal
20+
*
21+
* @group Others
22+
*/
23+
final class TableNameTest extends CIUnitTestCase
24+
{
25+
public function testCanCreateInstance(): void
26+
{
27+
$name = 'table';
28+
29+
$tableName = TableName::create($name, db_connect(), true);
30+
31+
$this->assertSame($name, (string) $tableName);
32+
}
33+
34+
public function testCanConvertToString(): void
35+
{
36+
$raw = 'table';
37+
$escaped = '"table"';
38+
39+
$tableName = new TableName($raw, $escaped);
40+
41+
$this->assertSame($raw, (string) $tableName);
42+
}
43+
44+
public function testCanGetEscapedName(): void
45+
{
46+
$raw = 'table';
47+
$escaped = '"table"';
48+
49+
$tableName = new TableName($raw, $escaped);
50+
51+
$this->assertSame($escaped, $tableName->getEscaped());
52+
}
53+
}

0 commit comments

Comments
 (0)