Giter Site home page Giter Site logo

pimlie / php-unit-conversion Goto Github PK

View Code? Open in Web Editor NEW
65.0 3.0 20.0 127 KB

A library providing full PSR-4 compatible unit conversions

License: MIT License

JavaScript 3.20% PHP 96.80%
php units conversion metric imperial united states customary international system

php-unit-conversion's Introduction

Php Unit Conversion

Build Status Coverage Status Latest Stable Version Total Downloads License

The php-unit-conversion/php-unit-conversion package provides full PSR-4 compatible unit conversion. Most other packages that are available for unit conversion are using string types to indicate unit types. In this package all unit types are classes.

We still need to add a lot more units and tests to make the package more usefull. If you want to help me with that, please check Contributing!

Basic Usage

use PhpUnitConversion\Unit\Mass;
$milliGram = new Mass\MilliGram(12);
$milliGram->getValue(); // 12
$milliGram->getSymbol(); // 'mg'

/* A format method is available that accepts two parameters:
 * @integer precision
 * @boolean add_symbol
 */
$milliGram->format(3, false); // 12.000

/* Units are set relative to the BASE_UNIT of the unit type
 * e.g. for Mass the base unit is gram's
 */
echo Mass::BASE_UNIT;
// PhpUnitConversion\Unit\Mass\Gram

/* Most units are linear related to the base unit by a fixed factor
 * For these units you can retrieve the factor by calling getFactor,
 * this can return false if no factor has been defined
 */
echo $milliGram->getFactor();
// 0.001

/* The base unit has no factor defined, this is because we use class constants
 * to define factors for SI prefixes and you can't extend/overwrite constants
 */
var_dump((new Mass\Gram(2))->getFactor());
// false

Unit Conversions

use PhpUnitConversion\Unit;
use PhpUnitConversion\Unit\Mass;

/* If you have an instantiated unit, you can convert to a new unit by calling the 
 * static `from` method on the unit you want to convert to 
 */
$grams = new Mass\Gram(21);
echo Mass\PennyWeight::from($grams)->format();
// 13.503 dwt

/* You can also call the `to` method on the unit object and pass the class name of 
 * the unit you want to convert to 
 */
$grams = new Mass\Gram(21);
$milliGram = $massUnit->to(Mass\MilliGram::class);
echo $milliGram->format(0);
// 21000 mg

/* or use an instantiated object, this will overwrite any existing value
 * due to php passing objects by reference there is no need for a left assignment this way 
 */
$grams = new Mass\Gram(21);
$kiloGram = new Mass\KiloGram;
$grams->to($kiloGram);
echo $kiloGram->format();
// 0.021 kg

/* but `to` also returns the object for left assignment
 */
$massUnit = new Mass\Gram(21);
$ounce = $massUnit->to(new Mass\Ounce);
echo $ounce->format();
// 0.741 oz

/* you can convert directly from a string which has a format of '<value><symbol>' 
 * by calling the static `from` method on the unit class
 */
$milliGrams = Unit::from('21 mg');
var_dump($milliGrams instanceof Mass\MilliGram::class)
// true

/* but if you already know which type of unit to expect, you can also call 
 * `from` directly on the unit type class. This could prevent errors when multiple units
 * exists with the same symbol
 */
$milliGrams = Mass::from('21 mg');
var_dump($milliGrams instanceof Mass\MilliGram::class)
// true

Find the nearest unit type

If you have a value and want to automatically convert it to the unit type which value is closest to 1, you can use the static nearest method. The nearest method should only be called on a Unit Type class.

use PhpUnitConversion\Unit\Mass;
$value = rand(0, 1E13);
$unit = Mass::nearest($value);
echo $unit->format();
// 3.471 long cwt

If you only want units from a specific measurement system, you can pass a System class name as second parameter

use PhpUnitConversion\System;
use PhpUnitConversion\Unit\Mass;

$gram = Mass\Gram(850);

/* Only Units from the Metric system */
$unit = Mass::nearest($value, System\Metric::class);
echo $unit->format();   
// 8.500 hg

/* Only Units from the USC / Imperial system */
$unit = Mass::nearest($value, System\USC::class);
echo $unit->format();   
// 1.874 lb

Storing values with their type

If you want to store values in e.g. a database, you often have to store two things: the value itself and the unit type. As all our Units have a TYPE constant defined, we can use this to add the type information to the value before storing it in the database. To retrieve this unit value you can invoke the class instance itself.

use PhpUnitConversion\Unit\Mass;
$kiloGrams = new Mass\KiloGrams(1);
echo $kiloGrams();
// 64001

The returned value is the result of first converting the value to the base value, then a shift left by 6 and add the TYPE constant.

You can use the static from method to convert to a base unit instance again:

use PhpUnitConversion\Unit;
$grams = Unit::from(64001);
echo get_class($grams);
// PhpUnitConversion\Unit\Mass\Gram

$kiloGrams = $grams->to(Unit\Mass\KiloGram::class);
echo $kiloGrams->format();
// 1 kg

Arithmetic Operators

/* You can add units of the same type by calling `add` method with one or more units as arguments
 * add always returns a new instance
 */
$grams = new Mass\Gram(580);
$addGrams = $massUnit->add(new Mass\KiloGram(0.4), new Mass\Gram(11));
echo $addGrams->format(0);
// 991 g

/* You can also substract units of the same type by calling `substract` method with one or more units
 * as arguments. substract always returns a new instance
 */
