├── .coveralls.yml ├── .gitignore ├── src └── Samsara │ └── Newton │ ├── Units │ ├── Core │ │ ├── Alias.php │ │ ├── ScalarQuantity.php │ │ ├── ConstantQuantity.php │ │ └── VectorQuantity.php │ ├── Vector │ │ ├── VectorForce.php │ │ ├── VectorMomentum.php │ │ ├── VectorVelocity.php │ │ └── VectorAcceleration.php │ ├── Amount.php │ ├── Resistance.php │ ├── Capacitance.php │ ├── Illumination.php │ ├── Inductance.php │ ├── MagneticFlux.php │ ├── AbsorbedDose.php │ ├── LuminousFlux.php │ ├── PlaneAngle.php │ ├── SolidAngle.php │ ├── CatalyticActivity.php │ ├── MagneticFluxDensity.php │ ├── ConductanceElectric.php │ ├── Cycles.php │ ├── LuminousIntensity.php │ ├── AngluarVelocity.php │ ├── Acceleration.php │ ├── ConductanceThermal.php │ ├── AngluarAcceleration.php │ ├── Charge.php │ ├── Energy.php │ ├── PhysicsConstants │ │ ├── Planck.php │ │ └── Gravitation.php │ ├── Density.php │ ├── Current.php │ ├── Radioactivity.php │ ├── Force.php │ ├── Volume.php │ ├── Momentum.php │ ├── Voltage.php │ ├── Velocity.php │ ├── Mass.php │ ├── Frequency.php │ ├── Time.php │ ├── Power.php │ ├── Temperature.php │ ├── Pressure.php │ ├── Area.php │ └── Length.php │ ├── Core │ ├── PrefixContainer.php │ ├── SIPrefixes.php │ ├── Quantity.php │ └── UnitComposition.php │ └── Provider │ └── PhysicsProvider.php ├── .travis.yml ├── tests ├── bootstrap.php └── Samsara │ └── Newton │ ├── Units │ └── ConstantsTest.php │ ├── Core │ ├── QuantityTest.php │ └── UnitCompositionTest.php │ └── Provider │ └── PhysicsProviderTest.php ├── composer.json ├── phpunit.xml.dist ├── COPYRIGHT ├── CONTRIBUTING.md ├── CHANGELOG.md ├── README.md └── LICENSE /.coveralls.yml: -------------------------------------------------------------------------------- 1 | src_dir: . -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | composer.lock 2 | .idea 3 | vendor 4 | build -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Core/Alias.php: -------------------------------------------------------------------------------- 1 | =5.6.0", 9 | "ircmaxell/random-lib": "1.1.*", 10 | "samsara/fermat": "dev-dev" 11 | }, 12 | "require-dev": { 13 | "phpunit/phpunit": "4.8.*" 14 | }, 15 | "autoload": { 16 | "psr-0": { 17 | "Samsara\\": "src/" 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | > 7 | tests 8 | 9 | 10 | > 11 | tests/Samsara 12 | 13 | 14 | 15 | 16 | ./src 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Amount.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::MOLE; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::MOLE] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::AMOUNT); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Resistance.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::OHMS; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::OHMS] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::RESISTANCE); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Capacitance.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::FARAD; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::FARAD] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::CAPACITANCE); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Illumination.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::LUX; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::LUX] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::ILLUMINATION); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Inductance.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::HENRY; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::HENRY] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::INDUCTANCE); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/MagneticFlux.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::WEBER; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::WEBER] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::MAG_FLUX); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/AbsorbedDose.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::GRAY; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::GRAY] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::ABSORBED_DOSE); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/LuminousFlux.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::LUMEN; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::LUMEN] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::LUMINOUS_FLUX); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/PlaneAngle.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::RADIANS; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::RADIANS] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::PLANE_ANGLE); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/SolidAngle.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::STERADIAN; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::STERADIAN] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::SOLID_ANGLE); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/CatalyticActivity.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::KATAL; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::KATAL] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::CATALYTIC_ACTIVITY); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/MagneticFluxDensity.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::TESLA; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::TESLA] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::MAG_FLUX_DENSITY); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/ConductanceElectric.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::SIEMENS; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::SIEMENS] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::CONDUCTANCE_ELEC); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Cycles.php: -------------------------------------------------------------------------------- 1 | 1 15 | ]; 16 | 17 | protected $native = self::CYCLES; 18 | 19 | public function __construct($value, $unit = null) 20 | { 21 | $this->rates = [ 22 | $this->units[self::CYCLES] => '1', 23 | ]; 24 | 25 | parent::__construct($value, $unit); 26 | 27 | $this->setComposition(UnitComposition::CYCLES); 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/LuminousIntensity.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::CANDELA; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::CANDELA] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::LUMINOUS_INTENSITY); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Core/PrefixContainer.php: -------------------------------------------------------------------------------- 1 | scale = $scale; 18 | $this->prefixPos = $prefixPos; 19 | 20 | } 21 | 22 | public function makeUnitString($unit) 23 | { 24 | return SIPrefixes::getUnitPrefixString($this->prefixPos).$unit; 25 | } 26 | 27 | public function applyScaling(NumberInterface $value) 28 | { 29 | return $value->multiply($this->scale); 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/AngluarVelocity.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::RADIANS_PER_SECOND; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::RADIANS_PER_SECOND] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::ANGULAR_VELOCITY); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Acceleration.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::METERS_PER_SECOND_SQUARED; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::METERS_PER_SECOND_SQUARED] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::ACCELERATION); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/ConductanceThermal.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::WATT_PER_METER_KELVIN; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::WATT_PER_METER_KELVIN] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::CONDUCTANCE_THERM); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/AngluarAcceleration.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::RADIANS_PER_SECOND_SQUARED; 17 | 18 | public function __construct($value, $unit = null) 19 | { 20 | $this->rates = [ 21 | $this->units[self::RADIANS_PER_SECOND_SQUARED] => '1' 22 | ]; 23 | 24 | parent::__construct($value, $unit); 25 | 26 | $this->setComposition(UnitComposition::ANGULAR_ACCELERATION); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Charge.php: -------------------------------------------------------------------------------- 1 | 1, 15 | self::KILOCOULOMB => 2 16 | ]; 17 | 18 | protected $native = self::COULOMB; 19 | 20 | public function __construct($value, $unit = null) 21 | { 22 | $this->rates = [ 23 | $this->units[self::COULOMB] => '1', 24 | $this->units[self::KILOCOULOMB] => '1000' 25 | ]; 26 | 27 | parent::__construct($value, $unit); 28 | 29 | $this->setComposition(UnitComposition::CHARGE); 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Energy.php: -------------------------------------------------------------------------------- 1 | 1, 15 | self::KILOWATTHOUR => 2 16 | ]; 17 | 18 | protected $native = self::JOULE; 19 | 20 | public function __construct($value, $unit = null) 21 | { 22 | $this->rates = [ 23 | $this->units[self::JOULE] => '1', 24 | $this->units[self::KILOWATTHOUR] => '3600' 25 | ]; 26 | 27 | parent::__construct($value, $unit); 28 | 29 | $this->setComposition(UnitComposition::ENERGY); 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Core/ConstantQuantity.php: -------------------------------------------------------------------------------- 1 | 1 14 | ]; 15 | 16 | protected $native = self::PLANCK; 17 | 18 | public function __construct() 19 | { 20 | $this->rates = [ 21 | $this->units[self::PLANCK] => '1' 22 | ]; 23 | 24 | $value = '0.000000000000000000000000000000000662606957'; 25 | $unit = self::PLANCK; 26 | 27 | parent::__construct($value, $unit); 28 | 29 | $this->defineComposition([ 30 | 'length' => 2, 31 | 'mass' => 1, 32 | 'time' => -1 33 | ]); 34 | } 35 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Density.php: -------------------------------------------------------------------------------- 1 | 1, 16 | self::G_PER_CUBIC_CENTIMETER => 2 17 | ]; 18 | 19 | protected $native = self::KG_PER_CUBIC_METER; 20 | 21 | public function __construct($value, $unit = null) 22 | { 23 | $this->rates = [ 24 | $this->units[self::KG_PER_CUBIC_METER] => '1', 25 | $this->units[self::G_PER_CUBIC_CENTIMETER] => '0.001' 26 | ]; 27 | 28 | parent::__construct($value, $unit); 29 | 30 | $this->setComposition(UnitComposition::DENSITY); 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/PhysicsConstants/Gravitation.php: -------------------------------------------------------------------------------- 1 | 1 15 | ]; 16 | 17 | protected $native = self::GRAVITATION; 18 | 19 | public function __construct() 20 | { 21 | $this->rates = [ 22 | $this->units[self::GRAVITATION] => '1' 23 | ]; 24 | 25 | $value = '0.0000000000667384'; 26 | $unit = self::GRAVITATION; 27 | 28 | parent::__construct($value, $unit); 29 | 30 | $this->defineComposition([ 31 | 'length' => 3, 32 | 'mass' => -1, 33 | 'time' => -2 34 | ]); 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | This program provides a way to interact with physics units and equations 2 | within PHP using objects. 3 | Copyright (C) 2015 Jordan LeDoux 4 | 5 | This program is free software; you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation; either version 2 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License along 16 | with this program; if not, write to the Free Software Foundation, Inc., 17 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 18 | 19 | You may contact the original author of this project at: 20 | 21 | jordan.ledoux@gmail.com 22 | -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Current.php: -------------------------------------------------------------------------------- 1 | 1, 16 | self::KILOAMPERE => 2, 17 | self::MEGAAMPERE => 3 18 | ]; 19 | 20 | protected $native = self::AMPERE; 21 | 22 | public function __construct($value, $unit = null) 23 | { 24 | $this->rates = [ 25 | $this->units[self::AMPERE] => '1', 26 | $this->units[self::KILOAMPERE] => '1000', 27 | $this->units[self::MEGAAMPERE] => '1000000' 28 | ]; 29 | 30 | parent::__construct($value, $unit); 31 | 32 | $this->setComposition(UnitComposition::CURRENT); 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Radioactivity.php: -------------------------------------------------------------------------------- 1 | 1, 16 | self::CURIE => 2, 17 | self::RUTHERFORD => 3 18 | ]; 19 | 20 | protected $native = self::BECQUEREL; 21 | 22 | public function __construct($value, $unit = null) 23 | { 24 | $this->rates = [ 25 | $this->units[self::BECQUEREL] => '1', 26 | $this->units[self::CURIE] => '37000000000', 27 | $this->units[self::RUTHERFORD] => '1000000' 28 | ]; 29 | 30 | parent::__construct($value, $unit); 31 | 32 | $this->setComposition(UnitComposition::RADIOACTIVITY); 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Force.php: -------------------------------------------------------------------------------- 1 | 1, 17 | self::KILONEWTON => 2, 18 | self::MEGANEWTON => 3, 19 | self::GIGANEWTON => 4 20 | ]; 21 | 22 | protected $native = self::NEWTON; 23 | 24 | public function __construct($value, $unit = null) 25 | { 26 | $this->rates = [ 27 | $this->units[self::NEWTON] => '1', 28 | $this->units[self::KILONEWTON] => '1000', 29 | $this->units[self::MEGANEWTON] => '1000000', 30 | $this->units[self::GIGANEWTON] => '1000000000', 31 | ]; 32 | 33 | parent::__construct($value, $unit); 34 | 35 | $this->setComposition(UnitComposition::FORCE); 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Volume.php: -------------------------------------------------------------------------------- 1 | 1, 18 | self::CUBIC_KILOMETERS => 2, 19 | self::LITERS => 3, 20 | self::GALLONS => 4 21 | ]; 22 | 23 | protected $native = self::CUBIC_METERS; 24 | 25 | public function __construct($value, $unit = null) 26 | { 27 | $this->rates = [ 28 | $this->units[self::CUBIC_METERS] => '1', 29 | $this->units[self::CUBIC_KILOMETERS] => '1000000000', 30 | $this->units[self::LITERS] => '0.001', 31 | $this->units[self::GALLONS] => '0.00378541' 32 | ]; 33 | 34 | parent::__construct($value, $unit); 35 | 36 | $this->setComposition(UnitComposition::VOLUME); 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Momentum.php: -------------------------------------------------------------------------------- 1 | 1, 18 | self::KILONEWTON_SECONDS => 2, 19 | self::MEGANEWTON_SECONDS => 3, 20 | self::KG_METER_SECONDS => 1, // Same as Ns 21 | ]; 22 | 23 | protected $native = self::NEWTON_SECONDS; 24 | 25 | public function __construct($value, $unit = null) 26 | { 27 | $this->rates = [ 28 | $this->units[self::NEWTON_SECONDS] => '1', // Same as kg-m/s 29 | $this->units[self::KILONEWTON_SECONDS] => '1000', 30 | $this->units[self::MEGANEWTON_SECONDS] => '1000000' 31 | ]; 32 | 33 | parent::__construct($value, $unit); 34 | 35 | $this->setComposition(UnitComposition::MOMENTUM); 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Voltage.php: -------------------------------------------------------------------------------- 1 | 1, 18 | self::KILOVOLTS => 2, 19 | self::MEGAVOLTS => 3, 20 | self::GIGAVOLTS => 4, 21 | self::TERRAVOLTS => 5 22 | ]; 23 | 24 | protected $native = self::VOLTS; 25 | 26 | public function __construct($value, $unit = null) 27 | { 28 | $this->rates = [ 29 | $this->units[self::VOLTS] => '1', 30 | $this->units[self::KILOVOLTS] => '1000', 31 | $this->units[self::MEGAVOLTS] => '1000000', 32 | $this->units[self::GIGAVOLTS] => '1000000000', 33 | $this->units[self::TERRAVOLTS] => '1000000000000' 34 | ]; 35 | 36 | parent::__construct($value, $unit); 37 | 38 | $this->setComposition(UnitComposition::VOLTAGE); 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Velocity.php: -------------------------------------------------------------------------------- 1 | 1, 17 | self::KILOMETERS_PER_SECOND => 2, 18 | self::LIGHT_SPEED => 3, 19 | self::AU_PER_SECOND => 4 20 | ]; 21 | 22 | protected $native = self::METERS_PER_SECOND; 23 | 24 | public function __construct($value, $unit = null) 25 | { 26 | $this->rates = [ 27 | $this->units[self::METERS_PER_SECOND] => '1', 28 | $this->units[self::KILOMETERS_PER_SECOND] => '1000', 29 | $this->units[self::LIGHT_SPEED] => '299792458', 30 | $this->units[self::AU_PER_SECOND] => '149597870700' 31 | ]; 32 | 33 | parent::__construct($value, $unit); 34 | 35 | $this->setComposition(UnitComposition::VELOCITY); 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Mass.php: -------------------------------------------------------------------------------- 1 | 1, 20 | self::MILLIGRAM => 2, 21 | self::GRAM => 3, 22 | self::KILOGRAM => 4, 23 | self::METRIC_TON => 5 24 | ]; 25 | 26 | public function __construct($value, $unit = null) 27 | { 28 | $this->rates = [ 29 | $this->units[self::MICROGRAM] => '0.000000001', 30 | $this->units[self::MILLIGRAM] => '0.000001', 31 | $this->units[self::GRAM] => '0.001', 32 | $this->units[self::KILOGRAM] => '1', 33 | $this->units[self::METRIC_TON] => '1000' 34 | ]; 35 | 36 | parent::__construct($value, $unit); 37 | 38 | $this->setComposition(UnitComposition::MASS); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Frequency.php: -------------------------------------------------------------------------------- 1 | 1, 19 | self::KILOHERTZ => 2, 20 | self::MEGAHERTZ => 3, 21 | self::GIGAHERTZ => 4, 22 | self::TERAHERTZ => 5 23 | ]; 24 | 25 | protected $native = self::HERTZ; 26 | 27 | public function __construct($value, $unit = null) 28 | { 29 | $this->rates = [ 30 | $this->units[self::HERTZ] => '1', 31 | $this->units[self::KILOHERTZ] => '1000', 32 | $this->units[self::MEGAHERTZ] => '1000000', 33 | $this->units[self::GIGAHERTZ] => '1000000000', 34 | $this->units[self::TERAHERTZ] => '1000000000000' 35 | ]; 36 | 37 | parent::__construct($value, $unit); 38 | 39 | $this->setComposition(UnitComposition::FREQUENCY); 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Time.php: -------------------------------------------------------------------------------- 1 | 1, 22 | self::MINUTE => 2, 23 | self::HOUR => 3, 24 | self::DAY => 4, 25 | self::WEEK => 5, 26 | self::YEAR => 6, 27 | self::MILLISECOND => 7 28 | ]; 29 | 30 | public function __construct($value, $unit = null) 31 | { 32 | $this->rates = [ 33 | $this->units[self::MILLISECOND] => '0.001', 34 | $this->units[self::SECOND] => '1', 35 | $this->units[self::MINUTE] => '60', 36 | $this->units[self::HOUR] => '3600', 37 | $this->units[self::DAY] => '86400', 38 | $this->units[self::WEEK] => '604800', 39 | $this->units[self::YEAR] => '31556736' 40 | ]; 41 | 42 | parent::__construct($value, $unit); 43 | 44 | $this->setComposition(UnitComposition::TIME); 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Power.php: -------------------------------------------------------------------------------- 1 | 1, 20 | self::KILOWATT => 2, 21 | self::MEGAWATT => 3, 22 | self::GIGAWATT => 4, 23 | self::TERAWATT => 5, 24 | self::PETAWATT => 6, 25 | self::HORSEPOWER => 7 26 | ]; 27 | 28 | protected $native = self::WATT; 29 | 30 | public function __construct($value, $unit = null) 31 | { 32 | $this->rates = [ 33 | $this->units[self::WATT] => '1', 34 | $this->units[self::KILOWATT] => '1000', 35 | $this->units[self::MEGAWATT] => '1000000', 36 | $this->units[self::GIGAWATT] => '1000000000', 37 | $this->units[self::TERAWATT] => '1000000000000', 38 | $this->units[self::PETAWATT] => '1000000000000000', 39 | $this->units[self::HORSEPOWER] => '745.699872' 40 | ]; 41 | 42 | parent::__construct($value, $unit); 43 | 44 | $this->setComposition(UnitComposition::POWER); 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Temperature.php: -------------------------------------------------------------------------------- 1 | 1, 18 | self::CELSIUS => 2, 19 | self::FAHRENHEIT=> 3 20 | ]; 21 | 22 | protected $native = self::KELVIN; 23 | 24 | public function __construct($value, $unit = null) 25 | { 26 | $this->rates = [ 27 | $this->units[self::KELVIN] => '1', 28 | $this->units[self::CELSIUS] => [ 29 | 'to' => function(NumberInterface $value) { 30 | return $value->subtract('273.15'); 31 | }, 32 | 'from' => function(NumberInterface $value) { 33 | return $value->add('273.15'); 34 | } 35 | ], 36 | $this->units[self::FAHRENHEIT] => [ 37 | 'to' => function(NumberInterface $value) { 38 | return $value->multiply(9)->divide(5)->subtract('459.67'); 39 | }, 40 | 'from' => function(NumberInterface $value) { 41 | return $value->add('459.67')->multiply(5)->divide(9); 42 | } 43 | ] 44 | ]; 45 | 46 | parent::__construct($value, $unit); 47 | 48 | $this->setComposition(UnitComposition::TEMPERATURE); 49 | } 50 | 51 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Pressure.php: -------------------------------------------------------------------------------- 1 | 1, 23 | self::KILOPASCAL => 2, 24 | self::MEGAPASCAL => 3, 25 | self::GIGAPASCAL => 8, 26 | self::TERAPASCAL => 4, 27 | self::BAR => 5, 28 | self::TORR => 6, 29 | self::ATMOSPHERE => 7, 30 | self::PSI => 9 31 | ]; 32 | 33 | protected $native = self::PASCAL; 34 | 35 | public function __construct($value, $unit = null) 36 | { 37 | $this->rates = [ 38 | $this->units[self::PASCAL] => '1', 39 | $this->units[self::KILOPASCAL] => '1000', 40 | $this->units[self::MEGAPASCAL] => '1000000', 41 | $this->units[self::GIGAPASCAL] => '1000000000', 42 | $this->units[self::TERAPASCAL] => '1000000000000', 43 | $this->units[self::BAR] => '100000', 44 | $this->units[self::TORR] => '133.3224', 45 | $this->units[self::ATMOSPHERE] => '101325', 46 | $this->units[self::PSI] => '6894.8' 47 | ]; 48 | 49 | parent::__construct($value, $unit); 50 | 51 | $this->setComposition(UnitComposition::PRESSURE); 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Area.php: -------------------------------------------------------------------------------- 1 | 1, 25 | self::HECTARE => 2, 26 | self::SQUARE_KILOMETER => 3, 27 | self::SQUARE_INCH => 4, 28 | self::SQUARE_FEET => 5, 29 | self::SQUARE_YARD => 6, 30 | self::ACRE => 7, 31 | self::SQUARE_MILE => 8 32 | ]; 33 | 34 | public function __construct($value, $unit = null) 35 | { 36 | $this->rates = [ 37 | $this->units[self::SQUARE_METER] => '1', 38 | $this->units[self::HECTARE] => '100', 39 | $this->units[self::SQUARE_KILOMETER] => '1000000', 40 | $this->units[self::SQUARE_INCH] => '0.00064516', 41 | $this->units[self::SQUARE_FEET] => '0.09290304', 42 | $this->units[self::SQUARE_YARD] => '0.83612736', 43 | $this->units[self::ACRE] => '247.105', 44 | $this->units[self::SQUARE_MILE] => '2589988.110336' 45 | ]; 46 | 47 | parent::__construct($value, $unit); 48 | 49 | $this->setComposition(UnitComposition::AREA); 50 | } 51 | 52 | } -------------------------------------------------------------------------------- /tests/Samsara/Newton/Units/ConstantsTest.php: -------------------------------------------------------------------------------- 1 | assertInstanceOf( 13 | 'Samsara\\Newton\\Units\\PhysicsConstants\\Gravitation', 14 | $gravitation 15 | ); 16 | 17 | $this->assertEquals( 18 | '0.0000000000667384', 19 | $gravitation->getValue() 20 | ); 21 | 22 | $gravitation->preConvertedAdd(1); 23 | $gravitation->preConvertedMultiply(2); 24 | $gravitation->preConvertedDivide(10); 25 | $gravitation->preConvertedSubtract(1); 26 | $gravitation->add($gravitation); 27 | $gravitation->add($gravitation); 28 | $gravitation->subtract($gravitation); 29 | 30 | $this->assertEquals( 31 | '0.0000000000667384', 32 | $gravitation->getValue() 33 | ); 34 | 35 | $this->assertEquals( 36 | 'N (m/kg)^2', 37 | $gravitation->getUnit() 38 | ); 39 | } 40 | 41 | public function testPlanck() 42 | { 43 | $planck = new Planck(); 44 | 45 | $this->assertInstanceOf( 46 | 'Samsara\\Newton\\Units\\PhysicsConstants\\Planck', 47 | $planck 48 | ); 49 | 50 | $this->assertEquals( 51 | '0.000000000000000000000000000000000662606957', 52 | $planck->getValue() 53 | ); 54 | 55 | $planck->preConvertedAdd(1); 56 | $planck->preConvertedMultiply(2); 57 | $planck->preConvertedDivide(10); 58 | $planck->preConvertedSubtract(1); 59 | $planck->add($planck); 60 | $planck->add($planck); 61 | $planck->subtract($planck); 62 | 63 | $this->assertEquals( 64 | '0.000000000000000000000000000000000662606957', 65 | $planck->getValue() 66 | ); 67 | 68 | $this->assertEquals( 69 | 'm^2 kg/s', 70 | $planck->getUnit() 71 | ); 72 | } 73 | 74 | } -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | This document lays out the guidelines for contributing to this project. 4 | 5 | ## Reporting Bugs & Opening Issues 6 | 7 | Please adhere to these guidelines when reporting bugs: 8 | 9 | - If the bug exists in a specific class/method, provide that in the title. 10 | - Provide as much detail as possible on how to reproduce the bug, including values. 11 | - If you have a proposed way to solve the problem, please **reply to your bug report with your solution**, do not list it in the description of the issue. 12 | 13 | If you want to open up an issue for any other reason, please adhere to these guidelines: 14 | 15 | - Keep the title around 5-7 words. 16 | - Do not include the words "feature" or synonyms in the title. We will handle that with tags. 17 | - If you want something improved in a specific class, please mention that. Example title: *"Add 'cubit' conversion to Length class"* 18 | - Discussion issues should start with a question (hence the discussion), so end the title in a question mark. :) 19 | 20 | ## Merge Acceptance Requirements 21 | 22 | In order for your pull request to be merged, the merge itself must meet the following guidelines: 23 | 24 | - New files created in the pull request must have a corresponding unit test file, or must be covered within an existing test file. 25 | - Your merge may not drop the project's test coverage below 85%. 26 | - Your merge may not drop the project's test coverage by MORE than 5%. 27 | - Your merge must pass Tracis-CI build tests for BOTH PHP 5.6.X and PHP 7.X. 28 | - You must make your pull request INTO the dev branch, and it is suggested that you work off of the dev branch. 29 | 30 | ## Coding Requirements 31 | 32 | The following guidelines are greatly encouraged, although strict adherence is not necessarily required for your pull request to be merged. 33 | 34 | - Coding Style: PSR-2 35 | - Namespacing: 36 | - Within `Samsara\Newton` 37 | - PSR-4 38 | - Docblock comments should be included and list, at a minimum: 39 | - The params 40 | - The exceptions thrown 41 | - The return value 42 | - Comments describing information for the developer should accompany any public methods 43 | - All methods should return some value. In other words, void is not considered a valid return value within this project. 44 | - Units, and anything dealing with units, should always treat them as MUTABLE. 45 | -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Length.php: -------------------------------------------------------------------------------- 1 | 1, 29 | self::CENTIMETER => 2, 30 | self::METER => 3, 31 | self::KILOMETER => 4, 32 | self::INCH => 5, 33 | self::FOOT => 6, 34 | self::YARD => 7, 35 | self::MILE => 8, 36 | self::NAUTICAL_MILE => 9, 37 | self::ASTRONOMICAL_UNIT => 10, 38 | self::LIGHT_YEAR => 11, 39 | self::PARSEC => 12 40 | ]; 41 | 42 | /** 43 | * @var string native unit name 44 | */ 45 | protected $native = self::METER; 46 | 47 | 48 | public function __construct($value, $unit = null) 49 | { 50 | $this->rates = [ 51 | $this->units[self::MILLIMETER] => '0.001', 52 | $this->units[self::CENTIMETER] => '0.01', 53 | $this->units[self::METER] => '1', 54 | $this->units[self::KILOMETER] => '1000', 55 | $this->units[self::INCH] => '0.0254', 56 | $this->units[self::FOOT] => '0.3048', 57 | $this->units[self::YARD] => '0.9144', 58 | $this->units[self::MILE] => '1609.34', 59 | $this->units[self::NAUTICAL_MILE] => '1852', 60 | $this->units[self::ASTRONOMICAL_UNIT] => '149597870700', 61 | $this->units[self::LIGHT_YEAR] => '9460528400000000' 62 | ]; 63 | 64 | parent::__construct($value, $unit); 65 | 66 | $this->setComposition(UnitComposition::LENGTH); 67 | } 68 | 69 | } -------------------------------------------------------------------------------- /tests/Samsara/Newton/Core/QuantityTest.php: -------------------------------------------------------------------------------- 1 | getUnitClass(UnitComposition::TIME, '500'); 13 | $time2 = $unit->getUnitClass(UnitComposition::TIME, '250'); 14 | 15 | $this->assertEquals( 16 | '750', 17 | $time->add($time2)->getValue() 18 | ); 19 | 20 | $length = $unit->getUnitClass(UnitComposition::LENGTH, '500'); 21 | 22 | $this->setExpectedException('Exception', 'Cannot add units of two different types.'); 23 | 24 | $time->add($length); 25 | } 26 | 27 | public function testSubtract() 28 | { 29 | $unit = new UnitComposition(); 30 | 31 | $time = $unit->getUnitClass(UnitComposition::TIME, '500'); 32 | $time2 = $unit->getUnitClass(UnitComposition::TIME, '250'); 33 | 34 | $this->assertEquals( 35 | '250', 36 | $time->subtract($time2)->getValue() 37 | ); 38 | 39 | $length = $unit->getUnitClass(UnitComposition::LENGTH, '500'); 40 | 41 | $this->setExpectedException('Exception', 'Cannot subtract units of two different types.'); 42 | 43 | $time->subtract($length); 44 | } 45 | 46 | public function testPreConverted() 47 | { 48 | $unit = new UnitComposition(); 49 | 50 | $time = $unit->getUnitClass(UnitComposition::TIME, '500'); 51 | 52 | $this->assertEquals( 53 | '600', 54 | $time->preConvertedAdd('100')->getValue() 55 | ); 56 | 57 | $this->assertEquals( 58 | '500', 59 | $time->preConvertedSubtract('100')->getValue() 60 | ); 61 | 62 | $this->assertEquals( 63 | '5', 64 | $time->preConvertedDivide('100')->getValue() 65 | ); 66 | 67 | $this->assertEquals( 68 | '500', 69 | $time->preConvertedMultiply('100')->getValue() 70 | ); 71 | } 72 | 73 | public function testGet() 74 | { 75 | $unit = new UnitComposition(); 76 | 77 | $time = $unit->getUnitClass(UnitComposition::TIME, '500'); 78 | 79 | $this->assertEquals( 80 | '500', 81 | $time->getValue() 82 | ); 83 | 84 | $this->assertEquals( 85 | 's', 86 | $time->getUnit() 87 | ); 88 | 89 | $this->assertEquals( 90 | '1', 91 | $time->getConversionRate('s') 92 | ); 93 | 94 | $unitComp = $time->getUnitsPresent(); 95 | 96 | $this->assertEquals( 97 | 1, 98 | count($unitComp) 99 | ); 100 | 101 | $this->assertEquals( 102 | 1, 103 | $unitComp['time'] 104 | ); 105 | } 106 | 107 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Core/SIPrefixes.php: -------------------------------------------------------------------------------- 1 | '1000', 33 | self::MEGA => '1000000', 34 | self::GIGA => '1000000000', 35 | self::TERA => '1000000000000', 36 | self::PETA => '1000000000000000', 37 | self::EXA => '1000000000000000000', 38 | self::ZETTA => '1000000000000000000000', 39 | self::MILLI => '0.001', 40 | self::MICRO => '0.000001', 41 | self::NANO => '0.000000001', 42 | self::PICO => '0.000000000001', 43 | self::FEMTO => '0.000000000000001', 44 | self::ATTO => '0.000000000000000001', 45 | self::ZEPTO => '0.000000000000000000001', 46 | ]; 47 | 48 | protected static $order = [ 49 | 0 => self::ZEPTO, 50 | 1 => self::ATTO, 51 | 2 => self::FEMTO, 52 | 3 => self::PICO, 53 | 4 => self::NANO, 54 | 5 => self::MICRO, 55 | 6 => self::MILLI, 56 | 7 => 'BASE', 57 | 8 => self::KILO, 58 | 9 => self::MEGA, 59 | 10 => self::GIGA, 60 | 11 => self::TERA, 61 | 12 => self::PETA, 62 | 13 => self::EXA, 63 | 14 => self::ZETTA 64 | ]; 65 | 66 | public function convertTo(PrefixContainer $prefix, NumberInterface $value, $unitSymbol) 67 | { 68 | 69 | } 70 | 71 | public static function matchBest(NumberInterface $value, $pos = 7) 72 | { 73 | 74 | // The number is more than three orders of magnitude from zero 75 | if ($value->greaterThanOrEqualTo(1000) || $value->lessThanOrEqualTo(-1000)) { 76 | // Increase the exponent by three and try again 77 | return self::matchBest($value->divide(1000), ($pos+1)); 78 | } 79 | 80 | // The number is a decimal less than one from zero 81 | if ($value->lessThan(1) && $value->greaterThan(-1) && !$value->equals(0)) { 82 | // Decrease the exponent by three and try again 83 | return self::matchBest($value->multiply(1000), ($pos-1)); 84 | } 85 | 86 | // If no transformation is needed, we have a special case of the return 87 | if ($pos == 7) { 88 | return new PrefixContainer(1, 7); 89 | } 90 | 91 | // Otherwise, we have our answer 92 | return new PrefixContainer(self::$scale[self::$order[$pos]], $pos); 93 | } 94 | 95 | public static function getUnitPrefixString($orderVal) 96 | { 97 | $prefix = self::$order[$orderVal]; 98 | 99 | if ($prefix == 'BASE') { 100 | return ''; 101 | } else { 102 | return $prefix; 103 | } 104 | } 105 | 106 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to this project will be documented in this file. 3 | This project adheres to [Semantic Versioning](http://semver.org/). 4 | 5 | ## [Unreleased] - [unreleased] 6 | ### Added 7 | - Unit test for Planck constant 8 | - Unit tests for exceptions in PhysicsProvider 9 | - **Dependency:** 10 | - samsara/fermat: dev-dev 11 | - ScalarQuantity (extending Quantity) 12 | - VectorQuantity (extending Quantity) 13 | - VectorAcceleration (extending VectorQuantity) 14 | - VectorForce (extending VectorQuantity) 15 | - VectorMomentum (extending VectorQuantity) 16 | - VectorVelocity (extending VectorQuantity) 17 | - `pecl install stats` to travis config 18 | - Divide by zero exception in UnitComposition (how did that get removed?) 19 | 20 | ### Removed 21 | - MathProvider class 22 | - MathProvider test 23 | 24 | ### Changed 25 | - `throw new \Exception` to `throw new \InvalidArgumentException` in PhysicsProvider where appropriate 26 | - All dimensionless physics unit (i.e. Acceleration, Energy, etc.) now extend ScalarQuantity 27 | - All MathProvider usages (removed) to BCProvider usages (from samsara/fermat) 28 | 29 | ### Fixed 30 | - **Renamed:** Plank.php -> Planck.php (incorrectly named file) 31 | 32 | ## [1.0.0] - 2015-10-09 33 | ### Added 34 | - CHANGELOG.md (this file) 35 | 36 | ### Changed 37 | - Added DocBlocks and comments for all public methods 38 | - Examined the visibility of methods and properties in each class 39 | 40 | ## [0.3.0] - 2015-08-28 41 | ### Added 42 | - A protected method on Quantity to allow a Unit to directly define its unit composition array 43 | - Constants 44 | - Gravitation Constant 45 | - Planck's Constant 46 | - Universal Gravitation Equation to the PhysicsProvider 47 | 48 | ## [0.2.0] - 2015-08-27 49 | ### Added 50 | - Units can now calculate square roots. 51 | - Instrumentation 52 | - Travis-CI 53 | - Coveralls 54 | - CONTRIBUTING.md file with Contribution Guidelines 55 | - COPYRIGHT file 56 | - LICENSE file 57 | - "Extending" section to README.md 58 | - "Contributing" section to README.md 59 | - Unit tests 60 | - **New Dependency (Dev):** PHPUnit 4.8.* 61 | - Quantity::preConvertedMultiply and Quantity::preConvertedDivide 62 | - **New Units:** 63 | - Cycles 64 | - Frequency 65 | - Momentum 66 | - Temperature 67 | - A naiveMultiOpt method for intelligently calculating the result of multiple multiplies and divides at once. 68 | 69 | ### Changed 70 | - PhysicsProvider methods now represent equations instead of results, and the result they return depends on the inputs you provide. 71 | - Renamed Project: PHPhysics => Newton 72 | - Fixed places where native math operations were being used instead of MathProvider. 73 | - Abstracted unit comp array comparison so that code can be reused in more places. 74 | - Bug where unit comp arrays might match the wrong unit due to ordering of the array. 75 | - Fixed condition where units might get set to non-numeric values, or get their unit changed permanently inside of a math operation. 76 | - Fixed divide by zero problem in MathProvider 77 | 78 | ## [0.1.2] - 2015-08-24 79 | ### Changed 80 | - Static references in UnitComposition to instance references 81 | 82 | ## [0.1.1] - 2015-08-24 83 | ### Added 84 | - README explaining usage and installation 85 | 86 | ## 0.1.0 - 2015-08-24 87 | ### Added 88 | - Initial commit with Units, UnitComposition, Quantity, etc. 89 | 90 | [unreleased]: https://github.com/JordanRL/Newton/compare/v1.0.0...HEAD 91 | [1.0.0]: https://github.com/JordanRL/Newton/compare/v0.3.0...v1.0.0 92 | [0.3.0]: https://github.com/JordanRL/Newton/compare/v0.2.0...v0.3.0 93 | [0.2.0]: https://github.com/JordanRL/Newton/compare/v0.1.2...v0.2.0 94 | [0.1.2]: https://github.com/JordanRL/Newton/compare/v0.1.1...v0.1.2 95 | [0.1.1]: https://github.com/JordanRL/Newton/compare/v0.1.0...v0.1.1 96 | -------------------------------------------------------------------------------- /src/Samsara/Newton/Units/Core/VectorQuantity.php: -------------------------------------------------------------------------------- 1 | setAzimuth(Numbers::makeOrDont(Numbers::IMMUTABLE, $azimuth)); 28 | $this->setInclination(Numbers::makeOrDont(Numbers::IMMUTABLE, $inclination)); 29 | $this->setMagnitude($scalarClass); 30 | 31 | $this->scalarClass = (new \ReflectionClass($scalarClass))->getName(); 32 | 33 | $this->defineComposition($scalarClass->getUnitsPresent()); 34 | 35 | parent::__construct($scalarClass->getValue(), $scalarClass->getUnit()); 36 | } 37 | 38 | /** 39 | * @return ScalarQuantity 40 | */ 41 | public function getScalarUnit() 42 | { 43 | return $this->getRho(); 44 | } 45 | 46 | public function preConvertedAdd($value) 47 | { 48 | $this->getScalarUnit()->preConvertedAdd($value); 49 | 50 | return $this; 51 | } 52 | 53 | public function preConvertedSubtract($value) 54 | { 55 | $this->getScalarUnit()->preConvertedSubtract($value); 56 | 57 | return $this; 58 | } 59 | 60 | public function preConvertedMultiply($value) 61 | { 62 | $this->getScalarUnit()->preConvertedMultiply($value); 63 | 64 | return $this; 65 | } 66 | 67 | public function preConvertedDivide($value) 68 | { 69 | $this->getScalarUnit()->preConvertedDivide($value); 70 | 71 | return $this; 72 | } 73 | 74 | /** 75 | * @param VectorQuantity|ScalarQuantity $quantity 76 | * 77 | * @returns $this 78 | * @throws \Exception 79 | */ 80 | public function add($quantity) 81 | { 82 | if ($this->scalarOrNot($quantity)) { 83 | $this->getScalarUnit()->add($quantity); 84 | } elseif ($quantity instanceof VectorQuantity) { 85 | $this->vectorAdd($quantity); 86 | } else { 87 | throw new \InvalidArgumentException('Can only add an instance of the scalar unit or VectorQuantity'); 88 | } 89 | 90 | return $this; 91 | } 92 | 93 | public function vectorAdd(VectorQuantity $vectorQuantity) 94 | { 95 | if (!$this->scalarOrNot($vectorQuantity->getScalarUnit())) { 96 | throw new \InvalidArgumentException('Cannot add vectors which have different types of scalar units.'); 97 | } 98 | 99 | $this->setAzimuth($this->getAzimuth()->add($vectorQuantity->getAzimuth())); 100 | $this->setInclination($this->getInclination()->add($vectorQuantity->getInclination())); 101 | $this->getScalarUnit()->add($vectorQuantity->getScalarUnit()); 102 | 103 | return $this; 104 | } 105 | 106 | /** 107 | * @param VectorQuantity|ScalarQuantity $quantity 108 | * 109 | * @returns $this 110 | * @throws \Exception 111 | */ 112 | public function subtract($quantity) 113 | { 114 | if ($this->scalarOrNot($quantity)) { 115 | $this->getScalarUnit()->subtract($quantity); 116 | } elseif ($quantity instanceof VectorQuantity) { 117 | $this->vectorSubtract($quantity); 118 | } else { 119 | throw new \InvalidArgumentException('Can only add an instance of the scalar unit or VectorQuantity'); 120 | } 121 | 122 | return $this; 123 | } 124 | 125 | public function vectorSubtract(VectorQuantity $vectorQuantity) 126 | { 127 | if (!$this->scalarOrNot($vectorQuantity->getScalarUnit())) { 128 | throw new \InvalidArgumentException('Cannot add vectors which have different types of scalar units.'); 129 | } 130 | 131 | $this->setAzimuth($this->getAzimuth()->subtract($vectorQuantity->getAzimuth())); 132 | $this->setInclination($this->getInclination()->subtract($vectorQuantity->getInclination())); 133 | $this->getScalarUnit()->subtract($vectorQuantity->getScalarUnit()); 134 | 135 | return $this; 136 | } 137 | 138 | public function getUnitCompositionClass() 139 | { 140 | return $this->getScalarUnit()->getUnitCompositionClass(); 141 | } 142 | 143 | public function to($unit) 144 | { 145 | $this->getScalarUnit()->to($unit); 146 | 147 | return $this; 148 | } 149 | 150 | public function toNative() 151 | { 152 | $this->getScalarUnit()->toNative(); 153 | 154 | return $this; 155 | } 156 | 157 | public function getConversionRate($unit) 158 | { 159 | return $this->getScalarUnit()->getConversionRate($unit); 160 | } 161 | 162 | public function addAlias($alias, $unit) 163 | { 164 | $this->getScalarUnit()->addAlias($alias, $unit); 165 | 166 | return $this; 167 | } 168 | 169 | public function addUnit($alias, $nativeConversion) 170 | { 171 | $this->getScalarUnit()->addUnit($alias, $nativeConversion); 172 | 173 | return $this; 174 | } 175 | 176 | protected function scalarOrNot($testInput) 177 | { 178 | $className = $this->scalarClass; 179 | 180 | return $testInput instanceof $className; 181 | } 182 | 183 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Newton 2 | 3 | [![Build Status](https://travis-ci.org/JordanRL/Newton.svg?branch=master)](https://travis-ci.org/JordanRL/Newton) [![Coverage Status](https://coveralls.io/repos/JordanRL/Newton/badge.svg?branch=master&service=github)](https://coveralls.io/github/JordanRL/Newton?branch=master) [![Latest Stable Version](https://poser.pugx.org/samsara/newton/v/stable)](https://packagist.org/packages/samsara/newton) [![Total Downloads](https://poser.pugx.org/samsara/newton/downloads)](https://packagist.org/packages/samsara/newton) [![Latest Unstable Version](https://poser.pugx.org/samsara/newton/v/unstable)](https://packagist.org/packages/samsara/newton) [![License](https://poser.pugx.org/samsara/newton/license)](https://packagist.org/packages/samsara/newton) 4 | 5 | **This project is unit tested against 5.6.X and 7.X, and merges are not accepted unless the tests pass on both.** 6 | 7 | ## Installation 8 | 9 | To install, simply require the package using composer: 10 | 11 | composer require samsara/newton "1.*" 12 | 13 | Or include it in your `composer.json` file: 14 | 15 | ```json 16 | { 17 | "require": { 18 | "samsara/newton": "1.*" 19 | } 20 | } 21 | ``` 22 | 23 | The project namespace is `Samsara\Newton\*`. You can view the project on [Packagist](https://packagist.org/packages/samsara/newton). 24 | 25 | ## Usage 26 | 27 | There are many ways to use this package. The preferred way involves instantiating the UnitComposition class and using it as a factory. 28 | 29 | In order to allow new unit classes which extend Quantity to work with the UnitComposition class, it was necessary to force instantiation of it. This is explained in further detail in the **Extending** section. 30 | 31 | This also means that if you directly instantiate a unit, you must inject a UnitComposition instance. 32 | 33 | ```php 34 | $unitComposition = new Samsara\Newton\Core\UnitComposition(); 35 | 36 | $thrust = $unitComposition->getUnitClass(UnitComposition::FORCE, 1000); 37 | echo $thrust; // 1000 Newtons 38 | $mass = $unitComposition->getUnitClass(UnitComposition::MASS, 1000); 39 | echo $mass; // 1000 kg 40 | 41 | $acceleration = $thrust->divideBy($mass); 42 | 43 | echo $acceleration; // 1 m/s^2 44 | 45 | $acceleration->addAlias('N/kg', 'm/s^2')->to('N/kg'); 46 | 47 | echo $acceleration; // 1 N/kg [Gravitational field strength] 48 | ``` 49 | 50 | You can also add unit of different types. 51 | 52 | ```php 53 | $unitComposition = new Samsara\Newton\Core\UnitComposition(); 54 | 55 | $thrust = $unitComposition->getUnitClass(UnitComposition::FORCE, 1000); 56 | echo $thrust; // 1000 Newtons 57 | $mass = $unitComposition->getUnitClass(UnitComposition::MASS, 500); 58 | echo $mass; // 500 kg 59 | 60 | $mass2 = new Mass(5, $unitComposition, 't'); // 't' = metric ton = 1000kg 61 | 62 | $mass->add($mass2); 63 | echo $mass; // 5500 kg; 64 | ``` 65 | 66 | The **MathProvider** has static methods which allow you to perform math operations using the BC Math extension. This is used internally in the project as we might very easily exceed the PHP_INT_MAX limit during unit conversions. It also provides several random functions, including a gaussianRandom() method. 67 | 68 | The **PhysicsProvider** has static methods which implement some common physics equations using the correct unit classes. 69 | 70 | An interesting, non-physics use for something like this library is to determine how many times a given server can execute a loop per second. For instance: 71 | 72 | ```php 73 | $unitComposition = new UnitComposition(); 74 | 75 | $start = microtime(true); 76 | for ($i = 0;$i < 10000;$i++) { 77 | // Loop to test 78 | } 79 | $end = microtime(true); 80 | 81 | $duration = $end - $start; 82 | $durationInMilliseconds = $duration * 1000; 83 | 84 | $time = new Time($durationInMilliseconds, $unitComposition, 'ms'); 85 | $cycles = new Cycles(10000, $unitComposition); 86 | 87 | $loopsPerSecond = $unitComposition->naiveDivide($cycles, $time); 88 | 89 | // The number of times, as measured, that the computer can execute the loop 90 | // in a single second. 91 | echo $loopsPerSecond->getValue(); 92 | ``` 93 | 94 | ## Extending 95 | 96 | Adding new units is relatively easy. You must first make your unit class, and this class must extend `Samsara\Newton\Core\Quantity`. This class must define a set of units in the `$units` property (where it defines the index for `$rates`), and then define the relative conversion rates between them. 97 | 98 | All of the conversions must be in terms of the **native** unit, which is defined in the property `$native`. 99 | 100 | ### Example 101 | 102 | ```php 103 | use Samsara\Newton\Core\Quantity; 104 | use Samsara\Newton\Core\UnitComposition; 105 | 106 | class MyUnit extends Quantity 107 | { 108 | const SOMEUNIT = 'g'; 109 | const BIGUNIT = 'bg'; 110 | 111 | protected $units = [ 112 | // It is the first index in the rates array 113 | self::SOMEUNIT => 1, 114 | self::BIGUNIT => 2 115 | ]; 116 | 117 | protected $native = self::SOMEUNIT; 118 | 119 | public function __construct($value, UnitComposition $unitComposition, $unit = null) 120 | { 121 | $this->rates = [ 122 | // Almost always the 'native' unit is set equal to 1 123 | $this->units[self::SOMEUNIT] => '1', 124 | $this->units[self::BIGUNIT] => '1000', 125 | ]; 126 | 127 | parent::__construct($value, $unitComposition, $unit) 128 | 129 | $this->setComposition($unitComposition->dynamicUnits['MyUnit']); 130 | } 131 | } 132 | ``` 133 | 134 | Then, in the calling context, you must prepare the UnitComposition class with the definitions of what types of units this custom unit contains. This allows the UnitComposition class to automatically use your custom class in multiply and divide operations when it is appropriate to do so. 135 | 136 | ```php 137 | $unitComposition = new UnitComposition(); 138 | 139 | // This will automatically instatiate the class Namespaced\MyUnit() 140 | // when 'time' has an exponent of 2, and 'mass' has an exponent of 1 141 | // after multiply or divide operations using the naive*() methods. 142 | // 143 | // The last argument defines how you can refer to the unit in the 144 | // factory method: getUnitClass() 145 | $unitComposition->addUnit('Namespaced\\MyUnit', ['time' => 2, 'mass' => 1], 'MyUnit'); 146 | 147 | // Now we can instantiate two ways: 148 | 149 | // $myunit is now an object of type MyUnit, in its native units, with a value of zero 150 | $myunit = $unitComposition->getUnitClass('MyUnit'); 151 | // Object of MyUnit type in native units with value 1000 152 | $myunit2 = $unitComposition->getUnitClass('MyUnit', 1000); 153 | 154 | // OR 155 | 156 | // MyUnit object in BIGUNIT with value 1 == 1000 in SOMEUNIT 157 | $myunit3 = new Namespaced\MyUnit(1, $unitComposition, 'bg'); 158 | 159 | // We can add them if we want 160 | 161 | // Automatically converts. $myunit3 now has value of 2 and units of BIGUNIT. 162 | $myunit3->add($myunit2)->add($myunit); 163 | ``` 164 | 165 | Only the instance of UnitComposition prepared in the way outlined above, with a call to addUnit(), will understand how to automatically return an instance of MyUnit(). Because of this, it is suggested that you treat the UnitComposition class as a service, and use a single instance of it within your application. 166 | 167 | ## Contributing 168 | 169 | Please ensure that pull requests meet the following guidelines: 170 | 171 | - New files created in the pull request must have a corresponding unit test file, or must be covered within an existing test file. 172 | - Your merge may not drop the project's test coverage below 85%. 173 | - Your merge may not drop the project's test coverage by MORE than 5%. 174 | - Your merge must pass Travis-CI build tests for BOTH PHP 5.6.X and PHP 7.X. 175 | 176 | For more information, please see the section on [Contributing](CONTRIBUTING.md) 177 | -------------------------------------------------------------------------------- /tests/Samsara/Newton/Provider/PhysicsProviderTest.php: -------------------------------------------------------------------------------- 1 | getUnitClass(UnitComposition::LENGTH); 16 | $time = $unit->getUnitClass(UnitComposition::TIME); 17 | $accel = $unit->getUnitClass(UnitComposition::ACCELERATION); 18 | 19 | $length->preConvertedAdd(1); 20 | $time->preConvertedAdd(1); 21 | $accel->preConvertedAdd(1); 22 | 23 | $this->assertInstanceOf( 24 | 'Samsara\\Newton\\Units\\Time', 25 | PhysicsProvider::constantAccelCalcs($length, $accel) 26 | ); 27 | 28 | $this->assertInstanceOf( 29 | 'Samsara\\Newton\\Units\\Length', 30 | PhysicsProvider::constantAccelCalcs($time, $accel) 31 | ); 32 | 33 | $this->assertInstanceOf( 34 | 'Samsara\\Newton\\Units\\Acceleration', 35 | PhysicsProvider::constantAccelCalcs($length, $time) 36 | ); 37 | 38 | } 39 | 40 | public function testConstantAccelTooFewArguments() 41 | { 42 | 43 | $this->setExpectedException('InvalidArgumentException'); 44 | PhysicsProvider::constantAccelCalcs(0); 45 | 46 | } 47 | 48 | public function testConstantAccelTooManyArguments() 49 | { 50 | 51 | $this->setExpectedException('InvalidArgumentException'); 52 | PhysicsProvider::constantAccelCalcs(0, 1, 2); 53 | 54 | } 55 | 56 | public function testConstantAccelInvalidArguments() 57 | { 58 | 59 | $this->setExpectedException('InvalidArgumentException'); 60 | PhysicsProvider::constantAccelCalcs(0, 1); 61 | 62 | } 63 | 64 | public function testConstantAccelOneOfEach() 65 | { 66 | 67 | $this->setExpectedException('InvalidArgumentException'); 68 | $unit = new UnitComposition(); 69 | 70 | $length = $unit->getUnitClass(UnitComposition::LENGTH); 71 | $length->preConvertedAdd(1); 72 | 73 | PhysicsProvider::constantAccelCalcs($length, $length); 74 | 75 | } 76 | 77 | public function testNewtonsSecondLaw() 78 | { 79 | 80 | $unit = new UnitComposition(); 81 | 82 | $force = $unit->getUnitClass(UnitComposition::FORCE); 83 | $mass = $unit->getUnitClass(UnitComposition::MASS); 84 | $accel = $unit->getUnitClass(UnitComposition::ACCELERATION); 85 | 86 | $force->preConvertedAdd(1); 87 | $mass->preConvertedAdd(1); 88 | $accel->preConvertedAdd(1); 89 | 90 | $this->assertInstanceOf( 91 | 'Samsara\\Newton\\Units\\Mass', 92 | PhysicsProvider::forceMassAccelCalcs($force, $accel) 93 | ); 94 | 95 | $this->assertInstanceOf( 96 | 'Samsara\\Newton\\Units\\Force', 97 | PhysicsProvider::forceMassAccelCalcs($mass, $accel) 98 | ); 99 | 100 | $this->assertInstanceOf( 101 | 'Samsara\\Newton\\Units\\Acceleration', 102 | PhysicsProvider::forceMassAccelCalcs($force, $mass) 103 | ); 104 | 105 | } 106 | 107 | public function testNewtonsSecondLawTooFewArguments() 108 | { 109 | 110 | $this->setExpectedException('InvalidArgumentException'); 111 | PhysicsProvider::forceMassAccelCalcs(0); 112 | 113 | } 114 | 115 | public function testNewtonsSecondLawTooManyArguments() 116 | { 117 | 118 | $this->setExpectedException('InvalidArgumentException'); 119 | PhysicsProvider::forceMassAccelCalcs(0, 1, 2); 120 | 121 | } 122 | 123 | public function testNewtonsSecondLawInvalidArguments() 124 | { 125 | 126 | $this->setExpectedException('InvalidArgumentException'); 127 | PhysicsProvider::forceMassAccelCalcs(0, 1); 128 | 129 | } 130 | 131 | public function testNewtonsSecondLawOneOfEach() 132 | { 133 | 134 | $this->setExpectedException('InvalidArgumentException'); 135 | $unit = new UnitComposition(); 136 | 137 | $mass = $unit->getUnitClass(UnitComposition::MASS); 138 | $mass->preConvertedAdd(1); 139 | 140 | PhysicsProvider::forceMassAccelCalcs($mass, $mass); 141 | 142 | } 143 | 144 | public function testKineticEnergy() 145 | { 146 | 147 | $unit = new UnitComposition(); 148 | 149 | $energy = $unit->getUnitClass(UnitComposition::ENERGY); 150 | $mass = $unit->getUnitClass(UnitComposition::MASS); 151 | $velocity = $unit->getUnitClass(UnitComposition::VELOCITY); 152 | 153 | $energy->preConvertedAdd(1); 154 | $mass->preConvertedAdd(1); 155 | $velocity->preConvertedAdd(1); 156 | 157 | $this->assertInstanceOf( 158 | 'Samsara\\Newton\\Units\\Mass', 159 | PhysicsProvider::kineticEnergyCalcs($energy, $velocity) 160 | ); 161 | 162 | $this->assertInstanceOf( 163 | 'Samsara\\Newton\\Units\\Energy', 164 | PhysicsProvider::kineticEnergyCalcs($mass, $velocity) 165 | ); 166 | 167 | $this->assertInstanceOf( 168 | 'Samsara\\Newton\\Units\\Velocity', 169 | PhysicsProvider::kineticEnergyCalcs($energy, $mass) 170 | ); 171 | 172 | } 173 | 174 | public function testKineticEnergyTooFewArguments() 175 | { 176 | 177 | $this->setExpectedException('InvalidArgumentException'); 178 | PhysicsProvider::kineticEnergyCalcs(0); 179 | 180 | } 181 | 182 | public function testKineticEnergyTooManyArguments() 183 | { 184 | 185 | $this->setExpectedException('InvalidArgumentException'); 186 | PhysicsProvider::kineticEnergyCalcs(0, 1, 2); 187 | 188 | } 189 | 190 | public function testKineticEnergyInvalidArguments() 191 | { 192 | 193 | $this->setExpectedException('InvalidArgumentException'); 194 | PhysicsProvider::kineticEnergyCalcs(0, 1); 195 | 196 | } 197 | 198 | public function testKineticEnergyOneOfEach() 199 | { 200 | 201 | $this->setExpectedException('InvalidArgumentException'); 202 | $unit = new UnitComposition(); 203 | 204 | $mass = $unit->getUnitClass(UnitComposition::MASS); 205 | $mass->preConvertedAdd(1); 206 | 207 | PhysicsProvider::kineticEnergyCalcs($mass, $mass); 208 | 209 | } 210 | 211 | public function testMomentum() 212 | { 213 | 214 | $unit = new UnitComposition(); 215 | 216 | $momentum = $unit->getUnitClass(UnitComposition::MOMENTUM); 217 | $mass = $unit->getUnitClass(UnitComposition::MASS); 218 | $velocity = $unit->getUnitClass(UnitComposition::VELOCITY); 219 | 220 | $momentum->preConvertedAdd(1); 221 | $mass->preConvertedAdd(1); 222 | $velocity->preConvertedAdd(1); 223 | 224 | $this->assertInstanceOf( 225 | 'Samsara\\Newton\\Units\\Mass', 226 | PhysicsProvider::momentumCalcs($momentum, $velocity) 227 | ); 228 | 229 | $this->assertInstanceOf( 230 | 'Samsara\\Newton\\Units\\Momentum', 231 | PhysicsProvider::momentumCalcs($mass, $velocity) 232 | ); 233 | 234 | $this->assertInstanceOf( 235 | 'Samsara\\Newton\\Units\\Velocity', 236 | PhysicsProvider::momentumCalcs($momentum, $mass) 237 | ); 238 | 239 | } 240 | 241 | public function testMomentumTooFewArguments() 242 | { 243 | 244 | $this->setExpectedException('InvalidArgumentException'); 245 | PhysicsProvider::momentumCalcs(0); 246 | 247 | } 248 | 249 | public function testMomentumTooManyArguments() 250 | { 251 | 252 | $this->setExpectedException('InvalidArgumentException'); 253 | PhysicsProvider::momentumCalcs(0, 1, 2); 254 | 255 | } 256 | 257 | public function testMomentumInvalidArguments() 258 | { 259 | 260 | $this->setExpectedException('InvalidArgumentException'); 261 | PhysicsProvider::momentumCalcs(0, 1); 262 | 263 | } 264 | 265 | public function testMomentumOneOfEach() 266 | { 267 | 268 | $this->setExpectedException('InvalidArgumentException'); 269 | $unit = new UnitComposition(); 270 | 271 | $mass = $unit->getUnitClass(UnitComposition::MASS); 272 | $mass->preConvertedAdd(1); 273 | 274 | PhysicsProvider::momentumCalcs($mass, $mass); 275 | 276 | } 277 | 278 | } -------------------------------------------------------------------------------- /tests/Samsara/Newton/Core/UnitCompositionTest.php: -------------------------------------------------------------------------------- 1 | addUnit('SomeClass', ['time' => 1, 'mass' => 1], 'test'); 20 | 21 | $this->assertEquals( 22 | 'SomeClass', 23 | $unit->dynamicUnits['test'] 24 | ); 25 | 26 | $this->assertArrayHasKey( 27 | 'time', 28 | $unit->unitComp['test'] 29 | ); 30 | 31 | $this->assertArrayHasKey( 32 | 'mass', 33 | $unit->unitComp['test'] 34 | ); 35 | 36 | $this->assertEquals( 37 | 1, 38 | $unit->unitComp['test']['time'] 39 | ); 40 | 41 | $this->assertEquals( 42 | 1, 43 | $unit->unitComp['test']['mass'] 44 | ); 45 | 46 | $this->setExpectedException('Exception', 'Cannot add unit SomeClass with key test because that key is already being used.'); 47 | 48 | $unit->addUnit('SomeClass', ['time' => 1, 'mass' => 1], 'test'); 49 | 50 | } 51 | 52 | public function testGetUnitClass() 53 | { 54 | $unit = new UnitComposition(); 55 | 56 | $this->assertInstanceOf( 57 | 'Samsara\\Newton\\Units\\Acceleration', 58 | $unit->getUnitClass('Acceleration') 59 | ); 60 | 61 | $this->assertInstanceOf( 62 | 'Samsara\\Newton\\Units\\Ampere', 63 | $unit->getUnitClass('Ampere') 64 | ); 65 | 66 | $this->assertInstanceOf( 67 | 'Samsara\\Newton\\Units\\Area', 68 | $unit->getUnitClass('Area') 69 | ); 70 | 71 | $this->assertInstanceOf( 72 | 'Samsara\\Newton\\Units\\Charge', 73 | $unit->getUnitClass('Charge') 74 | ); 75 | 76 | $this->assertInstanceOf( 77 | 'Samsara\\Newton\\Units\\Cycles', 78 | $unit->getUnitClass('Cycles') 79 | ); 80 | 81 | $this->assertInstanceOf( 82 | 'Samsara\\Newton\\Units\\Density', 83 | $unit->getUnitClass('Density') 84 | ); 85 | 86 | $this->assertInstanceOf( 87 | 'Samsara\\Newton\\Units\\Energy', 88 | $unit->getUnitClass('Energy') 89 | ); 90 | 91 | $this->assertInstanceOf( 92 | 'Samsara\\Newton\\Units\\Force', 93 | $unit->getUnitClass('Force') 94 | ); 95 | 96 | $this->assertInstanceOf( 97 | 'Samsara\\Newton\\Units\\Frequency', 98 | $unit->getUnitClass('Frequency') 99 | ); 100 | 101 | $this->assertInstanceOf( 102 | 'Samsara\\Newton\\Units\\Length', 103 | $unit->getUnitClass('Length') 104 | ); 105 | 106 | $this->assertInstanceOf( 107 | 'Samsara\\Newton\\Units\\Mass', 108 | $unit->getUnitClass('Mass') 109 | ); 110 | 111 | $this->assertInstanceOf( 112 | 'Samsara\\Newton\\Units\\Momentum', 113 | $unit->getUnitClass('Momentum') 114 | ); 115 | 116 | $this->assertInstanceOf( 117 | 'Samsara\\Newton\\Units\\Power', 118 | $unit->getUnitClass('Power') 119 | ); 120 | 121 | $this->assertInstanceOf( 122 | 'Samsara\\Newton\\Units\\Pressure', 123 | $unit->getUnitClass('Pressure') 124 | ); 125 | 126 | $this->assertInstanceOf( 127 | 'Samsara\\Newton\\Units\\Temperature', 128 | $unit->getUnitClass('Temperature') 129 | ); 130 | 131 | $this->assertInstanceOf( 132 | 'Samsara\\Newton\\Units\\Time', 133 | $unit->getUnitClass('Time') 134 | ); 135 | 136 | $this->assertInstanceOf( 137 | 'Samsara\\Newton\\Units\\Velocity', 138 | $unit->getUnitClass('Velocity') 139 | ); 140 | 141 | $this->assertInstanceOf( 142 | 'Samsara\\Newton\\Units\\Voltage', 143 | $unit->getUnitClass('Voltage') 144 | ); 145 | 146 | $this->assertInstanceOf( 147 | 'Samsara\\Newton\\Units\\Volume', 148 | $unit->getUnitClass('Volume') 149 | ); 150 | 151 | $unit->addUnit('Samsara\\Newton\\Units\\Volume', ['time' => 1, 'mass' => 1], 'test'); 152 | 153 | $this->assertInstanceOf( 154 | 'Samsara\\Newton\\Units\\Volume', 155 | $unit->getUnitClass('test') 156 | ); 157 | 158 | $this->setExpectedException('Exception', 'Unknown unit type: test2'); 159 | 160 | $unit->getUnitClass('test2'); 161 | } 162 | 163 | public function testGetUnitClassException() 164 | { 165 | $unit = new UnitComposition(); 166 | 167 | $unit->addUnit('Samsara\\Newton\\Core\\SIPrefixes', ['time' => 1, 'mass' => 1], 'test3'); 168 | 169 | $this->setExpectedException('Exception', 'Valid units must extend the Quantity class.'); 170 | 171 | $unit->getUnitClass('test3'); 172 | } 173 | 174 | public function testNaiveMultiply() 175 | { 176 | $unit = new UnitComposition(); 177 | $length = new Length(5, $unit); 178 | 179 | /** @var \Samsara\Newton\Units\Area $area */ 180 | $area = $unit->naiveMultiply($length, $length); 181 | 182 | $this->assertInstanceOf( 183 | 'Samsara\\Newton\\Units\\Area', 184 | $area 185 | ); 186 | 187 | $this->assertEquals( 188 | '25', 189 | $area->getValue() 190 | ); 191 | } 192 | 193 | public function testNaiveDivide() 194 | { 195 | $unit = new UnitComposition(); 196 | 197 | $thrust = new Force(1000, $unit); 198 | $mass = new Mass(1000, $unit); 199 | 200 | /** @var Acceleration $acceleration */ 201 | $acceleration = $unit->naiveDivide($thrust, $mass); 202 | 203 | $this->assertInstanceOf( 204 | 'Samsara\\Newton\\Units\\Acceleration', 205 | $acceleration 206 | ); 207 | 208 | $this->assertEquals( 209 | '1', 210 | $acceleration->getValue() 211 | ); 212 | 213 | $this->setExpectedException('Exception', 'Cannot divide by zero.'); 214 | 215 | $mass->preConvertedSubtract(1000); 216 | 217 | $unit->naiveDivide($thrust, $mass); 218 | } 219 | 220 | public function testGetUnitCompNameException() 221 | { 222 | $comp = ['time' => 6]; 223 | $unit = new UnitComposition(); 224 | 225 | $this->setExpectedException('Exception', 'Cannot match the unit definition to an existing unit.'); 226 | 227 | $unit->getUnitCompName($comp); 228 | } 229 | 230 | public function testNaiveMultiOpt() 231 | { 232 | $unit = new UnitComposition(); 233 | 234 | $cycles = $unit->getUnitClass('Cycles', 10); 235 | $time = $unit->getUnitClass('Time', 1); 236 | 237 | /** @var Frequency $frequency */ 238 | $frequency = $unit->naiveMultiOpt([$cycles], [$time]); 239 | 240 | $this->assertInstanceOf( 241 | 'Samsara\\Newton\\Units\\Frequency', 242 | $frequency 243 | ); 244 | 245 | $this->assertEquals( 246 | '10', 247 | $frequency->getValue() 248 | ); 249 | 250 | $this->assertEquals( 251 | '10', 252 | $unit->naiveMultiOpt([$time, 2, 5], [])->getValue() 253 | ); 254 | 255 | $this->assertEquals( 256 | '2', 257 | $unit->naiveMultiOpt([$time, 10], [5])->getValue() 258 | ); 259 | } 260 | 261 | public function testInvalidNumerator() 262 | { 263 | $unit = new UnitComposition(); 264 | 265 | $this->setExpectedException('Exception', 'Invalid numerator'); 266 | 267 | $unit->naiveMultiOpt(['hello', 'world'], []); 268 | } 269 | 270 | public function testInvalidDenominator() 271 | { 272 | $unit = new UnitComposition(); 273 | 274 | $this->setExpectedException('Exception', 'Invalid denominator'); 275 | 276 | $unit->naiveMultiOpt([], ['hello', 'world']); 277 | } 278 | 279 | public function testGetMultipliedUnit() 280 | { 281 | $unit = new UnitComposition(); 282 | 283 | $mass = $unit->getUnitClass(UnitComposition::MASS); 284 | $acceleration = $unit->getUnitClass(UnitComposition::ACCELERATION); 285 | 286 | $mass->preConvertedAdd(1); 287 | $acceleration->preConvertedAdd(1); 288 | 289 | $this->assertInstanceOf( 290 | 'Samsara\\Newton\\Units\\Force', 291 | $unit->getMultipliedUnit($mass, $acceleration) 292 | ); 293 | } 294 | 295 | public function testNaiveSquareRoot() 296 | { 297 | $unit = new UnitComposition(); 298 | 299 | $length = $unit->getUnitClass(UnitComposition::LENGTH); 300 | $acceleration = $unit->getUnitClass(UnitComposition::ACCELERATION); 301 | 302 | $acceleration->preConvertedAdd(1); 303 | 304 | $this->assertInstanceOf( 305 | 'Samsara\\Newton\\Units\\Time', 306 | $length->squareRoot([], [$acceleration]) 307 | ); 308 | } 309 | 310 | public function testGetDividedUnit() 311 | { 312 | $unit = new UnitComposition(); 313 | 314 | $mass = $unit->getUnitClass(UnitComposition::MASS); 315 | $force = $unit->getUnitClass(UnitComposition::FORCE); 316 | 317 | $mass->preConvertedAdd(1); 318 | $force->preConvertedAdd(1); 319 | 320 | $this->assertInstanceOf( 321 | 'Samsara\\Newton\\Units\\Acceleration', 322 | $unit->getDividedUnit($force, $mass) 323 | ); 324 | } 325 | 326 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Provider/PhysicsProvider.php: -------------------------------------------------------------------------------- 1 | multiplyBySquared($vals['time'])->preConvertedDivide(2); 73 | } elseif (array_key_exists('length', $vals) && array_key_exists('acceleration', $vals)) { 74 | /** @return Time */ 75 | return $vals['length']->squareRoot([2], [$vals['acceleration']]); 76 | } else { 77 | /** @return Acceleration */ 78 | return $vals['length']->divideBySquared($vals['time'])->preConvertedMultiply(2); 79 | } 80 | } 81 | 82 | /** 83 | * Force-Mass-Acceleration Equation: (Newton's Second Law) 84 | * 85 | * F = m a 86 | * 87 | * This is the same as the Force equation. 88 | * 89 | * This method should be called with the TWO known values, in any order. 90 | * 91 | * eg.: 92 | * 93 | * PhysicsProvider::forceMassAccelCalcs($mass, $force); 94 | * ... 95 | * PhysicsProvider::forceMassAccelCalcs($acceleration, $mass); 96 | * ... 97 | * PhysicsProvider::forceMassAccelCalcs($force, $mass); 98 | * 99 | * It returns the missing unit in the equation, with the value calculated based on the equation above, in native units. 100 | * 101 | * @param Mass[]|Force[]|Acceleration[] ...$quantities 102 | * @return Mass|Force|Acceleration 103 | * @throws \InvalidArgumentException 104 | */ 105 | public static function forceMassAccelCalcs(...$quantities) 106 | { 107 | if (count($quantities) != 2) { 108 | throw new \InvalidArgumentException('The Thrust-Mass Equation needs exactly two of: Force, Mass, Acceleration.'); 109 | } 110 | 111 | $vals = []; 112 | 113 | foreach ($quantities as $unit) { 114 | if ($unit instanceof Mass) { 115 | /** @var Mass */ 116 | $vals['mass'] = $unit; 117 | } elseif ($unit instanceof Force) { 118 | /** @var Force */ 119 | $vals['force'] = $unit; 120 | } elseif ($unit instanceof Acceleration) { 121 | /** @var Acceleration */ 122 | $vals['acceleration'] = $unit; 123 | } else { 124 | throw new \InvalidArgumentException('Only Mass, Force, and Acceleration are valid units for the Thrust-Mass Equation.'); 125 | } 126 | } 127 | 128 | if (count($vals) != 2) { 129 | throw new \InvalidArgumentException('The Thrust-Mass Equation needs only one of each unit.'); 130 | } 131 | 132 | if (array_key_exists('mass', $vals) && array_key_exists('force', $vals)) { 133 | /** @return Acceleration */ 134 | return $vals['force']->divideBy($vals['mass']); 135 | } elseif (array_key_exists('mass', $vals) && array_key_exists('acceleration', $vals)) { 136 | /** @return Force */ 137 | return $vals['acceleration']->multiplyBy($vals['mass']); 138 | } else { 139 | /** @return Mass */ 140 | return $vals['force']->divideBy($vals['acceleration']); 141 | } 142 | } 143 | 144 | /** 145 | * Kinetic Energy Equation: 146 | * 147 | * K = 1/2 m v^2 148 | * 149 | * This method should be called with the TWO known values, in any order. 150 | * 151 | * eg.: 152 | * 153 | * PhysicsProvider::kineticEnergyCalcs($mass, $energy); 154 | * ... 155 | * PhysicsProvider::kineticEnergyCalcs($energy, $velocity); 156 | * ... 157 | * PhysicsProvider::kineticEnergyCalcs($velocity, $mass); 158 | * 159 | * It returns the missing unit in the equation, with the value calculated based on the equation above, in native units. 160 | * 161 | * @param Energy[]|Velocity[]|Mass[] ...$quantities 162 | * @return Energy|Velocity|Mass 163 | * @throws \InvalidArgumentException 164 | */ 165 | public static function kineticEnergyCalcs(...$quantities) 166 | { 167 | if (count($quantities) != 2) { 168 | throw new \InvalidArgumentException('The Kinetic Energy Equation needs exactly two of: Mass, Velocity, Energy.'); 169 | } 170 | 171 | $vals = []; 172 | 173 | foreach ($quantities as $unit) { 174 | if ($unit instanceof Mass) { 175 | /** @var Mass */ 176 | $vals['mass'] = $unit; 177 | } elseif ($unit instanceof Velocity) { 178 | /** @var Velocity */ 179 | $vals['velocity'] = $unit; 180 | } elseif ($unit instanceof Energy) { 181 | /** @var Mass */ 182 | $vals['energy'] = $unit; 183 | } else { 184 | throw new \InvalidArgumentException('Only Mass, Velocity, and Energy are valid units for the Kinetic Energy Equation.'); 185 | } 186 | } 187 | 188 | if (count($vals) != 2) { 189 | throw new \InvalidArgumentException('The Kinetic Energy Equation needs only one of each unit.'); 190 | } 191 | 192 | if (array_key_exists('mass', $vals) && array_key_exists('velocity', $vals)) { 193 | /** @return Energy */ 194 | return $vals['mass']->multiplyBySquared($vals['velocity'])->preConvertedDivide(2); 195 | } elseif (array_key_exists('mass', $vals) && array_key_exists('energy', $vals)) { 196 | /** @return Velocity */ 197 | return $vals['energy']->squareRoot([2], [$vals['mass']]); 198 | } else { 199 | /** @return Mass */ 200 | return $vals['energy']->divideBySquared($vals['velocity'])->preConvertedMultiply(2); 201 | } 202 | } 203 | 204 | /** 205 | * Momentum Equation: 206 | * 207 | * p = m v 208 | * 209 | * This method should be called with the TWO known values, in any order. 210 | * 211 | * eg.: 212 | * 213 | * PhysicsProvider::momentumCalcs($mass, $velocity); 214 | * ... 215 | * PhysicsProvider::momentumCalcs($momentum, $mass); 216 | * ... 217 | * PhysicsProvider::momentumCalcs($velocity, $momentum); 218 | * 219 | * It returns the missing unit in the equation, with the value calculated based on the equation above, in native units. 220 | * 221 | * @param Momentum[]|Velocity[]|Mass[] ...$quantities 222 | * @return Momentum|Velocity|Mass 223 | * @throws \InvalidArgumentException 224 | */ 225 | public static function momentumCalcs(...$quantities) 226 | { 227 | if (count($quantities) != 2) { 228 | throw new \InvalidArgumentException('The Momentum Equation needs exactly two of: Mass, Velocity, Momentum.'); 229 | } 230 | 231 | $vals = []; 232 | 233 | foreach ($quantities as $unit) { 234 | if ($unit instanceof Mass) { 235 | /** @var Mass */ 236 | $vals['mass'] = $unit; 237 | } elseif ($unit instanceof Velocity) { 238 | /** @var Velocity */ 239 | $vals['velocity'] = $unit; 240 | } elseif ($unit instanceof Momentum) { 241 | /** @var Momentum */ 242 | $vals['momentum'] = $unit; 243 | } else { 244 | throw new \InvalidArgumentException('Only Mass, Velocity, and Momentum are valid units for the Momentum Equation.'); 245 | } 246 | } 247 | 248 | if (count($vals) != 2) { 249 | throw new \InvalidArgumentException('The Momentum Equation needs only one of each unit.'); 250 | } 251 | 252 | if (array_key_exists('mass', $vals) && array_key_exists('velocity', $vals)) { 253 | /** @return Momentum */ 254 | return $vals['mass']->multiplyBy($vals['velocity']); 255 | } elseif (array_key_exists('mass', $vals) && array_key_exists('momentum', $vals)) { 256 | /** @return Velocity */ 257 | return $vals['momentum']->divideBy($vals['mass']); 258 | } else { 259 | /** @return Mass */ 260 | return $vals['momentum']->divideBy($vals['velocity']); 261 | } 262 | } 263 | 264 | /** 265 | * Universal Gravitation Equation: 266 | * 267 | * A = (G m1 m2)/ r^2 268 | * 269 | * @param Mass[]|Acceleration[]|Length[] ...$quantities 270 | * @return Mass|Acceleration|Length 271 | * @throws \InvalidArgumentException 272 | */ 273 | public static function universalGravitation(...$quantities) 274 | { 275 | if (count($quantities) != 3) { 276 | throw new \InvalidArgumentException('The Universal Gravitation Equation requires at least three given units to calculate something.'); 277 | } 278 | 279 | $vals = []; 280 | 281 | foreach ($quantities as $unit) { 282 | if ($unit instanceof Mass) { 283 | /** @var Mass */ 284 | $vals['mass'][] = $unit; 285 | } elseif ($unit instanceof Length) { 286 | /** @var Length */ 287 | $vals['length'] = $unit; 288 | } elseif ($unit instanceof Acceleration) { 289 | /** @var Acceleration */ 290 | $vals['acceleration'] = $unit; 291 | } else { 292 | throw new \InvalidArgumentException('Only Mass, Acceleration and Length valid units for the Universal Gravitation Equation.'); 293 | } 294 | } 295 | 296 | $gravitation = new Gravitation(); 297 | 298 | $unitComposition = UnitComposition::getInstance(); 299 | 300 | if (array_key_exists('mass', $vals) && count($vals['mass']) == 2) { 301 | if (array_key_exists('length', $vals)) { 302 | /** @return Acceleration */ 303 | return $unitComposition->naiveMultiOpt([$gravitation, $vals['mass'][0], $vals['mass'][1]], [$vals['length'], $vals['length']]); 304 | } else { 305 | /** @return Length */ 306 | return $gravitation->squareRoot([$vals['mass'][0], $vals['mass'][1]], [$vals['acceleration']]); 307 | } 308 | } else { 309 | /** @return Mass */ 310 | return $unitComposition->naiveMultiOpt([$vals['acceleration'], $vals['length'], $vals['length']], [$gravitation, $vals['mass'][0]]); 311 | } 312 | } 313 | 314 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | -------------------------------------------------------------------------------- /src/Samsara/Newton/Core/Quantity.php: -------------------------------------------------------------------------------- 1 | 0 19 | * $units['km/h'] => 1 20 | * $units['km/hr'] => 1 21 | * 22 | * $rates[0] => 1 23 | * $rates[1] => 3.6 24 | * 25 | * @var array 26 | */ 27 | protected $units = []; 28 | 29 | /** 30 | * An array which explains the conversion rate from the native unit to the desired unit (by multiplication). 31 | * 32 | * m/s => km/s == 1 => 1000 33 | * km/s => km/h == 1000 => 3.6 34 | * 35 | * @var array 36 | */ 37 | protected $rates = []; 38 | 39 | /** 40 | * The native unit (in string form) that all multiplication or division should take place in. For instance, the 41 | * native unit of length is 'm' for meters; the native unit of mass is 'kg' for kilogram. 42 | * 43 | * @var string 44 | * Override this in each quantity subclass. 45 | */ 46 | protected $native; 47 | 48 | /** 49 | * The current numerical value of the unit in string form. It's important that numbers are operated on as strings, 50 | * because with the scale differences of the various units it is extremely likely that the maximum integer size 51 | * for PHP might be exceeded, and data loss might occur. 52 | * 53 | * @var NumberInterface 54 | */ 55 | private $value; 56 | 57 | /** 58 | * The current unit which the value is in. 59 | * 60 | * @var string 61 | */ 62 | private $unit; 63 | 64 | /** 65 | * This keeps track of what base units the current unit is composed of. This allows the UnitComposition class 66 | * to intelligently determine what unit is the result of multiplication and division. 67 | * 68 | * @var array 69 | */ 70 | private $unitTypesPresent = []; 71 | 72 | /** 73 | * The instance of UnitComposition which should be used when determining the unit types present in different units 74 | * and from which multiplication, division, and similar operations should take place. 75 | * 76 | * @var UnitComposition 77 | */ 78 | private $unitCompClass; 79 | 80 | private $alias; 81 | 82 | /** 83 | * @param float|int|string $value 84 | * @param string $unit 85 | */ 86 | public function __construct($value, $unit = null) 87 | { 88 | if (is_null($unit)) { 89 | $this->unit = $this->native; 90 | } else { 91 | $this->unit = $unit; 92 | } 93 | $this->value = Numbers::makeOrDont(Numbers::IMMUTABLE, $value); 94 | 95 | $this->unitCompClass = UnitComposition::getInstance(); 96 | } 97 | 98 | /** 99 | * Returns the UnitComposition class so that it can be modified or injected. 100 | * 101 | * @return UnitComposition 102 | */ 103 | public function getUnitCompositionClass() 104 | { 105 | return $this->unitCompClass; 106 | } 107 | 108 | /** 109 | * Converts the value of the current unit to its native units. 110 | * 111 | * @return Quantity 112 | */ 113 | public function toNative() 114 | { 115 | if ($this->unit == $this->native) { 116 | return $this; 117 | } 118 | 119 | return $this->to($this->native); 120 | } 121 | 122 | /** 123 | * Convert this object to another unit of measuring the same thing. For instance, meters -> feet. The value passed 124 | * to the to() method should be the string form of the unit (which is normally abbreviated, not spelled). 125 | * 126 | * @param string $unit 127 | * @return $this 128 | */ 129 | public function to($unit) 130 | { 131 | $this->value = $this->convert($this->value, $this->unit, $unit); 132 | $this->unit = $unit; 133 | 134 | return $this; 135 | } 136 | 137 | /** 138 | * Get's the conversion rate (by multiplication) between the argument unit and the native unit. 139 | * 140 | * @param string $unit 141 | * @return string 142 | * @throws \Exception 143 | */ 144 | public function getConversionRate($unit) 145 | { 146 | if (!array_key_exists($unit, $this->units)) { 147 | throw new \Exception('Cannot get conversion rate for undefined unit.'); 148 | } 149 | 150 | if (!array_key_exists($this->units[$unit], $this->rates)) { 151 | throw new \Exception('Cannot get conversion rate without defined rate.'); 152 | } 153 | 154 | return $this->rates[$this->units[$unit]]; 155 | } 156 | 157 | /** 158 | * Adds another string which can be used to reference the conversion rate of an existing unit. For instance, you 159 | * could add the verbose form 'meters' instead of just 'm' with the following: 160 | * 161 | * addAlias('meters', 'm') 162 | * 163 | * @param string $alias 164 | * @param string $unit 165 | * @return $this 166 | * @throws \Exception 167 | */ 168 | public function addAlias($alias, $unit) 169 | { 170 | if (array_key_exists($alias, $this->units)) { 171 | throw new \Exception('Cannot use '.$alias.' as an alias for '.$unit.' because '.$alias.' is already defined.'); 172 | } 173 | 174 | if (!array_key_exists($unit, $this->units)) { 175 | throw new \Exception('Cannot assign alias '.$alias.' to '.$unit.' because '.$unit.' is not yet defined.'); 176 | } 177 | 178 | $this->units[$alias] = $this->units[$unit]; 179 | 180 | return $this; 181 | } 182 | 183 | /** 184 | * Add a brand new conversion rate to this object, including the string alias it will be referenced by. 185 | * 186 | * @param string $alias The string by which you will reference this unit. Must be unique. 187 | * @param string|int|float $nativeConversion The number to multiply the native unit by to get the new unit. 188 | * 189 | * @return $this 190 | * @throws \Exception 191 | */ 192 | public function addUnit($alias, $nativeConversion) 193 | { 194 | if (array_key_exists($alias, $this->units)) { 195 | throw new \Exception('Cannot add new unit '.$alias.' because a unit with the same alias already exists.'); 196 | } 197 | 198 | $this->units[$alias] = (count($this->units)+1); 199 | 200 | $this->rates[$this->units[$alias]] = $nativeConversion; 201 | 202 | return $this; 203 | } 204 | 205 | /** 206 | * Returns the current numerical value. 207 | * 208 | * @return NumberInterface 209 | */ 210 | public function getValue() 211 | { 212 | return $this->value; 213 | } 214 | 215 | /** 216 | * Returns the current unit (in string form). 217 | * 218 | * @return string 219 | */ 220 | public function getUnit() 221 | { 222 | return $this->unit; 223 | } 224 | 225 | /** 226 | * Returns the array of the current unit types that exist in this unit object. 227 | * 228 | * @return array 229 | */ 230 | public function getUnitsPresent() 231 | { 232 | return $this->unitTypesPresent; 233 | } 234 | 235 | /** 236 | * Add a number to the value without consideration to conversion or units. 237 | * 238 | * @param string|int|float|NumberInterface $value 239 | * @return $this 240 | */ 241 | public function preConvertedAdd($value) 242 | { 243 | $this->value = $this->value->add($value); 244 | 245 | return $this; 246 | } 247 | 248 | /** 249 | * Subtract a number to the value without consideration to conversion or units. 250 | * 251 | * @param string|int|float|NumberInterface $value 252 | * @return $this 253 | */ 254 | public function preConvertedSubtract($value) 255 | { 256 | $this->value = $this->value->subtract($value); 257 | 258 | return $this; 259 | } 260 | 261 | /** 262 | * Multiply a number by the value without consideration to conversion or units. 263 | * 264 | * @param string|int|float|NumberInterface $value 265 | * @return $this 266 | */ 267 | public function preConvertedMultiply($value) 268 | { 269 | $this->value = $this->value->multiply($value); 270 | 271 | return $this; 272 | } 273 | 274 | /** 275 | * Divide a number by the value without consideration to conversion or units. 276 | * 277 | * @param string|int|float|NumberInterface $value 278 | * @param int $precision 279 | * @return $this 280 | */ 281 | public function preConvertedDivide($value, $precision = 2) 282 | { 283 | $this->value = $this->value->divide($value)->roundToPrecision($precision); 284 | 285 | return $this; 286 | } 287 | 288 | /** 289 | * Take an instance of the same unit object, convert it to the units that this unit is in, and add it to this unit. 290 | * 291 | * @param Quantity $quantity 292 | * @return $this 293 | * @throws \Exception 294 | */ 295 | public function add(Quantity $quantity) 296 | { 297 | if (get_class($this) != get_class($quantity)) { 298 | throw new \Exception('Cannot add units of two different types.'); 299 | } 300 | 301 | $oldUnit = $quantity->getUnit(); 302 | 303 | $this->value = $this->value->add($quantity->to($this->unit)->getValue()); 304 | 305 | $quantity->to($oldUnit); 306 | 307 | return $this; 308 | } 309 | 310 | /** 311 | * Take an instance of the same unit object, convert it to the units that this unit is in, and subtract it 312 | * from this unit. 313 | * 314 | * @param Quantity $quantity 315 | * @return $this 316 | * @throws \Exception 317 | */ 318 | public function subtract(Quantity $quantity) 319 | { 320 | if (get_class($this) != get_class($quantity)) { 321 | throw new \Exception('Cannot subtract units of two different types.'); 322 | } 323 | 324 | $oldUnit = $quantity->getUnit(); 325 | 326 | $this->value = $this->value->subtract($quantity->to($this->unit)->getValue()); 327 | 328 | $quantity->to($oldUnit); 329 | 330 | return $this; 331 | } 332 | 333 | /** 334 | * Take an instance of any unit and attempt to multiply. This will pass responsibility to the UnitComposition class 335 | * so that it can attempt to figure out what the resulting units should be. 336 | * 337 | * @param Quantity $quantity 338 | * @return Quantity 339 | */ 340 | public function multiplyBy(Quantity $quantity) 341 | { 342 | return $this->unitCompClass->naiveMultiply($this, $quantity); 343 | } 344 | 345 | /** 346 | * Take an instance of any unit and attempt to multiply by that unit after squaring it. This will pass 347 | * responsibility to the UnitComposition class so that it can attempt to figure out what the resulting 348 | * units should be. 349 | * 350 | * @param Quantity $quantity 351 | * @return Quantity 352 | * @throws \Exception 353 | */ 354 | public function multiplyBySquared(Quantity $quantity) 355 | { 356 | return $this->unitCompClass->naiveMultiOpt([$this, $quantity, $quantity], []); 357 | } 358 | 359 | /** 360 | * Take an instance of any unit and attempt to divide. This will pass responsibility to the UnitComposition class 361 | * so that it can attempt to figure out what the resulting units should be. 362 | * 363 | * @param Quantity $quantity 364 | * @param int $precision 365 | * @return Quantity 366 | */ 367 | public function divideBy(Quantity $quantity, $precision = 2) 368 | { 369 | return $this->unitCompClass->naiveDivide($this, $quantity, $precision); 370 | } 371 | 372 | /** 373 | * Take an instance of any unit and attempt to divide by that unit after squaring it. This will pass 374 | * responsibility to the UnitComposition class so that it can attempt to figure out what the resulting 375 | * units should be. 376 | * 377 | * @param Quantity $quantity 378 | * @param int $precision 379 | * @return Quantity 380 | * @throws \Exception 381 | */ 382 | public function divideBySquared(Quantity $quantity, $precision = 2) 383 | { 384 | return $this->unitCompClass->naiveMultiOpt([$this], [$quantity, $quantity], $precision); 385 | } 386 | 387 | /** 388 | * Attempts to take the square root of this unit. In practice it is very rare for a unit that has a common purpose 389 | * or name on its own to be rooted. Instead it is more common for the square root to occur after a series of 390 | * multiplication and division, so you may provide numerators and denominators to this method as well which will 391 | * occur BEFORE the square root is taken. 392 | * 393 | * @param Quantity[] $numerators 394 | * @param Quantity[] $denominators 395 | * @param int $precision 396 | * @return Quantity 397 | * @throws \Exception 398 | */ 399 | public function squareRoot(array $numerators = [], array $denominators = [], $precision = 2) 400 | { 401 | $numerators[] = $this; 402 | 403 | return $this->unitCompClass->naiveSquareRoot($numerators, $denominators, $precision); 404 | } 405 | 406 | /** 407 | * Return the current value and unit. 408 | * 409 | * @return string 410 | */ 411 | public function __toString() 412 | { 413 | return $this->value->getValue().' '.$this->unit; 414 | } 415 | 416 | public function useAs($alias) 417 | { 418 | 419 | } 420 | 421 | public function hasAlias($alias) 422 | { 423 | return $this->alias === $alias; 424 | } 425 | 426 | /** 427 | * 428 | * 429 | * @param NumberInterface $value 430 | * @param string $from 431 | * @param string $to 432 | * @return string 433 | * @throws \Exception 434 | */ 435 | protected function convert(NumberInterface $value, $from, $to) 436 | { 437 | if (!is_array($this->rates[$to]) && !is_array($this->rates[$from])) { 438 | // For simple, scaling conversions 439 | return $value->multiply($this->getConversionRate($from))->divide($this->getConversionRate($to)); 440 | } else { 441 | // For more complex conversions, like that between Celsius and Fahrenheit. 442 | // From and To callables must be how to get to native unit 443 | if (is_array($this->rates[$to])) { 444 | /** @var callable $toConversion */ 445 | $toConversion = $this->rates[$to]['to']; 446 | } else { 447 | $toConversion = function(NumberInterface $value) use ($to){ 448 | return $value->divide($this->getConversionRate($to)); 449 | }; 450 | } 451 | 452 | if (is_array($this->rates[$from])) { 453 | /** @var callable $fromConversion */ 454 | $fromConversion = $this->rates[$from]['from']; 455 | } else { 456 | $fromConversion = function(NumberInterface $value) use ($from){ 457 | return $value->multiply($this->getConversionRate($from)); 458 | }; 459 | } 460 | 461 | return $toConversion($fromConversion($value)); 462 | } 463 | } 464 | 465 | /** 466 | * 467 | * 468 | * @param string $key 469 | * @return $this 470 | */ 471 | protected function setComposition($key) 472 | { 473 | $this->unitTypesPresent = $this->unitCompClass->getCompArrayByName($key); 474 | 475 | return $this; 476 | } 477 | 478 | /** 479 | * 480 | * 481 | * @param array $comp 482 | * @return $this 483 | */ 484 | protected function defineComposition(array $comp) 485 | { 486 | $this->unitTypesPresent = $comp; 487 | 488 | return $this; 489 | } 490 | } -------------------------------------------------------------------------------- /src/Samsara/Newton/Core/UnitComposition.php: -------------------------------------------------------------------------------- 1 | [ 92 | 'length' => 2, 93 | 'time' => -2 94 | ], 95 | self::ACCELERATION => [ 96 | 'length' => 1, 97 | 'time' => -2 98 | ], 99 | self::AMOUNT => [ 100 | 'mol' => 1 101 | ], 102 | self::ANGULAR_ACCELERATION => [ 103 | 'planeAngle' => 1, 104 | 'time' => -2 105 | ], 106 | self::ANGULAR_VELOCITY => [ 107 | 'planeAngle' => 1, 108 | 'time' => -1 109 | ], 110 | self::AREA => [ 111 | 'length' => 2 112 | ], 113 | self::CAPACITANCE => [ 114 | 'time' => 4, 115 | 'electricCurrent' => 2, 116 | 'mass' => -1, 117 | 'length' => -2 118 | ], 119 | self::CATALYTIC_ACTIVITY => [ 120 | 'mol' => 1, 121 | 'time' => -1 122 | ], 123 | self::CHARGE => [ 124 | 'electricCurrent' => 1, 125 | 'time' => 1 126 | ], 127 | self::CONDUCTANCE_ELEC => [ 128 | 'time' => 3, 129 | 'electricCurrent' => 2, 130 | 'mass' => -1, 131 | 'length' => -2 132 | ], 133 | self::CONDUCTANCE_THERM => [ 134 | 'mass' => 1, 135 | 'length' => 1, 136 | 'time' => -3, 137 | 'temperature' => -1 138 | ], 139 | self::CURRENT => [ 140 | 'electricCurrent' => 1 141 | ], 142 | self::CYCLES => [ 143 | 'cycles' => 1 144 | ], 145 | self::DENSITY => [ 146 | 'mass' => 1, 147 | 'length' => -3 148 | ], 149 | self::ENERGY => [ 150 | 'mass' => 1, 151 | 'length' => 2, 152 | 'time' => -2 153 | ], 154 | self::FORCE => [ 155 | 'mass' => 1, 156 | 'length' => 1, 157 | 'time' => -2 158 | ], 159 | self::FREQUENCY => [ 160 | 'cycles' => 1, 161 | 'time' => -1 162 | ], 163 | self::ILLUMINATION => [ 164 | 'luminousIntensity' => 1, 165 | 'solidAngle' => 1, 166 | 'length' => -2 167 | ], 168 | self::INDUCTANCE => [ 169 | 'mass' => 1, 170 | 'length' => 2, 171 | 'time' => -2, 172 | 'electricCurrent' => -2 173 | ], 174 | self::LENGTH => [ 175 | 'length' => 1 176 | ], 177 | self::LUMINOUS_FLUX => [ 178 | 'luminousIntensity' => 1, 179 | 'solidAngle' => 1 180 | ], 181 | self::LUMINOUS_INTENSITY => [ 182 | 'luminousIntensity' => 1 183 | ], 184 | self::MAG_FLUX => [ 185 | 'mass' => 1, 186 | 'length' => 2, 187 | 'time' => -2, 188 | 'electricCurrent' => -1 189 | ], 190 | self::MAG_FLUX_DENSITY => [ 191 | 'mass' => 1, 192 | 'time' => -2, 193 | 'electricCurrent' => -1 194 | ], 195 | self::MASS => [ 196 | 'mass' => 1 197 | ], 198 | self::MOMENTUM => [ 199 | 'mass' => 1, 200 | 'length' => 1, 201 | 'time' => -1 202 | ], 203 | self::PLANE_ANGLE => [ 204 | 'planeAngle' => 1 205 | ], 206 | self::POWER => [ 207 | 'mass' => 1, 208 | 'length' => 2, 209 | 'time' => -3 210 | ], 211 | self::PRESSURE => [ 212 | 'mass' => 1, 213 | 'length' => -1, 214 | 'time' => -2 215 | ], 216 | self::RADIOACTIVITY => [ 217 | 'time' => -1 218 | ], 219 | self::RESISTANCE => [ 220 | 'mass' => 1, 221 | 'length' => 2, 222 | 'time' => -3, 223 | 'electricCurrent' => -2 224 | ], 225 | self::SOLID_ANGLE => [ 226 | 'solidAngle' => 1 227 | ], 228 | self::TEMPERATURE => [ 229 | 'temperature' => 1 230 | ], 231 | self::TIME => [ 232 | 'time' => 1 233 | ], 234 | self::VELOCITY => [ 235 | 'length' => 1, 236 | 'time' => -1 237 | ], 238 | self::VOLTAGE => [ 239 | 'mass' => 1, 240 | 'length' => 2, 241 | 'electricCurrent' => -1, 242 | 'time' => -3 243 | ], 244 | self::VOLUME => [ 245 | 'length' => 3 246 | ] 247 | ]; 248 | 249 | /** 250 | * This is where units that are added at runtime have their classname stored so that can be instantiated correctly. 251 | * 252 | * @var array 253 | */ 254 | protected $dynamicUnits = []; 255 | 256 | /** 257 | * The acceptable base composition types. 258 | * 259 | * @var array 260 | */ 261 | private $baseUnitTypes = [ 262 | 'length', 263 | 'mass', 264 | 'time', 265 | 'temperature', 266 | 'electricCurrent', 267 | 'cycles', 268 | 'luminousIntensity', 269 | 'mol', 270 | 'planeAngle', 271 | 'solidAngle' 272 | ]; 273 | 274 | /** 275 | * @var UnitComposition 276 | */ 277 | private static $instance; 278 | 279 | private function __construct() 280 | { 281 | foreach ($this->unitComp as $unit => $unitDef) { 282 | ksort($unitDef); 283 | 284 | $this->unitComp[$unit] = $unitDef; 285 | } 286 | } 287 | 288 | public static function getInstance() 289 | { 290 | if (!self::$instance) { 291 | self::$instance = new UnitComposition(); 292 | } 293 | 294 | return self::$instance; 295 | } 296 | 297 | public function getCompArrayByName($name) 298 | { 299 | if (!isset($this->unitComp[$name])) { 300 | throw new \Exception('Cannot return unit composition array for non-existent unit: '.$name); 301 | } 302 | 303 | return $this->unitComp[$name]; 304 | } 305 | 306 | /** 307 | * Add a brand new unit with class an composition. 308 | * 309 | * @param string $class 310 | * @param array $composition 311 | * @param string $key 312 | * @return $this 313 | * @throws \Exception 314 | */ 315 | public function addUnit($class, array $composition, $key) 316 | { 317 | if (array_key_exists($key, $this->unitComp)) { 318 | throw new \Exception('Cannot add unit '.$class.' with key '.$key.' because that key is already being used.'); 319 | } 320 | 321 | $this->unitComp[$key] = $composition; 322 | $this->dynamicUnits[$key] = $class; 323 | 324 | return $this; 325 | } 326 | 327 | /** 328 | * Returns the class for the set of numerators and denominators. 329 | * 330 | * @param Quantity[] $numerators 331 | * @param Quantity[] $denominators 332 | * @return Quantity 333 | */ 334 | public function getMultiUnits(array $numerators, array $denominators) 335 | { 336 | $unitComp = $this->getUnitCompArray($numerators, $denominators); 337 | 338 | return $this->getUnitCompClass($unitComp); 339 | } 340 | 341 | /** 342 | * Returns the multiplied and divided unit composition ONLY for a set of numerators and denominators. 343 | * 344 | * @param Quantity[] $numerators 345 | * @param Quantity[] $denominators 346 | * @return array 347 | */ 348 | public function getUnitCompArray(array $numerators, array $denominators) 349 | { 350 | $unitComp = []; 351 | 352 | foreach ($this->baseUnitTypes as $type) { 353 | $unitComp[$type] = 0; 354 | } 355 | 356 | foreach ($numerators as $unit) { 357 | if ($unit instanceof Quantity) { 358 | foreach ($unit->getUnitsPresent() as $unitType => $unitCount) { 359 | if ($unitCount != 0) { 360 | $unitComp[$unitType] += $unitCount; 361 | } 362 | } 363 | } 364 | } 365 | 366 | foreach ($denominators as $unit) { 367 | if ($unit instanceof Quantity) { 368 | foreach ($unit->getUnitsPresent() as $unitType => $unitCount) { 369 | if ($unitCount != 0) { 370 | $unitComp[$unitType] -= $unitCount; 371 | } 372 | } 373 | } 374 | } 375 | 376 | foreach ($unitComp as $key => $val) { 377 | if ($val == 0) { 378 | unset($unitComp[$key]); 379 | } 380 | } 381 | 382 | return $unitComp; 383 | } 384 | 385 | /** 386 | * Gets the unit class for two units which are multiplied. 387 | * 388 | * @param Quantity $unit1 389 | * @param Quantity $unit2 390 | * @return Quantity 391 | */ 392 | public function getMultipliedUnit(Quantity $unit1, Quantity $unit2) 393 | { 394 | return $this->getMultiUnits([$unit1, $unit2], []); 395 | } 396 | 397 | /** 398 | * Gets the unit class for two units which are divided. 399 | * 400 | * @param Quantity $numerator 401 | * @param Quantity $denominator 402 | * @return Quantity 403 | */ 404 | public function getDividedUnit(Quantity $numerator, Quantity $denominator) 405 | { 406 | return $this->getMultiUnits([$numerator], [$denominator]); 407 | } 408 | 409 | /** 410 | * Gets the unit class from the composition array. 411 | * 412 | * @param array $comp 413 | * @return Quantity 414 | * @throws \Exception 415 | */ 416 | public function getUnitCompClass(array $comp) 417 | { 418 | return $this->getUnitClass($this->getUnitCompName($comp)); 419 | } 420 | 421 | /** 422 | * Gets the unit name from the composition array. 423 | * 424 | * @param array $comp 425 | * @return string 426 | * @throws \Exception 427 | */ 428 | public function getUnitCompName(array $comp) 429 | { 430 | foreach ($this->unitComp as $unit => $unitDef) { 431 | ksort($comp); 432 | if ($comp === $unitDef) { 433 | return $unit; 434 | } 435 | } 436 | 437 | throw new \Exception('Cannot match the unit definition to an existing unit.'); 438 | } 439 | 440 | /** 441 | * Gets the unit class from the unit name. 442 | * 443 | * @param string $unit 444 | * @param int|NumberInterface $value 445 | * @return Quantity 446 | * @throws \Exception 447 | */ 448 | public function getUnitClass($unit, $value = 0) 449 | { 450 | switch ($unit) { 451 | case self::ACCELERATION: 452 | return new Acceleration($value); 453 | 454 | case self::CURRENT: 455 | return new Current($value); 456 | 457 | case self::AREA: 458 | return new Area($value); 459 | 460 | case self::CHARGE: 461 | return new Charge($value); 462 | 463 | case self::CYCLES: 464 | return new Cycles($value); 465 | 466 | case self::ENERGY: 467 | return new Energy($value); 468 | 469 | case self::DENSITY: 470 | return new Density($value); 471 | 472 | case self::FORCE: 473 | return new Force($value); 474 | 475 | case self::FREQUENCY: 476 | return new Frequency($value); 477 | 478 | case self::LENGTH: 479 | return new Length($value); 480 | 481 | case self::MASS: 482 | return new Mass($value); 483 | 484 | case self::MOMENTUM: 485 | return new Momentum($value); 486 | 487 | case self::POWER: 488 | return new Power($value); 489 | 490 | case self::PRESSURE: 491 | return new Pressure($value); 492 | 493 | case self::TEMPERATURE: 494 | return new Temperature($value); 495 | 496 | case self::TIME: 497 | return new Time($value); 498 | 499 | case self::VELOCITY: 500 | return new Velocity($value); 501 | 502 | case self::VOLTAGE: 503 | return new Voltage($value); 504 | 505 | case self::VOLUME: 506 | return new Volume($value); 507 | 508 | default: 509 | if (array_key_exists($unit, $this->dynamicUnits)) { 510 | $class = new \ReflectionClass($this->dynamicUnits[$unit]); 511 | 512 | $parent = $class->getParentClass(); 513 | 514 | if ($parent && ($parent->getName() == 'Samsara\\Newton\\Core\\Quantity' || $parent->getName() == 'Samsara\\Newton\\Units\\Core\\ScalarQuantity')) { 515 | return $class->newInstance($value); 516 | } else { 517 | throw new \Exception('Valid units must extend the Quantity class.'); 518 | } 519 | } 520 | throw new \Exception('Unknown unit type: '.$unit); 521 | } 522 | } 523 | 524 | /** 525 | * Alias for naiveMultiOpt where both arguments are multiplied 526 | * 527 | * @param Quantity $unit1 528 | * @param Quantity $unit2 529 | * @return Quantity 530 | * @throws \Exception 531 | */ 532 | public function naiveMultiply(Quantity $unit1, Quantity $unit2) 533 | { 534 | return $this->naiveMultiOpt([$unit1, $unit2], []); 535 | } 536 | 537 | /** 538 | * Alias for naiveMultiOpt where the first argument is divided by the second argument. 539 | * 540 | * @param Quantity $numerator 541 | * @param Quantity $denominator 542 | * @param int $precision 543 | * @return Quantity 544 | * @throws \Exception 545 | */ 546 | public function naiveDivide(Quantity $numerator, Quantity $denominator, $precision = 2) 547 | { 548 | return $this->naiveMultiOpt([$numerator], [$denominator], $precision); 549 | } 550 | 551 | /** 552 | * Takes an arbitrary number of unit objects which are to be multiplied and divided and attempts to determine both 553 | * the numerical answer, as well as what unit the answer is in, then returns an instance of the appropriate class 554 | * with the appropriate value. 555 | * 556 | * @param Quantity[] $numerators 557 | * @param Quantity[] $denominators 558 | * @param int $precision 559 | * 560 | * @return Quantity 561 | * @throws \Exception 562 | */ 563 | public function naiveMultiOpt(array $numerators, array $denominators, $precision = 2) 564 | { 565 | $newVal = $this->multiOptValue($numerators, $denominators, $precision); 566 | 567 | $newUnit = $this->getMultiUnits($numerators, $denominators); 568 | 569 | return $newUnit->preConvertedAdd($newVal); 570 | } 571 | 572 | /** 573 | * Attempts to take the square root of a set of numerators and denominators, determining both the value and unit 574 | * composition, and returning the correct unit object with the correct value. 575 | * 576 | * @param Quantity[]|int[] $numerators 577 | * @param Quantity[]|int[] $denominators 578 | * @param int $precision 579 | * 580 | * @return Quantity 581 | * @throws \Exception 582 | */ 583 | public function naiveSquareRoot(array $numerators, array $denominators, $precision = 2) 584 | { 585 | $newVal = $this->multiOptValue($numerators, $denominators, $precision); 586 | 587 | $unitComp = $this->getUnitCompArray($numerators, $denominators); 588 | 589 | $newUnitComp = []; 590 | 591 | foreach ($unitComp as $unit => $exp) { 592 | $newExp = $exp/2; 593 | if (!is_int($newExp)) { 594 | throw new \Exception('Incorrect exponents after square root.'); 595 | } 596 | $newUnitComp[$unit] = $newExp; 597 | } 598 | 599 | $newUnit = $this->getUnitCompClass($newUnitComp); 600 | 601 | return $newUnit->preConvertedAdd($newVal->sqrt()->roundToPrecision($precision)); 602 | } 603 | 604 | public function getVectorBySphericalCoords(ScalarQuantity $quantity, $azimuth, $inclination) 605 | { 606 | if ($quantity instanceof Acceleration) { 607 | return new VectorAcceleration($quantity, $azimuth, $inclination); 608 | } elseif ($quantity instanceof Force) { 609 | return new VectorForce($quantity, $azimuth, $inclination); 610 | } elseif ($quantity instanceof Momentum) { 611 | return new VectorMomentum($quantity, $azimuth, $inclination); 612 | } elseif ($quantity instanceof Velocity) { 613 | return new VectorVelocity($quantity, $azimuth, $inclination); 614 | } else { 615 | throw new \InvalidArgumentException('Non-vectorable scalar unit given.'); 616 | } 617 | } 618 | 619 | public function getVectorByCartesian(ScalarQuantity $quantity, $x, $y, $z = 0) 620 | { 621 | $azimuth = TrigonometryProvider::sphericalCartesianAzimuth($x, $y); 622 | $inclination = TrigonometryProvider::sphericalCartesianInclination($x, $y, $z); 623 | 624 | return $this->getVectorBySphericalCoords($quantity, $azimuth, $inclination); 625 | } 626 | 627 | public function getVectorByHeading(ScalarQuantity $quantity, $heading) 628 | { 629 | $parts = TrigonometryProvider::sphericalFromHeading($heading); 630 | 631 | return $this->getVectorBySphericalCoords($quantity, $parts['azimuth'], $parts['inclination']); 632 | } 633 | 634 | /** 635 | * @param array $numerators 636 | * @param array $denominators 637 | * @param int $precision 638 | * 639 | * @return NumberInterface 640 | * @throws \Exception 641 | */ 642 | protected function multiOptValue(array $numerators, array $denominators, $precision = 2) 643 | { 644 | $newVal = Numbers::make(Numbers::IMMUTABLE, 1); 645 | 646 | foreach ($numerators as $key => $quantity) { 647 | if ($quantity instanceof Quantity) { 648 | $oldUnit = $quantity->getUnit(); 649 | $newVal = $newVal->multiply($quantity->toNative()->getValue()); 650 | $quantity->to($oldUnit); 651 | } elseif (is_numeric($quantity)) { 652 | $newVal = $newVal->multiply($quantity); 653 | } else { 654 | throw new \Exception('Invalid numerator'); 655 | } 656 | } 657 | 658 | foreach ($denominators as $key => $quantity) { 659 | if ($quantity instanceof Quantity) { 660 | $oldUnit = $quantity->getUnit(); 661 | if ($quantity->getValue() == 0) { 662 | throw new \Exception('Cannot divide by zero.'); 663 | } 664 | $newVal = $newVal->divide($quantity->toNative()->getValue())->roundToPrecision($precision); 665 | $quantity->to($oldUnit); 666 | } elseif (is_numeric($quantity)) { 667 | if ($quantity == 0) { 668 | throw new \Exception('Cannot divide by zero.'); 669 | } 670 | $newVal = $newVal->divide($quantity)->roundToPrecision($precision); 671 | } else { 672 | throw new \Exception('Invalid denominator'); 673 | } 674 | } 675 | 676 | return $newVal; 677 | } 678 | 679 | } --------------------------------------------------------------------------------