Skip to content

Commit

Permalink
Added support for multiple character separators at string humanizer
Browse files Browse the repository at this point in the history
  • Loading branch information
drgomesp committed Oct 31, 2015
1 parent fe8f037 commit 9be5770
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 8 deletions.
6 changes: 6 additions & 0 deletions spec/Coduo/PHPHumanizer/StringSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace spec\Coduo\PHPHumanizer;

use Coduo\PHPHumanizer\String\Humanize;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

Expand All @@ -12,6 +13,11 @@ function it_humanize_string()
$this->humanize('news_count')->shouldReturn('News count');
}

function it_humanize_string_with_special_character()
{
$this->humanize('news-count', true, Humanize::SEPARATOR_DASH)->shouldReturn('News count');
}

function it_humanize_strings_without_capitalize()
{
$this->humanize('user', false)->shouldReturn('user');
Expand Down
4 changes: 2 additions & 2 deletions src/Coduo/PHPHumanizer/String.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@

class String
{
public static function humanize($text, $capitalize = true)
public static function humanize($text, $capitalize = true, $separator = Humanize::SEPARATOR_UNDERSCORE)
{
return (string) new Humanize($text, $capitalize);
return (string) new Humanize($text, $capitalize, $separator);
}

public static function truncate($text, $charactersCount, $append = '')
Expand Down
20 changes: 14 additions & 6 deletions src/Coduo/PHPHumanizer/String/Humanize.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

class Humanize
{
const SEPARATOR_DASH = '-';
const SEPARATOR_UNDERSCORE = '_';

/**
* @var array
*/
Expand All @@ -15,30 +18,35 @@ class Humanize
private $text;

/**
* @var bool
* @var boolean
*/
private $capitalize;

/**
* @var string
*/
private $separator;

/**
* @param $text
* @param bool $capitalize
* @param string $separator
*/
public function __construct($text, $capitalize = true)
public function __construct($text, $capitalize = true, $separator = self::SEPARATOR_UNDERSCORE)
{
$this->text = $text;
$this->capitalize = $capitalize;
$this->separator = $separator;
}

/**
* @internal param bool $capitalize
*
* @return string
*/
public function __toString()
{
$humanized = trim(mb_strtolower(preg_replace(array('/([A-Z])/', '/[_\s]+/'), array('_$1', ' '), $this->text)));
$humanized = trim(str_replace($this->forbiddenWords, '', $humanized));

$humanized = trim(strtolower(preg_replace(array('/([A-Z])/', "/[{$this->separator}\\s]+/"), array('_$1', ' '), $this->text)));
$humanized = trim(str_replace($this->forbiddenWords, "", $humanized));
return $this->capitalize ? ucfirst($humanized) : $humanized;
}
}

0 comments on commit 9be5770

Please sign in to comment.