1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations; |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
use Illuminate\Support\Str; |
8
|
|
|
|
9
|
|
|
abstract class AssociationFactory |
10
|
|
|
{ |
11
|
|
|
public static $marshalPolymorphics = true; |
12
|
|
|
public static function getAssocationFromStubs(AssociationStubBase $stubOne, AssociationStubBase $stubTwo): Association |
13
|
|
|
{ |
14
|
|
|
$checkAssocation = self::checkAssocations($stubOne, $stubTwo); |
15
|
|
|
return null === $checkAssocation ? self::buildAssocationFromStubs($stubOne, $stubTwo) : $checkAssocation; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
private static function buildAssocationFromStubs(AssociationStubBase $stubOne, AssociationStubBase $stubTwo): Association |
19
|
|
|
{ |
20
|
|
|
$oneFirst = $stubOne->getKeyField()->getIsKeyField(); |
|
|
|
|
21
|
|
|
$twoFirst = $stubTwo->getKeyField()->getIsKeyField(); |
|
|
|
|
22
|
|
|
$first = -1 === $stubOne->compare($stubTwo); |
23
|
|
|
|
24
|
|
|
$association = new AssociationMonomorphic(); |
25
|
|
|
if($stubOne->getTargType() == null && self::$marshalPolymorphics){ |
26
|
|
|
$stubOne->addAssociation($association); |
27
|
|
|
$stubOne = self::marshalPolyToMono($stubOne, $stubTwo); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
$input = [intval(!$first) => $stubOne, intval($first) => $stubTwo]; |
31
|
|
|
$association->setFirst($input[0]); |
32
|
|
|
$association->setLast($input[1]); |
33
|
|
|
return $association; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
private static function marshalPolyToMono(AssociationStubBase $stub, AssociationStubBase $stubTwo): AssociationStubBase{ |
37
|
|
|
$stubNew = clone $stub; |
38
|
|
|
$relPolyTypeName = substr($stubTwo->getBaseType(), strrpos($stubTwo->getBaseType(), '\\')+1); |
39
|
|
|
$relPolyTypeName = Str::plural($relPolyTypeName, 1); |
40
|
|
|
$stubNew->setRelationName($stub->getRelationName() . '_' . $relPolyTypeName); |
41
|
|
|
$stubNew->setTargType($stubTwo->getBaseType()); |
42
|
|
|
$stubNew->setForeignFieldName($stubTwo->getKeyFieldName()); |
43
|
|
|
$entity = $stub->getEntity(); |
44
|
|
|
$stubs = $entity->getStubs(); |
45
|
|
|
|
46
|
|
|
$stubs[$stubNew->getRelationName()] = $stubNew; |
47
|
|
|
$entity->setStubs($stubs); |
48
|
|
|
return $stubNew; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
private static function checkAssocations(AssociationStubBase $stubOne, AssociationStubBase $stubTwo): ?Association{ |
52
|
|
|
$assocOne = $stubOne->getAssocations(); |
53
|
|
|
foreach($assocOne as $association){ |
54
|
|
|
$isFirst = $association->getFirst() === $stubOne; |
55
|
|
|
if($association->{$isFirst ? 'getLast' : 'getFirst'}() == $stubTwo){ |
56
|
|
|
return $association; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
return null; |
60
|
|
|
} |
61
|
|
|
} |