Skip to content

Commit 2559680

Browse files
committed
refactor uess code
1 parent 3f9ecb8 commit 2559680

1 file changed

Lines changed: 23 additions & 13 deletions

File tree

src/Filterer.php

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,7 @@ public function execute(array $input) : FilterResponse
142142
unset($filters[FilterOptions::IS_REQUIRED]);//doesn't matter if required since we have this one
143143
unset($filters[FilterOptions::DEFAULT_VALUE]);//doesn't matter if there is a default since we have a value
144144
$conflicts = self::extractConflicts($filters, $field, $conflicts);
145-
146-
$uses = $filters[FilterOptions::USES] ?? [];
147-
unset($filters[FilterOptions::USES]);
145+
$uses = self::extractUses($filters);
148146

149147
foreach ($filters as $filter) {
150148
self::assertFilterIsNotArray($filter, $field);
@@ -160,16 +158,7 @@ public function execute(array $input) : FilterResponse
160158

161159
array_unshift($filter, $input);
162160
try {
163-
foreach ($uses as $usedField) {
164-
if (!array_key_exists($usedField, $filteredInput)) {
165-
throw new FilterException(
166-
"{$field} uses {$usedField} but {$usedField} was not given."
167-
);
168-
}
169-
170-
array_push($filter, $filteredInput[$usedField]);
171-
}
172-
161+
$this->addUsedInputToFilter($uses, $filteredInput, $field, $filter);
173162
$input = call_user_func_array($function, $filter);
174163
} catch (Exception $exception) {
175164
$errors = self::handleCustomError($field, $input, $exception, $errors, $customError);
@@ -241,6 +230,13 @@ private static function handleConflicts(array $inputToFilter, array $conflicts,
241230
return $errors;
242231
}
243232

233+
private static function extractUses(&$filters)
234+
{
235+
$uses = $filters[FilterOptions::USES] ?? [];
236+
unset($filters[FilterOptions::USES]);
237+
return is_array($uses) ? $uses : [$uses];
238+
}
239+
244240
/**
245241
* @return array
246242
*
@@ -669,4 +665,18 @@ private static function generateFilterResponse(string $responseType, FilterRespo
669665

670666
throw new InvalidArgumentException(sprintf("'%s' was not a recognized value", FiltererOptions::RESPONSE_TYPE));
671667
}
668+
669+
private function addUsedInputToFilter(array $uses, array $filteredInput, string $field, array &$filter)
670+
{
671+
foreach ($uses as $usedField) {
672+
if (array_key_exists($usedField, $filteredInput)) {
673+
array_push($filter, $filteredInput[$usedField]);
674+
continue;
675+
}
676+
677+
throw new FilterException(
678+
"{$field} uses {$usedField} but {$usedField} was not given."
679+
);
680+
}
681+
}
672682
}

0 commit comments

Comments
 (0)