doctrine/inflector
is a small library which helps in uppercase/lowercase
and singular/plural
based manipulation of a string.
Laravel uses this package in a class called Pluralizer
as shown below:
<?php
namespace Illuminate\Support;
use Doctrine\Inflector\CachedWordInflector;
use Doctrine\Inflector\Inflector;
use Doctrine\Inflector\Rules\English;
use Doctrine\Inflector\RulesetInflector;
class Pluralizer
{
/**
* Get the plural form of an English word.
*
* @param string $value
* @param int $count
* @return string
*/
public static function plural($value, $count = 2)
{
if ((int) abs($count) === 1 || static::uncountable($value) || preg_match('/^(.*)[A-Za-z0-9\x{0080}-\x{FFFF}]$/u', $value) == 0) {
return $value;
}
$plural = static::inflector()->pluralize($value);
return static::matchCase($plural, $value);
}
/**
* Get the singular form of an English word.
*
* @param string $value
* @return string
*/
public static function singular($value)
{
$singular = static::inflector()->singularize($value);
return static::matchCase($singular, $value);
}
}
Full source code can be found here
Laravel then uses Pluralizer
class in Str
helper class. Str::singular()
and Str::plural()
helper methods leverage Pluralizer::singular()
and Pluralizer::plural()
respectively as shown below:
<?php
namespace Illuminate\Support;
use Illuminate\Support\Traits\Macroable;
class Str
{
use Macroable;
/**
* Get the plural form of an English word.
*
* @param string $value
* @param int $count
* @return string
*/
public static function plural($value, $count = 2)
{
return Pluralizer::plural($value, $count);
}
/**
* Get the singular form of an English word.
*
* @param string $value
* @return string
*/
public static function singular($value)
{
return Pluralizer::singular($value);
}
}
Full source code can be found here
How Laravel deals with Uncountables?
If we look at the implementation of Pluralizer
class, we can see that Laravel maintains an array of uncountables like education, audio, jedi etc. If you provide such value to Str::plural()
helper method, it will be returned as it is.
I hope you find this blogpost useful. Next up we'll see how Laravel uses dragonmantank/cron-expression
package. Stay in the loop by following me on Twitter