Commit b602e3cf by Qiang Xue

Merge pull request #4166 from schmunk42/master

fixed inflector camel2id and id2camel
parents 9c4d4715 b96be063
...@@ -326,14 +326,16 @@ class BaseInflector ...@@ -326,14 +326,16 @@ class BaseInflector
* For example, 'PostTag' will be converted to 'post-tag'. * For example, 'PostTag' will be converted to 'post-tag'.
* @param string $name the string to be converted * @param string $name the string to be converted
* @param string $separator the character used to concatenate the words in the ID * @param string $separator the character used to concatenate the words in the ID
* @param string $strict whether to insert a separator between two consecutive uppercase chars, defaults to false
* @return string the resulting ID * @return string the resulting ID
*/ */
public static function camel2id($name, $separator = '-') public static function camel2id($name, $separator = '-', $strict = false)
{ {
$regex = $strict ? '/[A-Z]/' : '/(?<![A-Z])[A-Z]/';
if ($separator === '_') { if ($separator === '_') {
return trim(strtolower(preg_replace('/(?<![A-Z])[A-Z]/', '_\0', $name)), '_'); return trim(strtolower(preg_replace($regex, '_\0', $name)), '_');
} else { } else {
return trim(strtolower(str_replace('_', $separator, preg_replace('/(?<![A-Z])[A-Z]/', $separator . '\0', $name))), $separator); return trim(strtolower(str_replace('_', $separator, preg_replace($regex, $separator . '\0', $name))), $separator);
} }
} }
......
...@@ -95,6 +95,12 @@ class InflectorTest extends TestCase ...@@ -95,6 +95,12 @@ class InflectorTest extends TestCase
$this->assertEquals('post-tag', Inflector::camel2id('postTag')); $this->assertEquals('post-tag', Inflector::camel2id('postTag'));
$this->assertEquals('post_tag', Inflector::camel2id('postTag', '_')); $this->assertEquals('post_tag', Inflector::camel2id('postTag', '_'));
$this->assertEquals('foo-ybar', Inflector::camel2id('FooYBar', '-', false));
$this->assertEquals('foo_ybar', Inflector::camel2id('fooYBar', '_', false));
$this->assertEquals('foo-y-bar', Inflector::camel2id('FooYBar', '-', true));
$this->assertEquals('foo_y_bar', Inflector::camel2id('fooYBar', '_', true));
} }
public function testId2camel() public function testId2camel()
...@@ -104,6 +110,9 @@ class InflectorTest extends TestCase ...@@ -104,6 +110,9 @@ class InflectorTest extends TestCase
$this->assertEquals('PostTag', Inflector::id2camel('post-tag')); $this->assertEquals('PostTag', Inflector::id2camel('post-tag'));
$this->assertEquals('PostTag', Inflector::id2camel('post_tag', '_')); $this->assertEquals('PostTag', Inflector::id2camel('post_tag', '_'));
$this->assertEquals('FooYBar', Inflector::id2camel('foo-y-bar'));
$this->assertEquals('FooYBar', Inflector::id2camel('foo_y_bar', '_'));
} }
public function testHumanize() public function testHumanize()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment