Completed
Pull Request — master (#66)
by Daniel
05:43 queued 02:32
created

QuantityValue::newFromNumber()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
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.7
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.7
74
	 *
75
	 * @param string|int|float|DecimalValue|UnboundedQuantityValue $number
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 QuantityValue
81
	 * @throws IllegalValueException
82
	 */
83
	public static function newFromNumber( $number, $unit = '1', $upperBound = null, $lowerBound = null ) {
84
		$number = self::asDecimalValue( 'amount', $number );
85
		$upperBound = self::asDecimalValue( 'upperBound', $upperBound, $number );
86
		$lowerBound = self::asDecimalValue( 'lowerBound', $lowerBound, $number );
87
88
		return new self( $number, $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|UnboundedQuantityValue $number
97
	 * @param string $unit
98
	 * @param string|int|float|DecimalValue|null $upperBound
99
	 * @param string|int|float|DecimalValue|null $lowerBound
100
	 *
101
	 * @return QuantityValue
102
	 */
103
	public static function newFromDecimal( $number, $unit = '1', $upperBound = null, $lowerBound = null ) {
104
		return self::newFromNumber( $number, $unit, $upperBound, $lowerBound );
105
	}
106
107
	/**
108
	 * @see Serializable::unserialize
109
	 *
110
	 * @since 0.7
111
	 *
112
	 * @param string $data
113
	 */
114
	public function unserialize( $data ) {
115
		list( $amount, $unit, $upperBound, $lowerBound ) = unserialize( $data );
116
		$amount = DecimalValue::newFromArray( $amount );
117
		$upperBound = DecimalValue::newFromArray( $upperBound );
118
		$lowerBound = DecimalValue::newFromArray( $lowerBound );
119
		$this->__construct( $amount, $unit, $upperBound, $lowerBound );
120
	}
121
122
	/**
123
	 * Returns this quantity's upper bound.
124
	 *
125
	 * @since 0.7
126
	 *
127
	 * @return DecimalValue
128
	 */
129
	public function getUpperBound() {
130
		return $this->upperBound;
131
	}
132
133
	/**
134
	 * Returns this quantity's lower bound.
135
	 *
136
	 * @since 0.7
137
	 *
138
	 * @return DecimalValue
139
	 */
140
	public function getLowerBound() {
141
		return $this->lowerBound;
142
	}
143
144
	/**
145
	 * Returns the size of the uncertainty interval.
146
	 * This can roughly be interpreted as "amount +/- uncertainty/2".
147
	 *
148
	 * The exact interpretation of the uncertainty interval is left to the concrete application or
149
	 * data point. For example, the uncertainty interval may be defined to be that part of a
150
	 * normal distribution that is required to cover the 95th percentile.
151
	 *
152
	 * @since 0.7
153
	 *
154
	 * @return float
155
	 */
156
	public function getUncertainty() {
157
		return $this->upperBound->getValueFloat() - $this->lowerBound->getValueFloat();
158
	}
159
160
	/**
161
	 * Returns a DecimalValue representing the symmetrical offset to be applied
162
	 * to the raw amount for a rough representation of the uncertainty interval,
163
	 * as in "amount +/- offset".
164
	 *
165
	 * The offset is calculated as max( amount - lowerBound, upperBound - amount ).
166
	 *
167
	 * @since 0.7
168
	 *
169
	 * @return DecimalValue
170
	 */
171
	public function getUncertaintyMargin() {
172
		$math = new DecimalMath();
173
174
		$lowerMargin = $math->sum( $this->amount, $this->lowerBound->computeComplement() );
175
		$upperMargin = $math->sum( $this->upperBound, $this->amount->computeComplement() );
176
177
		$margin = $math->max( $lowerMargin, $upperMargin );
178
		return $margin;
179
	}
180
181
	/**
182
	 * Returns the order of magnitude of the uncertainty as the exponent of
183
	 * last significant digit in the amount-string. The value returned by this
184
	 * is suitable for use with @see DecimalMath::roundToExponent().
185
	 *
186
	 * @example: if two digits after the decimal point are significant, this
187
	 * returns -2.
188
	 *
189
	 * @example: if the last two digits before the decimal point are insignificant,
190
	 * this returns 2.
191
	 *
192
	 * Note that this calculation assumes a symmetric uncertainty interval,
193
	 * and can be misleading.
194
	 *
195
	 * @since 0.7
196
	 *
197
	 * @return int
198
	 */
199
	public function getOrderOfUncertainty() {
200
		// the desired precision is given by the distance between the amount and
201
		// whatever is closer, the upper or lower bound.
202
		//TODO: use DecimalMath to avoid floating point errors!
203
		$amount = $this->amount->getValueFloat();
204
		$upperBound = $this->upperBound->getValueFloat();
205
		$lowerBound = $this->lowerBound->getValueFloat();
206
		$precision = min( $amount - $lowerBound, $upperBound - $amount );
207
208
		if ( $precision === 0.0 ) {
209
			// If there is no uncertainty, the order of uncertainty is a bit more than what we have digits for.
210
			return -strlen( $this->amount->getFractionalPart() );
211
		}
212
213
		// e.g. +/- 200 -> 2; +/- 0.02 -> -2
214
		// note: we really want floor( log10( $precision ) ), but have to account for
215
		// small errors made in the floating point operations above.
216
		// @todo: use bcmath (via DecimalMath) to avoid this if possible
217
		$orderOfUncertainty = floor( log10( $precision + 0.0000000005 ) );
218
219
		return (int)$orderOfUncertainty;
220
	}
221
222
	/**
223
	 * Returns a transformed value derived from this QuantityValue by applying
224
	 * the given transformation to the amount and the upper and lower bounds.
225
	 * The resulting amount and bounds are rounded to the significant number of
226
	 * digits. Note that for exact quantities (with at least one bound equal to
227
	 * the amount), no rounding is applied (since they are considered to have
228
	 * infinite precision).
229
	 *
230
	 * The transformation is provided as a callback, which must implement a
231
	 * monotonously increasing, fully differentiable function mapping a DecimalValue
232
	 * to a DecimalValue. Typically, it will be a linear transformation applying a
233
	 * factor and an offset.
234
	 *
235
	 * @param string $newUnit The unit of the transformed quantity.
236
	 *
237
	 * @param callable $transformation A callback that implements the desired transformation.
238
	 *        The transformation will be called three times, once for the amount, once
239
	 *        for the lower bound, and once for the upper bound. It must return a DecimalValue.
240
	 *        The first parameter passed to $transformation is the DecimalValue to transform
241
	 *        In addition, any extra parameters passed to transform() will be passed through
242
	 *        to the transformation callback.
243
	 *
244
	 * @param mixed ... Any extra parameters will be passed to the $transformation function.
245
	 *
246
	 * @throws InvalidArgumentException
247
	 * @return QuantityValue
248
	 */
249
	public function transform( $newUnit, $transformation ) {
250
		if ( !is_callable( $transformation ) ) {
251
			throw new InvalidArgumentException( '$transformation must be callable.' );
252
		}
253
254
		if ( !is_string( $newUnit ) ) {
255
			throw new InvalidArgumentException( '$newUnit must be a string. Use "1" as the unit for unit-less quantities.' );
256
		}
257
258
		if ( $newUnit === '' ) {
259
			throw new InvalidArgumentException( '$newUnit must not be empty. Use "1" as the unit for unit-less quantities.' );
260
		}
261
262
		$oldUnit = $this->unit;
263
264
		if ( $newUnit === null ) {
265
			$newUnit = $oldUnit;
266
		}
267
268
		// Apply transformation by calling the $transform callback.
269
		// The first argument for the callback is the DataValue to transform. In addition,
270
		// any extra arguments given for transform() are passed through.
271
		$args = func_get_args();
272
		array_shift( $args );
273
274
		$args[0] = $this->amount;
275
		$amount = call_user_func_array( $transformation, $args );
276
277
		$args[0] = $this->upperBound;
278
		$upperBound = call_user_func_array( $transformation, $args );
279
280
		$args[0] = $this->lowerBound;
281
		$lowerBound = call_user_func_array( $transformation, $args );
282
283
		// use a preliminary QuantityValue to determine the significant number of digits
284
		$transformed = new self( $amount, $newUnit, $upperBound, $lowerBound );
285
		$roundingExponent = $transformed->getOrderOfUncertainty();
286
287
		// apply rounding to the significant digits
288
		$math = new DecimalMath();
289
290
		$amount = $math->roundToExponent( $amount, $roundingExponent );
291
		$upperBound = $math->roundToExponent( $upperBound, $roundingExponent );
292
		$lowerBound = $math->roundToExponent( $lowerBound, $roundingExponent );
293
294
		return new self( $amount, $newUnit, $upperBound, $lowerBound );
295
	}
296
297
	public function __toString() {
298
		return $this->amount->getValue()
299
			. '[' . $this->lowerBound->getValue()
300
			. '..' . $this->upperBound->getValue()
301
			. ']'
302
			. ( $this->unit === '1' ? '' : $this->unit );
303
	}
304
305
	/**
306
	 * @see DataValue::getArrayValue
307
	 *
308
	 * @since 0.7
309
	 *
310
	 * @return array
311
	 */
312
	public function getArrayValue() {
313
		return array(
314
			'amount' => $this->amount->getArrayValue(),
315
			'unit' => $this->unit,
316
			'upperBound' => $this->upperBound->getArrayValue(),
317
			'lowerBound' => $this->lowerBound->getArrayValue(),
318
		);
319
	}
320
321
	/**
322
	 * Constructs a new instance of the DataValue from the provided data.
323
	 * This can round-trip with @see getArrayValue
324
	 *
325
	 * @since 0.7
326
	 *
327
	 * @param mixed $data
328
	 *
329
	 * @return QuantityValue
330
	 * @throws IllegalValueException
331
	 */
332
	public static function newFromArray( $data ) {
333
		if ( !isset( $data['upperBound'] ) && isset( $data['lowerBound'] ) ) {
334
			// No bounds given, so construct an unbounded QuantityValue.
335
			return parent::newFromArray( $data );
336
		}
337
338
		self::requireArrayFields( $data, array( 'amount', 'unit', 'upperBound', 'lowerBound' ) );
339
340
		return new static(
341
			DecimalValue::newFromArray( $data['amount'] ),
342
			$data['unit'],
343
			DecimalValue::newFromArray( $data['upperBound'] ),
344
			DecimalValue::newFromArray( $data['lowerBound'] )
345
		);
346
	}
347
348
}
349