1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Sirius\Orm\CodeGenerator\Observer\Relation; |
5
|
|
|
|
6
|
|
|
use Nette\PhpGenerator\ClassType; |
7
|
|
|
use Sirius\Orm\Blueprint\Mapper; |
8
|
|
|
use Sirius\Orm\Contract\Relation\ToManyInterface; |
9
|
|
|
use Sirius\Orm\Helpers\Str; |
10
|
|
|
use Sirius\Orm\MapperConfig; |
11
|
|
|
|
12
|
|
|
class ManyToManyObserver extends OneToManyObserver implements ToManyInterface |
13
|
|
|
{ |
14
|
|
|
public function observe(string $key, $object) |
15
|
|
|
{ |
16
|
|
|
if ($key === $this->relation->getForeignMapper() . '_base_entity') { |
17
|
|
|
return $this->observeLinkedBaseEntity($object); |
18
|
|
|
} |
19
|
|
|
if ($key === $this->relation->getForeignMapper() . '_mapper_config') { |
20
|
|
|
return $this->observeLinkedMapperConfig($object); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
return parent::observe($key, $object); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
protected function observeLinkedBaseEntity(ClassType $class) |
27
|
|
|
{ |
28
|
|
|
$pivotColumns = $this->relation->getPivotColumns(); |
29
|
|
|
if (empty($pivotColumns)) { |
30
|
|
|
return $class; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
foreach ($pivotColumns as $column) { |
34
|
|
|
$comment = 'unsed only for relations with ' . $this->relation->getMapper()->getName(); |
35
|
|
|
if ($this->relation->getMapper()->getEntityStyle() === Mapper::ENTITY_STYLE_PROPERTIES) { |
36
|
|
|
$class->addComment(sprintf('@property mixed $%s - %s', $column, $comment)); |
37
|
|
|
} else { |
38
|
|
|
$setter = $class->addMethod(Str::methodName($column, 'set')); |
39
|
|
|
$setter->setVisibility(ClassType::VISIBILITY_PUBLIC); |
40
|
|
|
$setter->addParameter('value'); |
41
|
|
|
$setter->addBody('$this->set(\'' . $column . '\', $value);'); |
42
|
|
|
$setter->setComment($comment); |
43
|
|
|
|
44
|
|
|
$getter = $class->addMethod(Str::methodName($column, 'get')); |
45
|
|
|
$getter->setVisibility(ClassType::VISIBILITY_PUBLIC); |
46
|
|
|
$getter->addBody('return $this->get(\'' . $column . '\');'); |
47
|
|
|
$setter->setComment($comment); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $class; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
private function observeLinkedMapperConfig(array $config) |
55
|
|
|
{ |
56
|
|
|
$config[MapperConfig::PIVOT_ATTRIBUTES] = array_merge( |
57
|
|
|
$config[MapperConfig::PIVOT_ATTRIBUTES] ?? [], |
58
|
|
|
array_values($this->relation->getPivotColumns() ?? []) |
59
|
|
|
); |
60
|
|
|
|
61
|
|
|
return $config; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|