Cartalyst LLC.
Converter by Cartalyst
1
24
8
16
60

Introduction

A framework agnostic measurement conversion and formatting package featuring multiple types of measurements and currency conversion.

The package requires PHP 7.2.5+ and comes bundled with a Laravel 7 Facade and a Service Provider to simplify the optional framework integration and follows the FIG standard PSR-4 to ensure a high level of interoperability between shared PHP code and is fully unit-tested.

Have a read through the Installation Guide and on how to Integrate it with Laravel 7.

Convert and Format meters to centimeters
$value = Converter::from('length.m')->to('length.cm')->convert(200)->format();

>>> 20000 centimeters

Upgrade Guide

Please refer to the following guides to update your Converter installation to the 1.1 version.

Upgrading To 1.1 From 1.0

The main and only required change is on the configuration file where we:

  • Changed the base lenghts to use meters instead of kilometers
  • Added some more common units like mile, feet and inch.
  • Updated some units use abbreviations so it's more consistent with the International System of Units.

To update just you just need to run php artisan config:publish cartalyst/converter.

Note: If you have custom units, please create a backup of the app/config/packages/cartalyst/converter/config.php file before executing the command above.

Installation

The best and easiest way to install the Converter package is with Composer.

Preparation

Open your composer.json and add the following to the require array:

"cartalyst/converter": "^5.0"

Add the following lines after the require array on your composer.json file:

"repositories": [
    {
        "type": "composer",
        "url": "https://packages.cartalyst.com"
    }
]

Note: Make sure that after the required changes your composer.json file is valid by running composer validate.

Install the dependencies

Run Composer to install or update the new requirement.

php composer install

or

php composer update

Now you are able to require the vendor/autoload.php file to autoload the package.

Integration

Cartalyst packages are framework agnostic and as such can be integrated easily natively or with your favorite framework.

Laravel 7

The Converter package has optional support for Laravel 7 and it comes bundled with a Service Provider and a Facade for easy integration.

After installing the package, open your Laravel config file located at config/app.php and add the following lines.

In the $providers array add the following service provider for this package.

'Cartalyst\Converter\Laravel\ConverterServiceProvider',

In the $aliases array add the following facade for this package.

'Converter' => 'Cartalyst\Converter\Laravel\Facades\Converter',

Configuration

After installing, you can publish the package configuration file into your application by running the following command on your terminal:

php artisan vendor:publish

This will publish the config file to config/cartalyst.converter.php where you can modify the package configuration.

Native

Integrating the package outside of a framework is incredible easy, just follow the example below.

// Include the composer autoload file
require_once 'vendor/autoload.php';

// Import the necessary classes
use Cartalyst\Converter\Converter;
use Cartalyst\Converter\Exchangers\NativeExchanger;

// Require the converter config file
$config = require_once 'vendor/cartalyst/converter/src/config/config.php';

// Instantiate the converter and set the necessary configuration
$converter = new Converter(new NativeExchanger);
$converter->setMeasurements($config['measurements']);

The integration is done and you can now use all the available methods, here's an example:

// Convert meters to centimeters
$value = $converter->from('length.m')->to('length.cm')->convert(200)->format();

Usage

In this section we'll show you how to use the converter package.

Measurements

The measurements are the crucial part of the package

Get the measurements

This will return an array containing all the available measurements.

$measurements = Converter::getMeasurements();

Set the measurements

Setting new measurements is simple and easy, you just need to provide a multidimensional array.

You have two ways of setting measurements, runtime or through the config file.

Runtime
Converter::setMeasurements(array(

    'weight' => array(

        'kg' => array(
            'format' => '1,0.00 KG',
            'unit'   => '1.00',
        ),

        'g' => array(
            'format' => '(1,0.00 grams)',
            'unit'   => 1000.00,
        ),

        'lb' => array(
            'format' => '1,0.00 lb',
            'unit'   => 2.20462,
        ),

    ),

));
Config

