Test Failed
Push — BoundedQuantityValue ( 72482a...61280d )
by Daniel
02:23
created

QuantityValue::newFromNumber()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 5
nc 1
nop 4
1
<?php
2
3
namespace DataValues;
4
5
use InvalidArgumentException;
6
7
/**
8
 * Class representing a quantity with associated unit and uncertainty interval.
9
 * The amount is stored as a @see DecimalValue object.
10
 *
11
 * @see UnboundedQuantityValue For quantities with no known uncertainty interval.
12
 * For simple numeric amounts use @see NumberValue.
13
 *
14
 * @note UnboundedQuantityValue and QuantityValue both use the value type ID "quantity".
15
 * The fact that we use subclassing to model the bounded vs the unbounded case should be
16
 * considered an implementation detail.
17
 *
18
 * @since 0.1
19
 *
20
 * @license GPL-2.0+
21
 * @author Daniel Kinzler
22
 */
23
class QuantityValue extends UnboundedQuantityValue {
24
25
	/**
26
	 * The quantity's upper bound
27
	 *
28
	 * @var DecimalValue
29
	 */
30
	private $upperBound;
31
32
	/**
33
	 * The quantity's lower bound
34
	 *
35
	 * @var DecimalValue
36
	 */
37
	private $lowerBound;
38
39
	/**
40
	 * @param DecimalValue $amount
41
	 * @param string $unit A unit identifier. Must not be empty, use "1" for unit-less quantities.
42
	 * @param DecimalValue $upperBound The upper bound of the quantity, inclusive.
43
	 * @param DecimalValue $lowerBound The lower bound of the quantity, inclusive.
44
	 *
45
	 * @throws IllegalValueException
46
	 */
47
	public function __construct( DecimalValue $amount, $unit, DecimalValue $upperBound, DecimalValue $lowerBound ) {
48
		parent::__construct( $amount, $unit );
49
50
		if ( $lowerBound->compare( $amount ) > 0 ) {
0 ignored issues
show
Documentation introduced by
$amount is of type object<DataValues\DecimalValue>, but the function expects a object<self>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
51
			throw new IllegalValueException( '$lowerBound ' . $lowerBound->getValue() . ' must be <= $amount ' . $amount->getValue() );
52
		}
53
54
		if ( $upperBound->compare( $amount ) < 0 ) {
0 ignored issues
show
Documentation introduced by
$amount is of type object<DataValues\DecimalValue>, but the function expects a object<self>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
55
			throw new IllegalValueException( '$upperBound ' . $upperBound->getValue() . ' must be >= $amount ' . $amount->getValue() );
56
		}
57
58
		$this->upperBound = $upperBound;
59
		$this->lowerBound = $lowerBound;
60
	}
61
62
	/**
63
	 * Returns a QuantityValue representing the given amount.
64
	 * If no upper or lower bound is given, the amount is assumed to be absolutely exact,
65
	 * that is, the amount itself will be used as the upper and lower bound.
66
	 *
67
	 * This is a convenience wrapper around the constructor that accepts native values
68
	 * instead of DecimalValue objects.
69
	 *
70
	 * @note: if the amount or a bound is given as a string, the string must conform
71
	 * to the rules defined by @see DecimalValue.
72
	 *
73
	 * @since 0.1
74
	 *
75
	 * @param string|int|float|DecimalValue $amount
76
	 * @param string $unit A unit identifier. Must not be empty, use "1" for unit-less quantities.
77
	 * @param string|int|float|DecimalValue|null $upperBound
78
	 * @param string|int|float|DecimalValue|null $lowerBound
79
	 *
80
	 * @return self
81
	 * @throws IllegalValueException
82
	 */
83
	public static function newFromNumber( $amount, $unit = '1', $upperBound = null, $lowerBound = null ) {
84
		$amount = self::asDecimalValue( 'amount', $amount );
85
		$upperBound = self::asDecimalValue( 'upperBound', $upperBound, $amount );
86
		$lowerBound = self::asDecimalValue( 'lowerBound', $lowerBound, $amount );
87
88
		return new self( $amount, $unit, $upperBound, $lowerBound );
89
	}
90
91
	/**
92
	 * @see newFromNumber
93
	 *
94
	 * @deprecated since 0.1, use newFromNumber instead
95
	 *
96
	 * @param string|int|float|DecimalValue $amount
97
	 * @param string $unit
98
	 * @param string|int|float|DecimalValue|null $upperBound
99
	 * @param string|int|float|DecimalValue|null $lowerBound
100
	 *
101
	 * @return self
102
	 */
103
	public static function newFromDecimal( $amount, $unit = '1', $upperBound = null, $lowerBound = null ) {
104
		return self::newFromNumber( $amount, $unit, $upperBound, $lowerBound );
105
	}
106
107
	/**
108
	 * @see Serializable::serialize
109
	 *
110
	 * @since 0.1
111
	 *
112
	 * @return string
113
	 */
114
	public function serialize() {
115
		return serialize( array(
116
			$this->amount,
117
			$this->unit,
118
			$this->upperBound,
119
			$this->lowerBound,
120
		) );
121
	}
122
123
	/**
124
	 * @see Serializable::unserialize
125
	 *
126
	 * @since 0.1
127
	 *
128
	 * @param string $data
129
	 */
130
	public function unserialize( $data ) {
131
		list( $amount, $unit, $upperBound, $lowerBound ) = unserialize( $data );
132
		$this->__construct( $amount, $unit, $upperBound, $lowerBound );
133
	}
134
135
	/**
136
	 * Returns this quantity's upper bound.
137
	 *
138
	 * @since 0.1
139
	 *
140
	 * @return DecimalValue
141
	 */
142
	public function getUpperBound() {
143
		return $this->upperBound;
144
	}
145
146
	/**
147
	 * Returns this quantity's lower bound.
148
	 *
149
	 * @since 0.1
150
	 *
151
	 * @return DecimalValue
152
	 */
153
	public function getLowerBound() {
154
		return $this->lowerBound;
155
	}
156
157
	/**
158
	 * Returns the size of the uncertainty interval.
159
	 * This can roughly be interpreted as "amount +/- uncertainty/2".
160
	 *
161
	 * The exact interpretation of the uncertainty interval is left to the concrete application or
162
	 * data point. For example, the uncertainty interval may be defined to be that part of a
163
	 * normal distribution that is required to cover the 95th percentile.
164
	 *
165
	 * @since 0.1
166
	 *
167
	 * @return float
168
	 */
169
	public function getUncertainty() {
170
		return $this->upperBound->getValueFloat() - $this->lowerBound->getValueFloat();
171
	}
172
173
	/**
174
	 * Returns a DecimalValue representing the symmetrical offset to be applied
175
	 * to the raw amount for a rough representation of the uncertainty interval,
176
	 * as in "amount +/- offset".
177
	 *
178
	 * The offset is calculated as max( amount - lowerBound, upperBound - amount ).
179
	 *
180
	 * @todo Should be factored out into a separate QuantityMath class.
181
	 *
182
	 * @since 0.1
183
	 *
184
	 * @return DecimalValue
185
	 */
186
	public function getUncertaintyMargin() {
187
		$math = new DecimalMath();
188
189
		$lowerMargin = $math->sum( $this->amount, $this->lowerBound->computeComplement() );
190
		$upperMargin = $math->sum( $this->upperBound, $this->amount->computeComplement() );
191
192
		$margin = $math->max( $lowerMargin, $upperMargin );
193
		return $margin;
194
	}
195
196
	/**
197
	 * Returns the order of magnitude of the uncertainty as the exponent of
198
	 * last significant digit in the amount-string. The value returned by this
199
	 * is suitable for use with @see DecimalMath::roundToExponent().
200
	 *
201
	 * @example: if two digits after the decimal point are significant, this
202
	 * returns -2.
203
	 *
204
	 * @example: if the last two digits before the decimal point are insignificant,
205
	 * this returns 2.
206
	 *
207
	 * Note that this calculation assumes a symmetric uncertainty interval,
208
	 * and can be misleading.
209
	 *
210
	 * @todo Should be factored out into a separate QuantityMath class.
211
	 *
212
	 * @since 0.1
213
	 *
214
	 * @return int
215
	 */
216
	public function getOrderOfUncertainty() {
217
		// the desired precision is given by the distance between the amount and
218
		// whatever is closer, the upper or lower bound.
219
		//TODO: use DecimalMath to avoid floating point errors!
220
		$amount = $this->amount->getValueFloat();
221
		$upperBound = $this->upperBound->getValueFloat();
222
		$lowerBound = $this->lowerBound->getValueFloat();
223
		$precision = min( $amount - $lowerBound, $upperBound - $amount );
224
225
		if ( $precision === 0.0 ) {
226
			// If there is no uncertainty, the order of uncertainty is a bit more than what we have digits for.
227
			return -strlen( $this->amount->getFractionalPart() );
228
		}
229
230
		// e.g. +/- 200 -> 2; +/- 0.02 -> -2
231
		// note: we really want floor( log10( $precision ) ), but have to account for
232
		// small errors made in the floating point operations above.
233
		// @todo: use bcmath (via DecimalMath) to avoid this if possible
234
		$orderOfUncertainty = floor( log10( $precision + 0.0000000005 ) );
235
236
		return (int)$orderOfUncertainty;
237
	}
238
239
	/**
240
	 * Returns the number of significant figures in the amount-string,
241
	 * counting the decimal point, but not counting the leading sign.
242
	 *
243
	 * Note that this calculation assumes a symmetric uncertainty interval, and can be misleading
244
	 *
245
	 * @since 0.1
246
	 *
247
	 * @return int
248
	 */
249
	public function getSignificantFigures() {
250
		$math = new DecimalMath();
251
252
		// $orderOfUncertainty is +/- 200 -> 2; +/- 0.02 -> -2
253
		$orderOfUncertainty = $this->getOrderOfUncertainty();
254
255
		// the number of digits (without the sign) is the same as the position (with the sign).
256
		$significantDigits = $math->getPositionForExponent( $orderOfUncertainty, $this->amount );
257
258
		return $significantDigits;
259
	}
260
261
	/**
262
	 * Returns the unit held by this quantity.
263
	 * Unit-less quantities should use "1" as their unit.
264
	 *
265
	 * @since 0.1
266
	 *
267
	 * @return string
268
	 */
269
	public function getUnit() {
270
		return $this->unit;
271
	}
272
273
	/**
274
	 * Returns a transformed value derived from this QuantityValue by applying
275
	 * the given transformation to the amount and the upper and lower bounds.
276
	 * The resulting amount and bounds are rounded to the significant number of
277
	 * digits. Note that for exact quantities (with at least one bound equal to
278
	 * the amount), no rounding is applied (since they are considered to have
279
	 * infinite precision).
280
	 *
281
	 * The transformation is provided as a callback, which must implement a
282
	 * monotonously increasing, fully differentiable function mapping a DecimalValue
283
	 * to a DecimalValue. Typically, it will be a linear transformation applying a
284
	 * factor and an offset.
285
	 *
286
	 * @param string $newUnit The unit of the transformed quantity.
287
	 *
288
	 * @param callable $transformation A callback that implements the desired transformation.
289
	 *        The transformation will be called three times, once for the amount, once
290
	 *        for the lower bound, and once for the upper bound. It must return a DecimalValue.
291
	 *        The first parameter passed to $transformation is the DecimalValue to transform
292
	 *        In addition, any extra parameters passed to transform() will be passed through
293
	 *        to the transformation callback.
294
	 *
295
	 * @param mixed ... Any extra parameters will be passed to the $transformation function.
296
	 *
297
	 * @todo share more code with UnboundQuantityValue::transform.
298
	 * @todo Should be factored out into a separate QuantityMath class.
299
	 *
300
	 * @throws InvalidArgumentException
301
	 * @return self
302
	 */
303
	public function transform( $newUnit, $transformation ) {
304
		if ( !is_callable( $transformation ) ) {
305
			throw new InvalidArgumentException( '$transformation must be callable.' );
306
		}
307
308
		if ( !is_string( $newUnit ) ) {
309
			throw new InvalidArgumentException( '$newUnit must be a string. Use "1" as the unit for unit-less quantities.' );
310
		}
311
312
		if ( $newUnit === '' ) {
313
			throw new InvalidArgumentException( '$newUnit must not be empty. Use "1" as the unit for unit-less quantities.' );
314
		}
315
316
		$oldUnit = $this->unit;
317
318
		if ( $newUnit === null ) {
319
			$newUnit = $oldUnit;
320
		}
321
322
		// Apply transformation by calling the $transform callback.
323
		// The first argument for the callback is the DataValue to transform. In addition,
324
		// any extra arguments given for transform() are passed through.
325
		$args = func_get_args();
326
		array_shift( $args );
327
328
		$args[0] = $this->amount;
329
		$amount = call_user_func_array( $transformation, $args );
330
331
		$args[0] = $this->upperBound;
332
		$upperBound = call_user_func_array( $transformation, $args );
333
334
		$args[0] = $this->lowerBound;
335
		$lowerBound = call_user_func_array( $transformation, $args );
336
337
		// use a preliminary QuantityValue to determine the significant number of digits
338
		$transformed = new self( $amount, $newUnit, $upperBound, $lowerBound );
339
		$roundingExponent = $transformed->getOrderOfUncertainty();
340
341
		// apply rounding to the significant digits
342
		$math = new DecimalMath();
343
344
		$amount = $math->roundToExponent( $amount, $roundingExponent );
345
		$upperBound = $math->roundToExponent( $upperBound, $roundingExponent );
346
		$lowerBound = $math->roundToExponent( $lowerBound, $roundingExponent );
347
348
		return new self( $amount, $newUnit, $upperBound, $lowerBound );
349
	}
350
351
	public function __toString() {
352
		return $this->amount->getValue()
353
			. '[' . $this->lowerBound->getValue()
354
			. '..' . $this->upperBound->getValue()
355
			. ']'
356
			. ( $this->unit === '1' ? '' : $this->unit );
357
	}
358
359
	/**
360
	 * @see DataValue::getArrayValue
361
	 *
362
	 * @since 0.1
363
	 *
364
	 * @return array
365
	 */
366
	public function getArrayValue() {
367
		return array(
368
			'amount' => $this->amount->getArrayValue(),
369
			'unit' => $this->unit,
370
			'upperBound' => $this->upperBound->getArrayValue(),
371
			'lowerBound' => $this->lowerBound->getArrayValue(),
372
		);
373
	}
374
375
	/**
376
	 * Constructs a new instance of the DataValue from the provided data.
377
	 * This can round-trip with @see getArrayValue
378
	 *
379
	 * @note: if the upperBound or lowerBound field is missing from $data,
380
	 * this returns an UnboundedQuantityValue, not a QuantityValue!
381
	 *
382
	 * @since 0.1
383
	 *
384
	 * @param mixed $data
385
	 *
386
	 * @return UnboundedQuantityValue
387
	 * @throws IllegalValueException
388
	 */
389
	public static function newFromArray( $data ) {
390
		if ( !isset( $data['upperBound'] ) && !isset( $data['lowerBound'] ) ) {
391
			// No bounds given, so construct an unbounded QuantityValue.
392
			return parent::newFromArray( $data );
393
		}
394
395
		self::requireArrayFields( $data, array( 'amount', 'unit', 'upperBound', 'lowerBound' ) );
396
397
		return new self(
398
			DecimalValue::newFromArray( $data['amount'] ),
399
			$data['unit'],
400
			DecimalValue::newFromArray( $data['upperBound'] ),
401
			DecimalValue::newFromArray( $data['lowerBound'] )
402
		);
403
	}
404
405
}
406