Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions doc/fields/NumberField.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ Basic Information
-----------------

* **PHP Class**: ``EasyCorp\Bundle\EasyAdminBundle\Field\NumberField``
* **Doctrine DBAL Type** used to store this value: ``decimal``, ``float`` or
``string``
* **Doctrine DBAL Type** used to store this value: ``decimal``, ``float``,
``string`` or ``number`` (``\BcMath\Number``, PHP 8.4+)
* **Symfony Form Type** used to render the field: `NumberType`_
* **Rendered as**:

Expand Down Expand Up @@ -71,6 +71,25 @@ constants of `PHP NumberFormatter class`_::

yield NumberField::new('...')->setRoundingMode(\NumberFormatter::ROUND_CEILING);

setStoredAsBcMathNumber
~~~~~~~~~~~~~~~~~~~~~~~

If your entity property uses ``\BcMath\Number`` (available in PHP 8.4+), use this
option to handle the conversion between the form input and the ``\BcMath\Number``
object automatically::

yield NumberField::new('...')->setStoredAsBcMathNumber();

This is useful when your Doctrine entity uses the ``number`` column type::

#[ORM\Column(type: Types::NUMBER, precision: 8, scale: 2, nullable: true)]
public ?\BcMath\Number $price = null;

.. caution::

This option requires PHP 8.4 or higher and cannot be combined with
``setStoredAsString()``.

setStoredAsString
~~~~~~~~~~~~~~~~~

Expand Down
3 changes: 3 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ parameters:
- '#Property EasyCorp\\Bundle\\EasyAdminBundle\\Twig\\EasyAdminTwigExtension::\$uxIconRuntime has unknown class Symfony\\UX\\Icons\\Twig\\UXIconRuntime as its type#'
- '#Parameter \$uxIconRuntime of method EasyCorp\\Bundle\\EasyAdminBundle\\Twig\\EasyAdminTwigExtension::__construct\(\) has invalid type Symfony\\UX\\Icons\\Twig\\UXIconRuntime#'
- '#Call to method renderIcon\(\) on an unknown class Symfony\\UX\\Icons\\Twig\\UXIconRuntime#'
- '#Class BcMath\\Number not found\.#'
- '#has invalid return type BcMath\\Number\.#'
- '#Instantiated class BcMath\\Number not found\.#'
-
identifier: missingType.generics
treatPhpDocTypesAsCertain: false
Expand Down
23 changes: 22 additions & 1 deletion src/Field/Configurator/NumberConfigurator.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,36 @@ public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $c
$scale = $field->getCustomOption(NumberField::OPTION_NUM_DECIMALS);
$roundingMode = $field->getCustomOption(NumberField::OPTION_ROUNDING_MODE);
$isStoredAsString = true === $field->getCustomOption(NumberField::OPTION_STORED_AS_STRING);
$isStoredAsBcMathNumber = true === $field->getCustomOption(NumberField::OPTION_STORED_AS_BCMATH_NUMBER);

$field->setFormTypeOptionIfNotSet('input', $isStoredAsString ? 'string' : 'number');
if ($isStoredAsString && $isStoredAsBcMathNumber) {
throw new \InvalidArgumentException(sprintf('The "%s" field cannot use both "setStoredAsString()" and "setStoredAsBcMathNumber()" options at the same time.', $field->getProperty()));
}

if ($isStoredAsBcMathNumber && \PHP_VERSION_ID < 80400) {
throw new \LogicException('The "setStoredAsBcMathNumber()" option requires PHP 8.4 or higher.');
}

$input = match (true) {
$isStoredAsString, $isStoredAsBcMathNumber => 'string',
default => 'number',
};
$field->setFormTypeOptionIfNotSet('input', $input);
$field->setFormTypeOptionIfNotSet('rounding_mode', $roundingMode);
$field->setFormTypeOptionIfNotSet('scale', $scale);

if ($isStoredAsBcMathNumber) {
$field->setFormTypeOption('ea_bcmath_number', true);
}

if (null === $value = $field->getValue()) {
return;
}

if ($isStoredAsBcMathNumber) {
$value = (float) (string) $value;
}

