1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Cycle\Annotated\Utils; |
6
|
|
|
|
7
|
|
|
use Cycle\Annotated\Annotation\Entity; |
8
|
|
|
use Cycle\Annotated\Entities; |
9
|
|
|
use Doctrine\Inflector\Rules\English\InflectorFactory; |
10
|
|
|
use Spiral\Attributes\ReaderInterface; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @internal |
14
|
|
|
*/ |
15
|
|
|
class EntityUtils |
16
|
|
|
{ |
17
|
|
|
private \Doctrine\Inflector\Inflector $inflector; |
18
|
|
|
|
19
|
480 |
|
public function __construct(private ReaderInterface $reader) |
20
|
|
|
{ |
21
|
480 |
|
$this->inflector = (new InflectorFactory())->build(); |
22
|
480 |
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param class-string $class |
|
|
|
|
26
|
|
|
*/ |
27
|
468 |
|
public function hasParent(string $class, bool $root = true): bool |
28
|
|
|
{ |
29
|
468 |
|
return $this->findParent($class, $root) !== null; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param class-string $class |
|
|
|
|
34
|
|
|
* |
35
|
|
|
* @return class-string|null |
|
|
|
|
36
|
|
|
*/ |
37
|
468 |
|
public function findParent(string $class, bool $root = true): ?string |
38
|
|
|
{ |
39
|
|
|
/** @var class-string[] $parents */ |
40
|
468 |
|
$parents = class_parents($class); |
41
|
|
|
|
42
|
468 |
|
$parents = $root ? array_reverse($parents) : $parents; |
43
|
|
|
|
44
|
468 |
|
foreach ($parents as $parent) { |
45
|
|
|
try { |
46
|
308 |
|
$class = new \ReflectionClass($parent); |
47
|
|
|
} catch (\ReflectionException) { |
48
|
|
|
continue; |
49
|
|
|
} |
50
|
|
|
|
51
|
308 |
|
if ($class->getDocComment() === false) { |
52
|
|
|
continue; |
53
|
|
|
} |
54
|
|
|
|
55
|
308 |
|
$ann = $this->reader->firstClassMetadata($class, Entity::class); |
56
|
308 |
|
if ($ann !== null) { |
57
|
308 |
|
return $parent; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
468 |
|
return null; |
62
|
|
|
} |
63
|
|
|
|
64
|
468 |
|
public function tableName(string $role, int $namingStrategy = Entities::TABLE_NAMING_PLURAL): string |
65
|
|
|
{ |
66
|
468 |
|
return match ($namingStrategy) { |
67
|
450 |
|
Entities::TABLE_NAMING_PLURAL => $this->inflector->pluralize($this->inflector->tableize($role)), |
68
|
|
|
Entities::TABLE_NAMING_SINGULAR => $this->inflector->singularize($this->inflector->tableize($role)), |
69
|
468 |
|
default => $this->inflector->tableize($role), |
70
|
|
|
}; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|