|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Statix\FormAction\Concerns; |
| 4 | + |
| 5 | +use Statix\FormAction\Attributes\Computed; |
| 6 | +use Statix\FormAction\FormAction; |
| 7 | +use Statix\FormAction\Inspector; |
| 8 | + |
| 9 | +trait SupportsComputedAttributeFeatures |
| 10 | +{ |
| 11 | + protected $supportComputedProperties = true; |
| 12 | + |
| 13 | + public function dontSupportComputedProperties(): static |
| 14 | + { |
| 15 | + $this->supportComputedProperties = false; |
| 16 | + |
| 17 | + return $this; |
| 18 | + } |
| 19 | + |
| 20 | + public function supportComputedProperties(): static |
| 21 | + { |
| 22 | + $this->supportComputedProperties = true; |
| 23 | + |
| 24 | + return $this; |
| 25 | + } |
| 26 | + |
| 27 | + public function bootSupportsComputedAttributeFeatures(): void |
| 28 | + { |
| 29 | + if (! $this->supportComputedProperties) { |
| 30 | + return; |
| 31 | + } |
| 32 | + |
| 33 | + // hook into the beforeAuthorization method |
| 34 | + /** @var FormAction $this */ |
| 35 | + $this->afterValidation(function (FormAction $action) { |
| 36 | + |
| 37 | + // get the inspector |
| 38 | + $inspector = Inspector::make($action); |
| 39 | + |
| 40 | + // get the public properties with the Computed attribute |
| 41 | + $publicProperties = $inspector->getPublicPropertiesWithAttribute(Computed::class); |
| 42 | + |
| 43 | + // loop through the public properties |
| 44 | + foreach ($publicProperties as $property) { |
| 45 | + |
| 46 | + // get the Computed attribute, it does not allow multiple so we can just get the first one |
| 47 | + |
| 48 | + /** @var ReflectionAttribute $computed */ |
| 49 | + $computed = $inspector->getPropertyAttributes($property, Computed::class)[0]; |
| 50 | + |
| 51 | + $result = $computed->newInstance()->getResult($action, $inspector->getPropertyName($property)); |
| 52 | + |
| 53 | + // TODO: need to check that the result of the computed attribute is of the correct type and passes validation |
| 54 | + $inspector->setPropertyValue($property, $result); |
| 55 | + |
| 56 | + } |
| 57 | + |
| 58 | + }); |
| 59 | + } |
| 60 | +} |
0 commit comments