Skip to content

Commit

Permalink
Merge pull request #34 from pelmered/feature/setup-laravel-pint
Browse files Browse the repository at this point in the history
Setup Laravel Pint
  • Loading branch information
pelmered authored May 11, 2024
2 parents ee404b3 + c244d43 commit 89a9296
Show file tree
Hide file tree
Showing 22 changed files with 164 additions and 117 deletions.
25 changes: 25 additions & 0 deletions .github/workflows/code-style.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: Code style

on:
push:
branches: [main]
pull_request:
branches: [main]

jobs:
phplint:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Get changed files
id: changed-files
uses: tj-actions/changed-files@v39

- name: Run Laravel Pint
uses: aglipanci/laravel-pint-action@latest
with:
verboseMode: true
testMode: true
configPath: ./pint.json
14 changes: 9 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@

# Filament Money Field
Money field powered by [Money PHP ](https://www.moneyphp.org/en/stable/).

Money field powered by [Money PHP](https://www.moneyphp.org/en/stable/).

This package gives much better localization support for money fields in Filament than most other packages, and especially the built-in money support on TextColumns and TextEntries. For example when it comes to currency symbols and decimal and thousands separators. Especially for more obscure currencies. This also includes an input field that handles localized formats.

Expand All @@ -23,7 +25,7 @@ This package would give "1 234,56 kr", while most other solutions probably would

- PHP 8.2 or higher
- Filament 3.0 or higher
- [PHP Internationalization extension (intl) ](https://www.php.net/manual/en/intro.intl.php)
- [PHP Internationalization extension (intl)](https://www.php.net/manual/en/intro.intl.php)
- The database column should be a integers with minor units (i.e. cents) and not a float (Floats should never be used for storing money).

## Key features
Expand All @@ -47,6 +49,7 @@ composer require pelmered/filament-money-field
## Configure your locale

### Set the default currency and locale

**Set the default options for currency and locale so that you don't have to set them for every field.**

**Option 1 (Recommended): Put the default options in your .env file.**
Expand All @@ -63,6 +66,7 @@ php artisan vendor:publish --provider="Pelmered\FilamentMoneyField\FilamentMoney
## Additional Configuration

### If you want to use the formatting mask on the `MoneyInput` component

**This will auto format the input field as you type.**

This is a bit experimental at the moment and is therefore disabled by default. Hopefully it will be improved in the future and enabled by default in the next major version. Please try it out and provide feedback.
Expand All @@ -78,7 +82,7 @@ If you want to use international currency codes istead of their symbols or local
MONEY_INTL_CURRENCY_SYMBOL=true // Defaults to false
```

### Placement of currency symbol/code on input fields.
### Placement of currency symbol/code on input fields

Possible options: `after`, `before`, `none`.

Expand Down Expand Up @@ -146,7 +150,7 @@ MoneyColumn::make('price')
->locale('sv_SE');
```

## Roadmap / Ideas for the future.
## Roadmap / Ideas for the future

Contact me or create an issue if you want something of this, or something else.
I appreciate if you could tell me a bit about your use case for that feature as well.
Expand All @@ -162,4 +166,4 @@ When you are submitting a PR, I appreciate if you:

- Add tests for your code. Not a strict requirement. Ask for guidance if you are unsure. I will try to help if I have time.
- Run the test suite and make sure it passes with `composer test`.
- Check the code with `composer phpstan`. It doesn't have to be 100 % clean, but if there is something there in your code it is good if you can address it before submitting.
- Check the code with `composer lint`. This will run both PHPStan and Pint. See if you can address any issues there before submitting.
7 changes: 5 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
"filament/filament": "^3.0",
"orchestra/testbench": "^8.8 || ^9.0",
"phpstan/phpstan": "^1.10",
"nunomaduro/collision": "^7.0 || ^8.0"
"nunomaduro/collision": "^7.0 || ^8.0",
"laravel/pint": "^1.15"
},
"extra": {
"laravel": {
Expand All @@ -45,6 +46,7 @@
},
"scripts": {
"phpstan": "vendor/bin/phpstan analyse src --level=8",
"pint": "vendor/bin/pint",
"post-autoload-dump": [
"@clear",
"@prepare"
Expand All @@ -58,7 +60,8 @@
"@php vendor/bin/testbench serve"
],
"lint": [
"@php vendor/bin/phpstan analyse"
"composer phpstan",
"composer pint"
],
"test": [
"@php vendor/bin/testbench package:test"
Expand Down
3 changes: 2 additions & 1 deletion config/filament-money-field.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@
|---------------------------------------------------------------------------
|
| Where the dunit should be on form fields. Options are 'before' (prefix), 'after' (suffix) or 'none'.
| Note: In most non-English speaking European countries, the currency symbol is after the amount and is preceded by a space (as in "10 €")
| Note: In most non-English speaking European countries,
| the currency symbol is after the amount and is preceded by a space (as in "10 €")
|
*/
'form_currency_symbol_placement' => env('MONEY_UNIT_PLACEMENT', 'before'),
Expand Down
11 changes: 11 additions & 0 deletions pint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"preset": "laravel",
"rules": {
"binary_operator_spaces": {
"default": "align_single_space_minimal",
"operators": {
"=>": "align_single_space_minimal"
}
}
}
}
3 changes: 2 additions & 1 deletion src/Exceptions/UnsupportedCurrency.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Pelmered\FilamentMoneyField\Exceptions;

use RuntimeException;
Expand All @@ -7,6 +8,6 @@ class UnsupportedCurrency extends RuntimeException
{
public function __construct(string $currencyCode)
{
parent::__construct('Currency not supported: ' . $currencyCode);
parent::__construct('Currency not supported: '.$currencyCode);
}
}
5 changes: 3 additions & 2 deletions src/FilamentMoneyFieldServiceProvider.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Pelmered\FilamentMoneyField;

use Spatie\LaravelPackageTools\Package;
Expand All @@ -11,13 +12,13 @@ class FilamentMoneyFieldServiceProvider extends PackageServiceProvider
public function configurePackage(Package $package): void
{
$package->name(static::$name)
->hasConfigFile();
->hasConfigFile();
}

public function boot(): void
{
$this->publishes([
__DIR__ . '/../config/filament-money-field.php' => config_path('filament-money-field.php'),
__DIR__.'/../config/filament-money-field.php' => config_path('filament-money-field.php'),
], 'config');
}
}
26 changes: 13 additions & 13 deletions src/Forms/Components/MoneyInput.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ class MoneyInput extends TextInput
{
use HasMoneyAttributes;


protected function setUp(): void
{
parent::setUp();
Expand All @@ -26,12 +25,12 @@ protected function setUp(): void
$this->prepare();

$currency = $component->getCurrency();
$locale = $component->getLocale();
$locale = $component->getLocale();

if (is_null($state)) {
return null;
}
if (!is_numeric($state)) {
if (! is_numeric($state)) {
return $state;
}

Expand All @@ -40,9 +39,9 @@ protected function setUp(): void

$this->dehydrateStateUsing(function (MoneyInput $component, $state): ?string {
$currency = $component->getCurrency();
$state = MoneyFormatter::parseDecimal($state, $currency, $component->getLocale());
$state = MoneyFormatter::parseDecimal($state, $currency, $component->getLocale());

if (!is_numeric($state)) {
if (! is_numeric($state)) {
return null;
}

Expand Down Expand Up @@ -72,9 +71,9 @@ protected function prepare(): void
strtr(
'$money($input, \'\', \'{decimalSeparator}\', \'{groupingSeparator}\', {fractionDigits})',
[
'{decimalSeparator}' => $formattingRules->decimalSeparator,
'{decimalSeparator}' => $formattingRules->decimalSeparator,
'{groupingSeparator}' => $formattingRules->groupingSeparator,
'{fractionDigits}' => $formattingRules->fractionDigits,
'{fractionDigits}' => $formattingRules->fractionDigits,
]
)
);
Expand All @@ -85,23 +84,24 @@ protected function prepare(): void
public function minValue(mixed $value): static
{
$this->rule(new MinValueRule((int) $this->evaluate($value), $this));

return $this;
}

public function maxValue(mixed $value): static
{
$this->rule(new MaxValueRule((int) $this->evaluate($value), $this));

return $this;
}


public function getLabel(): string
{
return $this->evaluate($this->label)
?? (string)str($this->getName())
->afterLast('.')
->kebab()
->replace(['-', '_'], ' ')
->title();
?? (string) str($this->getName())
->afterLast('.')
->kebab()
->replace(['-', '_'], ' ')
->title();
}
}
3 changes: 2 additions & 1 deletion src/Forms/Rules/MaxValueRule.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Pelmered\FilamentMoneyField\Forms\Rules;

use Closure;
Expand Down Expand Up @@ -32,7 +33,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void
'The {attribute} must be less than or equal to {value}.',
[
'{attribute}' => Str::of($this->component->getLabel())->title(),
'{value}' => MoneyFormatter::formatAsDecimal($this->max, $currencyCode, $locale),
'{value}' => MoneyFormatter::formatAsDecimal($this->max, $currencyCode, $locale),
]
)
);
Expand Down
3 changes: 2 additions & 1 deletion src/Forms/Rules/MinValueRule.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Pelmered\FilamentMoneyField\Forms\Rules;

use Closure;
Expand Down Expand Up @@ -31,7 +32,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void
'The {attribute} must be at least {value}.',
[
'{attribute}' => ucwords($this->component->getLabel()),
'{value}' => MoneyFormatter::formatAsDecimal($this->min, $currencyCode, $locale),
'{value}' => MoneyFormatter::formatAsDecimal($this->min, $currencyCode, $locale),
]
)
);
Expand Down
8 changes: 5 additions & 3 deletions src/HasMoneyAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
trait HasMoneyAttributes
{
protected Currency $currency;

protected string $locale;

protected ?string $monetarySeparator = null;

public function getCurrency(): Currency
Expand All @@ -34,11 +36,11 @@ public function getLocale(): string
public function currency(string|Closure $currencyCode): static
{
/** @var non-empty-string $currencyCode */
$currencyCode = (string) $this->evaluate($currencyCode);
$currencyCode = (string) $this->evaluate($currencyCode);
$this->currency = new Currency($currencyCode);
$currencies = new ISOCurrencies();
$currencies = new ISOCurrencies();

if (!$currencies->contains($this->currency)) {
if (! $currencies->contains($this->currency)) {
throw new UnsupportedCurrency($currencyCode);
}

Expand Down
16 changes: 8 additions & 8 deletions src/MoneyFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
namespace Pelmered\FilamentMoneyField;

use Money\Currencies\ISOCurrencies;
use Money\Currency;
use Money\Exception\ParserException;
use Money\Formatter\IntlMoneyFormatter;
use Money\Parser\IntlLocalizedDecimalParser;
use Money\Money;
use Money\Currency;
use Money\Parser\IntlLocalizedDecimalParser;
use NumberFormatter;

class MoneyFormatter
Expand All @@ -18,14 +18,15 @@ public static function format(
string $locale,
int $outputStyle = NumberFormatter::CURRENCY
): string {
if ($value === '' || !is_numeric($value)) {
if ($value === '' || ! is_numeric($value)) {
return '';
}

$numberFormatter = self::getNumberFormatter($locale, $outputStyle);
$moneyFormatter = new IntlMoneyFormatter($numberFormatter, new ISOCurrencies());
$moneyFormatter = new IntlMoneyFormatter($numberFormatter, new ISOCurrencies());

$money = new Money((int) $value, $currency);

return $moneyFormatter->format($money); // outputs $1.000,00
}

Expand All @@ -40,15 +41,14 @@ public static function parseDecimal(?string $moneyString, Currency $currency, st
return '';
}

$currencies = new ISOCurrencies();
$numberFormatter = self::getNumberFormatter($locale, NumberFormatter::DECIMAL);
$moneyParser = new IntlLocalizedDecimalParser($numberFormatter, $currencies);
$moneyParser = new IntlLocalizedDecimalParser($numberFormatter, new ISOCurrencies());

// Needed to fix some parsing issues with small numbers such as
// "2,00" with "," left as thousands separator in the wrong place
// See: https://github.com/pelmered/filament-money-field/issues/20
$formattingRules = self::getFormattingRules($locale);
$moneyString = str_replace($formattingRules->groupingSeparator, '', $moneyString);
$moneyString = str_replace($formattingRules->groupingSeparator, '', $moneyString);

try {
return $moneyParser->parse($moneyString, $currency)->getAmount();
Expand All @@ -59,7 +59,7 @@ public static function parseDecimal(?string $moneyString, Currency $currency, st

public static function getFormattingRules(string $locale): MoneyFormattingRules
{
$config = config('filament-money-field');
$config = config('filament-money-field');
$numberFormatter = new NumberFormatter($locale, NumberFormatter::CURRENCY);

return new MoneyFormattingRules(
Expand Down
1 change: 1 addition & 0 deletions src/MoneyFormattingRules.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Pelmered\FilamentMoneyField;

class MoneyFormattingRules
Expand Down
Loading

0 comments on commit 89a9296

Please sign in to comment.