| 1: | <?php |
| 2: | |
| 3: | declare(strict_types=1); |
| 4: | |
| 5: | namespace Atk4\Data\Reference; |
| 6: | |
| 7: | use Atk4\Data\Model; |
| 8: | use Atk4\Data\Persistence; |
| 9: | |
| 10: | class ContainsOne extends ContainsBase |
| 11: | { |
| 12: | #[\Override] |
| 13: | protected function getDefaultPersistence(Model $theirModel): Persistence |
| 14: | { |
| 15: | $ourModel = $this->getOurModelPassedToRefXxx(); |
| 16: | |
| 17: | return new Persistence\Array_([ |
| 18: | $this->tableAlias => $ourModel->isEntity() && $this->getOurFieldValue($ourModel) !== null ? [1 => $this->getOurFieldValue($ourModel)] : [], |
| 19: | ]); |
| 20: | } |
| 21: | |
| 22: | #[\Override] |
| 23: | public function ref(Model $ourModel, array $defaults = []): Model |
| 24: | { |
| 25: | $ourModel = $this->getOurModel($ourModel); |
| 26: | |
| 27: | $theirModel = $this->createTheirModel(array_merge($defaults, [ |
| 28: | 'containedInEntity' => $ourModel->isEntity() ? $ourModel : null, |
| 29: | 'table' => $this->tableAlias, |
| 30: | ])); |
| 31: | |
| 32: | foreach ([Model::HOOK_AFTER_SAVE, Model::HOOK_AFTER_DELETE] as $spot) { |
| 33: | $this->onHookToTheirModel($theirModel, $spot, function (Model $theirEntity) { |
| 34: | $ourModel = $this->getOurModel($theirEntity->containedInEntity); |
| 35: | $ourModel->assertIsEntity(); |
| 36: | |
| 37: | |
| 38: | $persistence = $theirEntity->getModel()->getPersistence(); |
| 39: | $row = $persistence->getRawDataByTable($theirEntity->getModel(), $this->tableAlias); |
| 40: | $row = $row ? array_shift($row) : null; |
| 41: | $ourModel->save([$this->getOurFieldName() => $row]); |
| 42: | }); |
| 43: | } |
| 44: | |
| 45: | if ($ourModel->isEntity()) { |
| 46: | $theirModelOrig = $theirModel; |
| 47: | $theirModel = $theirModel->tryLoadOne(); |
| 48: | |
| 49: | if ($theirModel === null) { |
| 50: | $theirModel = $theirModelOrig->createEntity(); |
| 51: | } |
| 52: | } |
| 53: | |
| 54: | return $theirModel; |
| 55: | } |
| 56: | } |
| 57: | |