Repository navigation
Expand file tree
/
Copy pathPluralizer.php
More file actions
116 lines (95 loc) · 2.75 KB
/
Copy pathPluralizer.php
File metadata and controls
116 lines (95 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Stringable;
use Countable;
use Doctrine\Inflector\Inflector;
use Doctrine\Inflector\InflectorFactory;
use Doctrine\Inflector\Language;
class Pluralizer
{
/**
* Uncountable word forms.
*/
public static array $uncountable
= [
'recommended',
'related',
];
/**
* The language that should be used by the inflector.
*/
protected static string $language = Language::ENGLISH;
protected static ?Inflector $inflector = null;
/**
* Get the plural form of an English word.
*/
public static function plural(string $value, array|Countable|int $count = 2): string
{
if (is_countable($count)) {
$count = count($count);
}
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::getInflector()->pluralize($value);
return static::matchCase($plural, $value);
}
/**
* Get the singular form of an English word.
*/
public static function singular(string $value): string
{
$singular = static::getInflector()->singularize($value);
return static::matchCase($singular, $value);
}
public static function setInflector(?Inflector $inflector): void
{
static::$inflector = $inflector;
}
/**
* Get the inflector instance.
*/
public static function getInflector(): Inflector
{
if (is_null(static::$inflector)) {
static::$inflector = InflectorFactory::createForLanguage(static::$language)->build();
}
return static::$inflector;
}
public static function useLanguage(string $language): void
{
static::$language = $language;
static::$inflector = null;
}
/**
* Determine if the given value is uncountable.
*
* @param string $value
* @return bool
*/
protected static function uncountable($value)
{
return in_array(strtolower($value), static::$uncountable);
}
/**
* Attempt to match the case on two strings.
*/
protected static function matchCase(string $value, string $comparison): string
{
$functions = ['mb_strtolower', 'mb_strtoupper', 'ucfirst', 'ucwords'];
foreach ($functions as $function) {
if ($function($comparison) === $comparison) {
return $function($value);
}
}
return $value;
}
}