Skip to content

Commit 0f383ef

Browse files
authored
Merge pull request #12 from sctice/php-code--handle-empty-constant
PhpCode: Handle empty constant
2 parents 51b71e8 + 49ad222 commit 0f383ef

File tree

2 files changed

+32
-8
lines changed

2 files changed

+32
-8
lines changed

src/PhpCode.php

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -107,17 +107,21 @@ public static function makePhpConstantName($rawName)
107107
{
108108
$phpName = preg_replace("/([^a-zA-Z0-9_]+)/", "_", $rawName);
109109
$phpName = trim($phpName, '_');
110-
$phpName = self::fromCamelCase($phpName);
111110

112-
if (in_array(strtolower($phpName), self::$keywords)) {
113-
$phpName = '_' . $phpName;
114-
}
111+
if ($phpName) {
112+
$phpName = self::fromCamelCase($phpName);
115113

116-
if (!$phpName) {
114+
if (in_array(strtolower($phpName), self::$keywords)) {
115+
$phpName = '_' . $phpName;
116+
}
117+
118+
if (is_numeric($phpName[0])) {
119+
$phpName = 'const_' . $phpName;
120+
}
121+
} else {
117122
$phpName = 'const_' . substr(md5($rawName), 0, 6);
118-
} elseif (is_numeric($phpName[0])) {
119-
$phpName = 'const_' . $phpName;
120123
}
124+
121125
return strtoupper($phpName);
122126
}
123127

tests/src/PHPUnit/PhpCodeTest.php

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,26 @@
77

88
class PhpCodeTest extends \PHPUnit_Framework_TestCase
99
{
10+
public function testMakePhpConstantName()
11+
{
12+
$this->assertSame('A', PhpCode::makePhpConstantName('a'));
13+
$this->assertSame('ABC', PhpCode::makePhpConstantName('abc'));
14+
$this->assertSame('A_B_C', PhpCode::makePhpConstantName('a*b##c'));
15+
$this->assertSame('ABC', PhpCode::makePhpConstantName('_abc_'));
16+
$this->assertSame('ABC', PhpCode::makePhpConstantName('__abc__'));
17+
$this->assertSame('AB_C', PhpCode::makePhpConstantName('__AB__c__'));
18+
19+
// Keyword would be invalid.
20+
$this->assertSame('_AS', PhpCode::makePhpConstantName('as'));
21+
22+
// Leading numeric would be invalid.
23+
$this->assertSame('CONST_1_A', PhpCode::makePhpConstantName('1A'));
24+
25+
// Empty would be invalid.
26+
$this->assertSame('CONST_CFCD20', PhpCode::makePhpConstantName('0'));
27+
$this->assertSame('CONST_B14A7B', PhpCode::makePhpConstantName('_'));
28+
}
29+
1030
public function testFromCamelCase()
1131
{
1232
$this->assertSame('api_key', PhpCode::fromCamelCase('apiKey'));
@@ -18,4 +38,4 @@ public function testFromCamelCase()
1838
$this->assertSame('_x-', PhpCode::fromCamelCase('_x-'));
1939
}
2040

21-
}
41+
}

0 commit comments

Comments
 (0)