Skip to content

Commit

Permalink
Add divisor option to the MoneyColumnType (#66)
Browse files Browse the repository at this point in the history
  • Loading branch information
maxmishyn authored Feb 14, 2024
1 parent e122b72 commit 5b19bb0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
19 changes: 19 additions & 0 deletions docs/src/reference/types/column/money.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,25 @@ $builder
;
```

### `divisor`

- **type**: `integer`
- **default**: `1`

If you need to divide your starting value by a number before rendering it to the user,
you can use the `divisor` option. For example if you need to show amounts as integer in order to avoid
rounding errors, you can transform values in cents automatically:

```php
$builder
->addColumn('price', MoneyColumnType::class, [
'divisor' => 100,
])
;
```

In this case, if the price field is set to 9950, then the value 99.5 will actually be rendered to the user.

### `use_intl_formatter`

- **type**: `bool`
Expand Down
10 changes: 9 additions & 1 deletion src/Column/Type/MoneyColumnType.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ public function buildValueView(ColumnValueView $view, ColumnInterface $column, a
$currency = $currency($view->parent->data);
}

if (1 !== $options['divisor']) {
$view->vars['value'] /= $options['divisor'];
}

$view->vars = array_merge($view->vars, [
'currency' => $currency,
]);
Expand All @@ -24,9 +28,13 @@ public function buildValueView(ColumnValueView $view, ColumnInterface $column, a
public function configureOptions(OptionsResolver $resolver): void
{
$resolver
->setRequired('currency')
->setRequired(['currency', 'divisor'])
->setAllowedTypes('currency', ['string', 'callable'])
->setAllowedTypes('divisor', 'int')
;
$resolver->setDefaults([
'divisor' => 1,
]);
}

public function getParent(): ?string
Expand Down

0 comments on commit 5b19bb0

Please sign in to comment.