devshed-io/arithmatic

Chainable math methods in php

1.5.1 2021-11-10 13:23 UTC

This package is auto-updated.

Last update: 2024-12-10 20:30:59 UTC


README



Arithmatic

Tests Latest Release License Total Downloads

Chainable math methods for PHP. Designed to make working with math more fluent and easier to read.

Installation (via Composer)

composer require devshed-io/arithmatic

Usage

Basic usage allows you to chain methods for better readability:

Arithmatic
    ::start(5)
    ->add(5)
    ->subtract(7);
    ->divide(2);
    ->multiply(7)
    ->output();

The when method will execute the given callback when the first argument given to the method evaluates to true:

Arithmatic
    ::start(10)
    ->when(true, fn (Arithmatic $calculation) => $calculation->subtract(5))->output();

When also provides a third method that will run when the conditional evaluates to false:

Arithmatic
    ::start(10)
    ->when(
        false,
        fn (Arithmatic $calculation) => $calculation->subtract(5),
        fn (Arithmatic $calculation) => $calculation->add(5), // This will run...
    )
    ->output();

Arithmatic also provides the underlying run API so you can chain methods with arrays:

Arithmatic
    ::make(10)
    ->run([
        'add' => 5,
        'divide' => 2,
        'round'
    ])
    ->output(); // 3

N.B. Unless you call output, arithmatic will provide an instance of itself. It can be coerced to a string using the __toString() or (string) methods.

Available Methods

  • percentageOf
  • percentageChange
  • divide
  • subtract
  • add
  • multiply
  • mean
  • round
  • clamp
  • clone

Testing (with Docker Compose)

docker-compose run --rm php vendor/bin/phpunit --testdox

License

MIT license