Skip to content

Commit

Permalink
Add options param to toArray
Browse files Browse the repository at this point in the history
  • Loading branch information
nicksagona committed May 17, 2024
1 parent 50fe505 commit 7e7905e
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 6 deletions.
15 changes: 14 additions & 1 deletion src/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -564,16 +564,29 @@ public function count(): int
/**
* Method to get the field values as an array
*
* @param array $options
* @return array
*/
public function toArray(): array
public function toArray(array $options = []): array
{
$fieldValues = [];

foreach ($this->fieldsets as $fieldset) {
$fieldValues = array_merge($fieldValues, $fieldset->toArray());
}

if (!empty($options)) {
if (isset($options['exclude'])) {
if (!is_array($options['exclude'])) {
$options['exclude'] = [$options['exclude']];
}
$fieldValues = array_diff_key($fieldValues, array_flip($options['exclude']));
}
if (isset($options['filter'])) {
$fieldValues = array_filter($fieldValues, $options['filter']);
}
}

return $fieldValues;
}

Expand Down
5 changes: 3 additions & 2 deletions src/FormInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,10 @@ public function count(): int;
/**
* Get values
*
* @param array $options
* @return array
*/
public function toArray(): array;
public function toArray(array $options = []): array;

/**
* Method to iterate over object
Expand Down Expand Up @@ -116,4 +117,4 @@ public function offsetSet(mixed $offset, mixed $value): void;
*/
public function offsetUnset(mixed $offset): void;

}
}
21 changes: 18 additions & 3 deletions src/FormValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -506,11 +506,26 @@ public function count(): int
/**
* Get values
*
* @param array $options
* @return array
*/
public function toArray(): array
public function toArray(array $options = []): array
{
return $this->values;
$fieldValues = $this->values;

if (!empty($options)) {
if (isset($options['exclude'])) {
if (!is_array($options['exclude'])) {
$options['exclude'] = [$options['exclude']];
}
$fieldValues = array_diff_key($fieldValues, array_flip($options['exclude']));
}
if (isset($options['filter'])) {
$fieldValues = array_filter($fieldValues, $options['filter']);
}
}

return $fieldValues;
}

/**
Expand Down Expand Up @@ -560,4 +575,4 @@ public function __unset(string $name): void
}
}

}
}

0 comments on commit 7e7905e

Please sign in to comment.