$formatterAttributes = ['rounding_mode' => $this->getRoundingModeAsString($roundingMode)];
if (null !== $scale) {
$formatterAttributes['fraction_digit'] = $scale;
Expand Down
17 changes: 15 additions & 2 deletions src/Field/NumberField.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace EasyCorp\Bundle\EasyAdminBundle\Field;

use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldInterface;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use EasyCorp\Bundle\EasyAdminBundle\Form\Type\EaNumberType;
use Symfony\Contracts\Translation\TranslatableInterface;

/**
Expand All @@ -16,6 +16,7 @@ final class NumberField implements FieldInterface
public const OPTION_NUM_DECIMALS = 'numDecimals';
public const OPTION_ROUNDING_MODE = 'roundingMode';
public const OPTION_STORED_AS_STRING = 'storedAsString';
public const OPTION_STORED_AS_BCMATH_NUMBER = 'storedAsBcMathNumber';
public const OPTION_NUMBER_FORMAT = 'numberFormat';
public const OPTION_THOUSANDS_SEPARATOR = 'thousandsSeparator';
public const OPTION_DECIMAL_SEPARATOR = 'decimalSeparator';
Expand All @@ -26,12 +27,13 @@ public static function new(string $propertyName, TranslatableInterface|string|bo
->setProperty($propertyName)
->setLabel($label)
->setTemplateName('crud/field/number')
->setFormType(NumberType::class)
->setFormType(EaNumberType::class)
->addCssClass('field-number')
->setDefaultColumns('col-md-4 col-xxl-3')
->setCustomOption(self::OPTION_NUM_DECIMALS, null)
->setCustomOption(self::OPTION_ROUNDING_MODE, \NumberFormatter::ROUND_HALFUP)
->setCustomOption(self::OPTION_STORED_AS_STRING, false)
->setCustomOption(self::OPTION_STORED_AS_BCMATH_NUMBER, false)
->setCustomOption(self::OPTION_NUMBER_FORMAT, null)
->setCustomOption(self::OPTION_THOUSANDS_SEPARATOR, null)
->setCustomOption(self::OPTION_DECIMAL_SEPARATOR, null);
Expand Down Expand Up @@ -76,6 +78,17 @@ public function setStoredAsString(bool $asString = true): self
return $this;
}

/**
* If true, the field value is stored as a \BcMath\Number instance (requires PHP 8.4+).
* This cannot be combined with setStoredAsString().
*/
public function setStoredAsBcMathNumber(bool $asBcMathNumber = true): self
{
$this->setCustomOption(self::OPTION_STORED_AS_BCMATH_NUMBER, $asBcMathNumber);

return $this;
}

// If set, all the other formatting options are ignored. This format is passed
// directly to the first argument of `sprintf()` to format the number before displaying it
public function setNumberFormat(string $sprintfFormat): self
Expand Down
33 changes: 33 additions & 0 deletions src/Form/DataTransformer/StringToBcMathNumberTransformer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;

/**
* Transforms between \BcMath\Number objects and string values.
*/
class StringToBcMathNumberTransformer implements DataTransformerInterface
{
public function transform(mixed $value): ?string
{
if (null === $value) {
return null;
}

if (!$value instanceof \BcMath\Number) {
throw new \InvalidArgumentException(sprintf('Expected an instance of "%s", got "%s".', \BcMath\Number::class, get_debug_type($value)));
}

return (string) $value;
}

public function reverseTransform(mixed $value): ?\BcMath\Number
{
if (null === $value || '' === $value) {
return null;
}

return new \BcMath\Number($value);
}
}
36 changes: 36 additions & 0 deletions src/Form/Type/EaNumberType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Form\Type;

use EasyCorp\Bundle\EasyAdminBundle\Form\DataTransformer\StringToBcMathNumberTransformer;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
* Extends NumberType to support \BcMath\Number objects via a data transformer.
*/
class EaNumberType extends NumberType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
parent::buildForm($builder, $options);

if (true === $options['ea_bcmath_number']) {
$builder->addModelTransformer(new StringToBcMathNumberTransformer());
}
}

public function configureOptions(OptionsResolver $resolver): void
{
parent::configureOptions($resolver);

$resolver->setDefault('ea_bcmath_number', false);
$resolver->setAllowedTypes('ea_bcmath_number', 'bool');
}

public function getBlockPrefix(): string
{
return 'number';
}
}
121 changes: 119 additions & 2 deletions tests/Unit/Field/NumberFieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

use EasyCorp\Bundle\EasyAdminBundle\Field\Configurator\NumberConfigurator;
use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
use EasyCorp\Bundle\EasyAdminBundle\Form\Type\EaNumberType;
use EasyCorp\Bundle\EasyAdminBundle\Intl\IntlFormatter;
use Symfony\Component\Form\Extension\Core\Type\NumberType;

class NumberFieldTest extends AbstractFieldTest
{
Expand All @@ -24,10 +24,11 @@ public function testDefaultOptions(): void
self::assertNull($fieldDto->getCustomOption(NumberField::OPTION_NUM_DECIMALS));
self::assertSame(\NumberFormatter::ROUND_HALFUP, $fieldDto->getCustomOption(NumberField::OPTION_ROUNDING_MODE));
self::assertFalse($fieldDto->getCustomOption(NumberField::OPTION_STORED_AS_STRING));
self::assertFalse($fieldDto->getCustomOption(NumberField::OPTION_STORED_AS_BCMATH_NUMBER));
self::assertNull($fieldDto->getCustomOption(NumberField::OPTION_NUMBER_FORMAT));
self::assertNull($fieldDto->getCustomOption(NumberField::OPTION_THOUSANDS_SEPARATOR));
self::assertNull($fieldDto->getCustomOption(NumberField::OPTION_DECIMAL_SEPARATOR));
self::assertSame(NumberType::class, $fieldDto->getFormType());
self::assertSame(EaNumberType::class, $fieldDto->getFormType());
self::assertStringContainsString('field-number', $fieldDto->getCssClass());
}

