Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add counted() to Inflector Helper #2296

Merged
merged 1 commit into from
Oct 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions system/Helpers/inflector_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,29 @@ function plural(string $string): string

//--------------------------------------------------------------------

if (! function_exists('counted'))
{
/**
* Counted
*
* Takes a number and a word to return the plural or not
* E.g. 0 cats, 1 cat, 2 cats, ...
*
* @param int $count Number of items
* @param string $string Input string
* @return string
*/
function counted(int $count, string $string): string
{
$result = "{$count} ";
$result .= $count === 1 ? singular($string) : plural($string);

return $result;
}
}

//--------------------------------------------------------------------

if (! function_exists('camelize'))
{
/**
Expand Down
23 changes: 23 additions & 0 deletions tests/system/Helpers/InflectorHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,29 @@ public function testPlural()

//--------------------------------------------------------------------

public function testCounted()
{
$triplets = [
[3, 'cat', '3 cats'],
[1, 'cat', '1 cat'],
[0, 'cat', '0 cats'],
[3, 'cats', '3 cats'],
[1, 'cats', '1 cat'],
[0, 'cats', '0 cats'],
[3, 'fish', '3 fish'],
[1, 'fish', '1 fish'],
[0, 'fish', '0 fish'],
];

foreach ($triplets as $triplet)
{
$result = counted($triplet[0], $triplet[1]);
$this->assertEquals($triplet[2], $result);
}
}

//--------------------------------------------------------------------

public function testCamelize()
{
$strings = [
Expand Down
11 changes: 11 additions & 0 deletions user_guide_src/source/helpers/inflector_helper.rst
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@ The following functions are available:

echo plural('dog'); // Prints 'dogs'

.. php:function:: counted($count, $string)

:param int $count: Number of items
:param string $string: Input string
:returns: A singular or plural phrase
:rtype: string

Changes a word and its count to a phrase. Example::

echo counted(3, 'dog'); // Prints '3 dogs'

.. php:function:: camelize($string)

:param string $string: Input string
Expand Down