Skip to content

Commit c9e4ebc

Browse files
committed
Normalize user action args
1 parent e117425 commit c9e4ebc

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/Model/UserAction.php

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use Atk4\Core\InitializerTrait;
1010
use Atk4\Core\TrackableTrait;
1111
use Atk4\Data\Exception;
12+
use Atk4\Data\Field;
1213
use Atk4\Data\Model;
1314

1415
/**
@@ -118,6 +119,46 @@ public function getActionForEntity(Model $entity): self
118119
throw new Exception('Action instance not found in model');
119120
}
120121

122+
/**
123+
* @param mixed $value
124+
*
125+
* @return mixed
126+
*/
127+
protected function normalizeArg(string $name, $value)
128+
{
129+
$argFieldSeed = $this->args[$name];
130+
if ($argFieldSeed instanceof Model) {
131+
return $value === null
132+
? null
133+
: $argFieldSeed::assertInstanceOf($value);
134+
}
135+
136+
$argField = new Field($argFieldSeed);
137+
138+
return $argField->normalize($value);
139+
}
140+
141+
/**
142+
* @param array<int|string, mixed> $args
143+
*
144+
* @return array<string, mixed>
145+
*/
146+
protected function normalizeArgs($args): array
147+
{
148+
$argsNames = array_keys($this->args);
149+
150+
$res = [];
151+
foreach ($args as $k => $v) {
152+
if (is_int($k)) {
153+
$k = $argsNames[$k];
154+
}
155+
156+
$res[$k] = $this->normalizeArg($k, $v);
157+
}
158+
159+
return $res;
160+
}
161+
121162
/**
122163
* Attempt to execute callback of the action.
123164
*
@@ -142,6 +183,7 @@ public function execute(...$args)
142183
try {
143184
$this->validateBeforeExecute();
144185

186+
$args = $this->normalizeArgs($args);
145187
if ($passOwner) {
146188
array_unshift($args, $this->_getOwner());
147189
}
@@ -215,6 +257,7 @@ public function preview(...$args)
215257
try {
216258
$this->validateBeforeExecute();
217259

260+
$args = $this->normalizeArgs($args);
218261
if ($passOwner) {
219262
array_unshift($args, $this->_getOwner());
220263
}

0 commit comments

Comments
 (0)