@@ -14,6 +14,31 @@ public function __construct()
1414 parent ::__construct (self ::$ defaultName );
1515 }
1616
17+ public static function isForeignKeyColumn (\ReflectionProperty $ property ) : bool
18+ {
19+ if (!\str_contains ($ property ->getName (), '_ ' )) {
20+ return false ;
21+ }
22+
23+ $ type = $ property ->getType ();
24+
25+ if (!$ type instanceof \ReflectionNamedType || $ type ->isBuiltin ()) {
26+ return false ;
27+ }
28+
29+ $ typeReflection = new \ReflectionClass ($ type ->getName ());
30+
31+ return $ typeReflection ->isSubclassOf (\CoolBeans \Contract \PrimaryKey::class);
32+ }
33+
34+ public static function getForeignKeyFromName (string $ columnName ) : array
35+ {
36+ $ parts = \explode ('_ ' , $ property ->getName ());
37+ $ column = \array_pop ($ parts );
38+
39+ return [\implode ('_ ' , $ parts ), $ column ];
40+ }
41+
1742 public function generate (string $ source ) : string
1843 {
1944 $ beans = $ this ->getBeans ($ source );
@@ -499,8 +524,9 @@ private function validateBean(\ReflectionClass $bean) : void
499524
500525 private function getForeignKey (\ReflectionProperty $ property , \ReflectionClass $ bean ) : ?string
501526 {
502- $ type = $ property ->getType ();
503- \assert ($ type instanceof \ReflectionNamedType);
527+ if (!self ::isForeignKeyColumn ($ property )) {
528+ return null ;
529+ }
504530
505531 $ hasPrimaryKeyAttribute = self ::hasPrimaryKeyAttribute ($ bean );
506532 $ attributeColumns = $ hasPrimaryKeyAttribute
@@ -536,9 +562,8 @@ private function getForeignKey(\ReflectionProperty $property, \ReflectionClass $
536562
537563 $ table = $ foreignKey ->table ;
538564 $ column = $ foreignKey ->column ;
539- } elseif (\str_contains ($ property ->getName (), '_id ' )) {
540- $ table = \str_replace ('_id ' , '' , $ property ->getName ());
541- $ column = 'id ' ;
565+ } elseif (\str_contains ($ property ->getName (), '_ ' )) {
566+ [$ table , $ column ] = self ::getForeignKeyFromName ($ property ->getName ());
542567 } else {
543568 return null ;
544569 }
0 commit comments