$grams = new Mass\Gram(580);
$subGrams = $massUnit->substract(new Mass\KiloGram(0.4), new Mass\Gram(11));
echo $subGrams->format(0);
// 169 g

/* When you try to add/substract units of different types an exception is thrown
 */
$grams = new Mass\Gram(580);
$addGrams = $massUnit->add(new Time\Second(60) );
// throws a PhpUnitConversion\Exception\UnsupportedUnitException

Adding custom units

use PhpUnitConversion\Map as UnitMap;

/* You can add custom units by calling the add method on UnitMap.
 * The first argument should be the path to a directory containing UnitTypes files with
 * the corresponding Unit files in a subfolder.
 * The second argument is the namespace that you use in your files
 */
UnitMap::add('YOUR_UNITS_DIR_OR_FILE', 'YOUR_UNITS_NAMESPACE');

/* If you only want add one unit to an existing unit type, add a third argument with the class name
 * of the unit type you want your unit to add to
 */
UnitMap::add('/path/to/TwoTableSpoons.php', '\\MyUnits', PhpUnitConversion\Unit\Volume::class);

Contributing

Please check Contributing for details.

php-unit-conversion's People

Contributors

cpave3 avatar eyaraws avatar jkrzefski avatar joshuabehrens avatar neilcrookes avatar pimlie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

php-unit-conversion's Issues

Enhancement: Multiply unit by numeric factor

E.g.

/* You can multiply a unit by calling `multiply` method with a float as an argument
 * add always returns a new instance
 */
$quantity = 7;
$unitWeight = new Mass\Gram(500);
$totalWeight = $unitWeight->multiply($quantity);
echo $totalWeight->format(0);
// 3500 g

Feet (height) units?

Am I missing something or there are no feet units for height?

Cheers

I'm dumb. It's foot lol

Mass base unit is not the SI unit

The SI unit for mass is kilogramm (kg) and not gramm (g).
For me it's okay that the package uses internally a different unit as base, but there should be an interface flagging units as SI if the base-unit isn't the SI unit.

Using UnitMap to add a unit HeadCount can't find unit

Hi im having a hard time figuring out why i get a not found.
I'm trying to add a Headcount.php unit within Amount unit type.
But i get this
Class 'PhpUnitConversion\Unit\Amount\HeadCount' not found

I'm using the UnitMap::add

UnitMap::add(
dirname(__DIR__, 2) .'/helpers/unitconversion/Fixtures/Amount/HeadCount.php',
 "PhpUnitConversion\\Unit",
\PhpUnitConversion\Unit\Amount::class
);

First parameter is the server path that's the correct path to my HeadCount.php
Second im not sure what to use
Third the class of the unit type I want to add it to

This is my HeadCount.php unit

 namespace PhpUnitConversion\Unit\Amount;
 use PhpUnitConversion\Unit\Amount;
 class HeadCount extends Amount
 {
   const FACTOR = 1;
  const SYMBOL = 'hc';
  const LABEL = 'head count';
}

Initlization:

$hd = new  \PhpUnitConversion\Unit\Amount\HeadCount(343);

I need to initilize it like above reason i have dynamic way of calling it

$convertFromClass = "\PhpUnitConversion\Unit\\". $type . "\\" .  $from;
$convertFrom = new $convertFromClass($formattedNumber);

Looking in Map.php source code the static load() adds it to self:$paths like this

"[["/var/www/vhost/biome/vendor/php-unit-conversion/php-unit-conversion/src/Unit/"
"PhpUnitConversion\Unit"
true
null]

["/var/www/vhost/biome/app/helpers/unitconversion/Fixtures/Amount/HeadCount.php"
"PhpUnitConversion\Unit"
true
"PhpUnitConversion\Unit\Amount"]]"

Any way to add in a new Unit type for Length

Would need to add my custom units of measure. Like TonneKilimeter and PassengerKilometer in Length.
How can I do thats outside the scope of the library?
Something similar to Adding custom units, but only adding units to already defined units.

Unit\Length conversion is giving wrong numbers

foot to meters for the number 136043.25 gives back 124397.9478 instead the correct answer is 41465.9826.

    $convertFromClass = "\PhpUnitConversion\Unit\Length\Foot';
$convertToClass = "\PhpUnitConversion\Unit\Length\Meter;
$convertFrom = new $convertFromClass($formatNumberToConvert);
$convertTo = new $convertToClass();

$convertedNum = $convertFrom->to($convertTo);
$convertValue = $convertedNum->format($precision, false); // debatable to use (float)
$convertNoPrecision = $convertedNum->getValue();
$convertSymbol = $convertedNum->getSymbol();
   echo $convertValue; // It's wrong number

It's not possible to add multiple single file units to the same unit-type

Right now it's not possible to add multiple single file units to the same unittype.

UnitMap::add('Unit1.php', '\\MyUnits', Length::class);
UnitMap::add('Unit2.php', '\\MyUnits', Length::class);

The problem is

self::$map = self::$map + $classes;

Instead of $array + $array it should use array_merge_recursive(). This will merge the arrays on the level they should get merged - the array of units in the unit-type.

Spelling error in Unit::substract method name

The English word is spelled subtract (without an s), not substract as the library uses it.
Of course simply renaming it to the correct spelling would be a BC, but the incorrect version could be kept as an alias with a @deprecated annotation.

Handling Pressure

Is there anything to handle units of measurement for air pressure? Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.