Open the file located at app/config/packages/cartalyst/converter/config.php and add your new measurements.

Formatting

We have a robust way of formatting measurements, please read along

You can place any currency symbol or text at the beginning or end of the format.

The first character , in the case above represents the thousands separator, the second one represents the decimals separator, digits after the second separator represent the number of decimals you want to show.

If you want to have only a decimal separator, you have to override the first separator using an !

Ex. a value of 2000.5 with the format '0!0.00 KG' would output 2000.50 KG.

Format a unit

$value = Converter::to('weight.lb')->value(200000)->format();

>>> 200,000 lb

Custom Formatting

$value = Converter::to('weight.lb')->value(200000)->format('1,0.00 Pounds');

>>> 200,000.00 Pounds

Negative Formats

Negative numbers are formatted according to the regular format by default, if you need to override the format for negative values, just provide a 'negative' property that defines your negative format.

Example

'currency' => array(

    'usd' => array(
        'format'   => '$1,0.00',
        'negative' => '($1,0.00)'.
    ),

),

Convertions

We have a very simple way of converting a measurement to another.

Converting from a unit to another

$value = Converter::from('weight.g')->to('weight.lb')->convert(200000)->format();

>>> 441 lb

Retrieve a converted unit value

$value = Converter::from('weight.g')->to('weight.lb')->convert(200000)->getValue();

>>> 440.924

Currency

Currency conversion requires an exchanger to fetch currency rates from a third party.

Default Exchangers

By default the native exchanger is used, which will fall back to the regular config values, you can define these units under your config file, if no unit is defined, the exchanger defaults to 1.

We have built-in support for two exchangers out of the box.

Native Exchanger

It defaults to user defined measurements configurations

'measurements' => array(

    'currency' => array(

        'usd' => array(
            'format' => '$1,0.00',
            'unit'   => 1
        ),

        'eur' => array(
            'format' => '€1,0.00',
            'unit'   => 1.2
        ),

    ),
)

Note: If you're using Laravel 6, define the units on your config file.

OpenExchangeRates.org Exchanger

It utilizes illuminate/cache to cache the currency results for a configurable amount of time.

<?php

use Cartalyst\Converter\Converter;
use Cartalyst\Converter\Exchangers\OpenExchangeRatesExchanger;
use Illuminate\Cache\CacheManager;
use Illuminate\Filesystem\Filesystem;

// Setup the Illuminate cache
$cache = new CacheManager(app());

// Create the exchanger
$exchanger = new OpenExchangeRatesExchanger($cache);

// Set app id
$exchanger->setAppId('your_app_id');

// Set cache expiration duration in minutes
$exchanger->setExpires(60);

// Create a new converter instance
$converter = new Converter($exchanger);

// Convert a currency from USD to EUR
$value = $converter->from('currency.usd')->to('currency.eur')->convert(200)->format();

Note: If you're using Laravel 6, you only need to modify your config file and set your app_id and switch the default exchanger to openexchangerates and you're ready to go, just use the facade.

Custom Exchangers

You can create your own exchanger by creating a class that implements the Cartalyst\Converter\Exchangers\ExchangerInterface.

<?php

use Cartalyst\Converter\Exchangers\ExchangerInterface;

class CustomExchanger implements ExchangerInterface {

    /**
     * Return the exchange rate for the provided currency code.
     *
     * @param  string  $code
     * @return float
     */
    public function get($code)
    {
        // Your logic to retrieve the value based on the currency code
        return 1;
    }

}

To use your new exchanger simply pass it as a parameter to the Converter instance.

Note: If you're using Laravel 6, you can bind your new exchanger into the container as converter.{exchanger_name}.exchanger and switch the default exchanger on your config file to match your exchanger name, and simply use the facade.

You wont find fancy lifestyle graphics and marketing bravado here. Just cold... hard... code...

Code Well, Rock On!
Processing Payment...