Repository navigation
Expand file tree
/
Copy pathPlural.php
More file actions
57 lines (49 loc) · 1.72 KB
/
Copy pathPlural.php
File metadata and controls
57 lines (49 loc) · 1.72 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
<?php
declare(strict_types=1);
namespace Respect\Data\Styles;
use function array_map;
use function explode;
use function implode;
use function preg_match;
use function preg_replace;
/**
* Default plural table style familiar from frameworks such as Rails, Kohana,
* Laravel, FuelPHP, etc:
*
* authors posts categories posts_categories
* -------- --------- ---------- ----------------
* id id id id
* name author_id name post_id
* title category_id
*
* Scope/method names stay PHP-conventional singular camelCase (`post`,
* `postCategory`); only the *table* name pluralizes. That makes `realName` the
* single point of difference from {@see Standard} — class resolution, foreign
* keys, and junction names are all singular/snake and inherited unchanged
* (`composed` is itself expressed through `realName`).
*/
final class Plural extends Standard
{
public function realName(string $name): string
{
$pieces = array_map($this->singularToPlural(...), explode('_', $this->realProperty($name)));
return implode('_', $pieces);
}
private function singularToPlural(string $name): string
{
return $this->applyFirstMatch($name, [
'/^(.+)y$/' => '$1ies',
'/^(.+)([^s])$/' => '$1$2s',
]);
}
/** @param array<string, string> $replacements */
private function applyFirstMatch(string $name, array $replacements): string
{
foreach ($replacements as $pattern => $replacement) {
if (preg_match($pattern, $name)) {
return (string) preg_replace($pattern, $replacement, $name);
}
}
return $name;
}
}