Skip to content

Commit 66b029e

Browse files
committed
Add counted() inflector
1 parent 38e686f commit 66b029e

3 files changed

Lines changed: 57 additions & 0 deletions

File tree

system/Helpers/inflector_helper.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,29 @@ function plural(string $string): string
165165

166166
//--------------------------------------------------------------------
167167

168+
if (! function_exists('counted'))
169+
{
170+
/**
171+
* Counted
172+
*
173+
* Takes a number and a word to return the plural or not
174+
* E.g. 0 cats, 1 cat, 2 cats, ...
175+
*
176+
* @param int $count Number of items
177+
* @param string $string Input string
178+
* @return string
179+
*/
180+
function counted(int $count, string $string): string
181+
{
182+
$result = "{$count} ";
183+
$result .= $count === 1 ? singular($string) : plural($string);
184+
185+
return $result;
186+
}
187+
}
188+
189+
//--------------------------------------------------------------------
190+
168191
if (! function_exists('camelize'))
169192
{
170193
/**

tests/system/Helpers/InflectorHelperTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,29 @@ public function testPlural()
9292

9393
//--------------------------------------------------------------------
9494

95+
public function testCounted()
96+
{
97+
$triplets = [
98+
[3, 'cat', '3 cats'],
99+
[1, 'cat', '1 cat'],
100+
[0, 'cat', '0 cats'],
101+
[3, 'cats', '3 cats'],
102+
[1, 'cats', '1 cat'],
103+
[0, 'cats', '0 cats'],
104+
[3, 'fish', '3 fish'],
105+
[1, 'fish', '1 fish'],
106+
[0, 'fish', '0 fish'],
107+
];
108+
109+
foreach ($triplets as $triplet)
110+
{
111+
$result = counted($triplet[0], $triplet[1]);
112+
$this->assertEquals($triplet[2], $result);
113+
}
114+
}
115+
116+
//--------------------------------------------------------------------
117+
95118
public function testCamelize()
96119
{
97120
$strings = [

user_guide_src/source/helpers/inflector_helper.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,17 @@ The following functions are available:
4444

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

47+
.. php:function:: counted($count, $string)
48+
49+
:param int $count: Number of items
50+
:param string $string: Input string
51+
:returns: A singular or plural phrase
52+
:rtype: string
53+
54+
Changes a word and its count to a phrase. Example::
55+
56+
echo counted(3, 'dog'); // Prints '3 dogs'
57+
4758
.. php:function:: camelize($string)
4859
4960
:param string $string: Input string

0 commit comments

Comments
 (0)