dereuromark/cakephp-decimal

CakePHP plugin for decimal handling via value object. Provides DecimalType class.

Installs: 397

Dependents: 0

Suggesters: 0

Security: 0

Stars: 3

Watchers: 1

Forks: 0

Open Issues: 0

Type:cakephp-plugin

1.0.1 2020-12-14 02:03 UTC

This package is auto-updated.

Last update: 2023-02-06 21:03:50 UTC


README

CI Latest Stable Version codecov License Minimum PHP Version

This is an alternative to

  • the core Decimal type (using plain strings)

As value object you have a few advantages, especially on handling the values inside your business logic.

This branch is for use with CakePHP 4.2+. See version map for details.

Requirements

Installation

Require the plugin through Composer:

composer require dereuromark/cakephp-decimal

Usage

To enable this for all your decimal columns, use this in bootstrap:

Type::map('decimal', 'CakeDecimal\Database\Type\DecimalObjectType');

This will automatically replace the core behavior and map any incoming value to the value object on marshalling, and also convert your database values to it when reading.

If you just want to map certain fields, you need to use an alias for those.

Type::map('decimal_object', 'CakeDecimal\Database\Type\DecimalObjectType');

Then inside your Table classes set them explicitly inside _initializeSchema():

/**
 * @param \Cake\Database\Schema\TableSchemaInterface $schema
 *
 * @return \Cake\Database\Schema\TableSchemaInterface
 */
protected function _initializeSchema(TableSchemaInterface $schema): TableSchemaInterface {
    $schema->setColumnType('amount', 'decimal_object');
    ...

    return $schema;
}

For details on Decimal class, see Decimal value object documentation.

Configuration

You can configure the Type class in your bootstrap.

To enable auto trim:

Type::build('decimal')
    ->useAutoTrim();

To enable localization parsing:

Type::build('decimal')
    ->useLocaleParser();

Customization

You can extend the value object and use the same config as shown above to enable your custom Decimal VO extension class. Your extension can be more strict or less strict.