Expand Down Expand Up @@ -254,4 +255,120 @@ public function testFormattedValueWithSmallDecimal(): void

self::assertMatchesRegularExpression('/0[.,]00123/', $fieldDto->getFormattedValue());
}

public function testSetStoredAsBcMathNumber(): void
{
if (\PHP_VERSION_ID < 80400) {
$this->markTestSkipped('BcMath\Number requires PHP 8.4 or higher.');
}

$field = NumberField::new('foo');
$field->setStoredAsBcMathNumber();
$fieldDto = $this->configure($field);

self::assertTrue($fieldDto->getCustomOption(NumberField::OPTION_STORED_AS_BCMATH_NUMBER));
self::assertSame('string', $fieldDto->getFormTypeOption('input'));
self::assertTrue($fieldDto->getFormTypeOption('ea_bcmath_number'));
}

public function testSetStoredAsBcMathNumberFalse(): void
{
if (\PHP_VERSION_ID < 80400) {
$this->markTestSkipped('BcMath\Number requires PHP 8.4 or higher.');
}

$field = NumberField::new('foo');
$field->setStoredAsBcMathNumber(false);
$fieldDto = $this->configure($field);

self::assertFalse($fieldDto->getCustomOption(NumberField::OPTION_STORED_AS_BCMATH_NUMBER));
self::assertSame('number', $fieldDto->getFormTypeOption('input'));
}

public function testStoredAsBcMathNumberAndStoredAsStringThrowsException(): void
{
if (\PHP_VERSION_ID < 80400) {
$this->markTestSkipped('BcMath\Number requires PHP 8.4 or higher.');
}

$this->expectException(\InvalidArgumentException::class);

$field = NumberField::new('foo');
$field->setStoredAsString();
$field->setStoredAsBcMathNumber();
$this->configure($field);
}

public function testFieldWithBcMathNumberValue(): void
{
if (\PHP_VERSION_ID < 80400) {
$this->markTestSkipped('BcMath\Number requires PHP 8.4 or higher.');
}

$field = NumberField::new('foo');
$field->setValue(new \BcMath\Number('123.45'));
$field->setStoredAsBcMathNumber();
$field->setNumDecimals(2);
$fieldDto = $this->configure($field);

self::assertMatchesRegularExpression('/123[.,]45/', $fieldDto->getFormattedValue());
}

public function testFieldWithBcMathNumberNullValue(): void
{
if (\PHP_VERSION_ID < 80400) {
$this->markTestSkipped('BcMath\Number requires PHP 8.4 or higher.');
}

$field = NumberField::new('foo');
$field->setValue(null);
$field->setStoredAsBcMathNumber();
$fieldDto = $this->configure($field);

self::assertNull($fieldDto->getValue());
}

public function testBcMathNumberWithThousandsSeparator(): void
{
if (\PHP_VERSION_ID < 80400) {
$this->markTestSkipped('BcMath\Number requires PHP 8.4 or higher.');
}

$field = NumberField::new('foo');
$field->setValue(new \BcMath\Number('1234567.89'));
$field->setStoredAsBcMathNumber();
$field->setThousandsSeparator(' ');
$field->setNumDecimals(2);
$fieldDto = $this->configure($field);

self::assertStringContainsString('1 234 567', $fieldDto->getFormattedValue());
}

public function testBcMathNumberWithNumberFormat(): void
{
if (\PHP_VERSION_ID < 80400) {
$this->markTestSkipped('BcMath\Number requires PHP 8.4 or higher.');
}

$field = NumberField::new('foo');
$field->setValue(new \BcMath\Number('42.5'));
$field->setStoredAsBcMathNumber();
$field->setNumberFormat('%.3f');
$fieldDto = $this->configure($field);

self::assertSame('42.500', $fieldDto->getFormattedValue());
}

public function testStoredAsBcMathNumberRequiresPhp84(): void
{
if (\PHP_VERSION_ID >= 80400) {
$this->markTestSkipped('This test verifies that setStoredAsBcMathNumber() throws LogicException on PHP < 8.4 where BcMath\Number is not available.');
}

$this->expectException(\LogicException::class);

$field = NumberField::new('foo');
$field->setStoredAsBcMathNumber();
$this->configure($field);
}
}
Loading
Loading