|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
|
|
4
|
|
|
namespace AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations; |
|
5
|
|
|
|
|
6
|
|
|
use Illuminate\Support\Str; |
|
7
|
|
|
|
|
8
|
|
|
abstract class AssociationFactory |
|
9
|
|
|
{ |
|
10
|
|
|
public static $marshalPolymorphics = true; |
|
11
|
|
|
public static function getAssocationFromStubs(AssociationStubBase $stubOne, AssociationStubBase $stubTwo): Association |
|
12
|
|
|
{ |
|
13
|
|
|
$checkAssocation = self::checkAssocations($stubOne, $stubTwo); |
|
14
|
|
|
return null === $checkAssocation ? self::buildAssocationFromStubs($stubOne, $stubTwo) : $checkAssocation; |
|
15
|
|
|
} |
|
16
|
|
|
|
|
17
|
|
|
private static function buildAssocationFromStubs(AssociationStubBase $stubOne, AssociationStubBase $stubTwo): Association |
|
18
|
|
|
{ |
|
19
|
|
|
$oneFirst = $stubOne->getKeyField()->getIsKeyField(); |
|
|
|
|
|
|
20
|
|
|
$twoFirst = $stubTwo->getKeyField()->getIsKeyField(); |
|
|
|
|
|
|
21
|
|
|
$first = -1 === $stubOne->compare($stubTwo); |
|
22
|
|
|
|
|
23
|
|
|
$association = new AssociationMonomorphic(); |
|
24
|
|
|
if ($stubOne->getTargType() == null && self::$marshalPolymorphics) { |
|
25
|
|
|
$stubOne->addAssociation($association); |
|
26
|
|
|
$stubOne = self::marshalPolyToMono($stubOne, $stubTwo); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
$input = [intval(!$first) => $stubOne, intval($first) => $stubTwo]; |
|
30
|
|
|
$association->setFirst($input[0]); |
|
31
|
|
|
$association->setLast($input[1]); |
|
32
|
|
|
return $association; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
private static function marshalPolyToMono(AssociationStubBase $stub, AssociationStubBase $stubTwo): AssociationStubBase |
|
36
|
|
|
{ |
|
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
|
|
|
{ |
|
53
|
|
|
$assocOne = $stubOne->getAssociations(); |
|
54
|
|
|
foreach ($assocOne as $association) { |
|
55
|
|
|
$isFirst = $association->getFirst() === $stubOne; |
|
56
|
|
|
if ($association->{$isFirst ? 'getLast' : 'getFirst'}() == $stubTwo) { |
|
57
|
|
|
return $association; |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
return null; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|