Passed
Push — master ( 2fd507...ed2d15 )
by
unknown
01:05 queued 10s
created

UnboundedQuantityValue::transform()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4.3244

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 8
cts 11
cp 0.7272
rs 9.568
c 0
b 0
f 0
cc 4
nc 3
nop 2
crap 4.3244
1
<?php
2
3
namespace DataValues;
4
5
use InvalidArgumentException;
6
7
/**
8
 * Class representing a quantity with associated unit.
9
 * The amount is stored as a @see DecimalValue object.
10
 *
11
 * @see QuantityValue for quantities with a 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.8
19
 *
20
 * @license GPL-2.0-or-later
21
 * @author Daniel Kinzler
22
 */
23
class UnboundedQuantityValue extends DataValueObject {
24
25
	/**
26
	 * The quantity's amount
27
	 *
28
	 * @var DecimalValue
29
	 */
30
	protected $amount;
31
32
	/**
33
	 * The quantity's unit identifier (use "1" for unitless quantities).
34
	 *
35
	 * @var string
36
	 */
37
	protected $unit;
38
39
	/**
40
	 * @param DecimalValue $amount
41
	 * @param string $unit A unit identifier. Must not be empty, use "1" for unit-less quantities.
42
	 *
43
	 * @throws IllegalValueException
44
	 */
45 32
	public function __construct( DecimalValue $amount, $unit ) {
46 32
		if ( !is_string( $unit ) || $unit === '' ) {
47 2
			throw new IllegalValueException( '$unit must be a non-empty string. Use "1" for unit-less quantities.' );
48
		}
49
50 30
		$this->amount = $amount;
51 30
		$this->unit = $unit;
52 30
	}
53
54
	/**
55
	 * Returns a QuantityValue representing the given amount.
56
	 *
57
	 * This is a convenience wrapper around the constructor that accepts native values
58
	 * instead of DecimalValue objects.
59
	 *
60
	 * @note if the amount or a bound is given as a string, the string must conform
61
	 * to the rules defined by @see DecimalValue.
62
	 *
63
	 * @param string|int|float|DecimalValue $amount
64
	 * @param string $unit A unit identifier. Must not be empty, use "1" for unit-less quantities.
65
	 *
66
	 * @return self
67
	 * @throws InvalidArgumentException
68
	 */
69 7
	public static function newFromNumber( $amount, $unit = '1' ) {
70 7
		$amount = self::asDecimalValue( 'amount', $amount );
71
72 7
		return new self( $amount, $unit );
73
	}
74
75
	/**
76
	 * Converts $number to a DecimalValue if possible and necessary.
77
	 *
78
	 * @note if the $number is given as a string, it must conform to the rules
79
	 *        defined by @see DecimalValue.
80
	 *
81
	 * @param string $name The variable name to use in exception messages
82
	 * @param string|int|float|DecimalValue|null $number
83
	 * @param DecimalValue|null $default
84
	 *
85
	 * @throws InvalidArgumentException
86
	 * @return DecimalValue
87
	 */
88 7
	protected static function asDecimalValue( $name, $number, DecimalValue $default = null ) {
89 7
		if ( !is_string( $name ) ) {
90
			throw new InvalidArgumentException( '$name must be a string' );
91
		}
92
93 7
		if ( $number === null ) {
94
			if ( $default === null ) {
95
				throw new InvalidArgumentException( '$' . $name . ' must not be null' );
96
			}
97
98
			$number = $default;
99
		}
100
101 7
		if ( $number instanceof DecimalValue ) {
102
			// nothing to do
103 6
		} elseif ( is_int( $number ) || is_float( $number ) || is_string( $number ) ) {
104 6
			$number = new DecimalValue( $number );
105
		} else {
106
			throw new IllegalValueException( '$' . $name . '  must be a string, int, or float' );
107
		}
108
109 7
		return $number;
110
	}
111
112
	/**
113
	 * @see Serializable::serialize
114
	 *
115
	 * @return string
116
	 */
117 9
	public function serialize() {
118 9
		return serialize( [
119 9
			$this->amount,
120 9
			$this->unit
121
		] );
122
	}
123
124
	/**
125
	 * @see Serializable::unserialize
126
	 *
127
	 * @param string $data
128
	 */
129 9
	public function unserialize( $data ) {
130 9
		list( $amount, $unit ) = unserialize( $data );
131 9
		$this->__construct( $amount, $unit );
132 9
	}
133
134
	/**
135
	 * @see DataValue::getType
136
	 *
137
	 * @return string
138
	 */
139 15
	public static function getType() {
140 15
		return 'quantity';
141
	}
142
143
	/**
144
	 * @see DataValue::getSortKey
145
	 *
146
	 * @return float
147
	 */
148 3
	public function getSortKey() {
149 3
		return $this->amount->getValueFloat();
150
	}
151
152
	/**
153
	 * Returns the quantity object.
154
	 * @see DataValue::getValue
155
	 *
156
	 * @return self
157
	 */
158 6
	public function getValue() {
159 6
		return $this;
160
	}
161
162
	/**
163
	 * Returns the amount represented by this quantity.
164
	 *
165
	 * @return DecimalValue
166
	 */
167 20
	public function getAmount() {
168 20
		return $this->amount;
169
	}
170
171
	/**
172
	 * Returns the unit held by this quantity.
173
	 * Unit-less quantities should use "1" as their unit.
174
	 *
175
	 * @return string
176
	 */
177 10
	public function getUnit() {
178 10
		return $this->unit;
179
	}
180
181
	/**
182
	 * Returns a transformed value derived from this QuantityValue by applying
183
	 * the given transformation to the amount and the upper and lower bounds.
184
	 * The resulting amount and bounds are rounded to the significant number of
185
	 * digits. Note that for exact quantities (with at least one bound equal to
186
	 * the amount), no rounding is applied (since they are considered to have
187
	 * infinite precision).
188
	 *
189
	 * The transformation is provided as a callback, which must implement a
190
	 * monotonously increasing, fully differentiable function mapping a DecimalValue
191
	 * to a DecimalValue. Typically, it will be a linear transformation applying a
192
	 * factor and an offset.
193
	 *
194
	 * @param string $newUnit The unit of the transformed quantity.
195
	 *
196
	 * @param callable $transformation A callback that implements the desired transformation.
197
	 *        The transformation will be called three times, once for the amount, once
198
	 *        for the lower bound, and once for the upper bound. It must return a DecimalValue.
199
	 *        The first parameter passed to $transformation is the DecimalValue to transform
200
	 *        In addition, any extra parameters passed to transform() will be passed through
201
	 *        to the transformation callback.
202
	 *
203
	 * @param mixed ... Any extra parameters will be passed to the $transformation function.
204
	 *
205
	 * @todo Should be factored out into a separate QuantityMath class.
206
	 *
207
	 * @throws InvalidArgumentException
208
	 * @return self
209
	 */
210 7
	public function transform( $newUnit, $transformation ) {
211 7
		if ( !is_callable( $transformation ) ) {
212
			throw new InvalidArgumentException( '$transformation must be callable.' );
213
		}
214
215 7
		if ( !is_string( $newUnit ) || $newUnit === '' ) {
216
			throw new InvalidArgumentException(
217
				'$newUnit must be a non-empty string. Use "1" for unit-less quantities.'
218
			);
219
		}
220
221
		// Apply transformation by calling the $transform callback.
222
		// The first argument for the callback is the DataValue to transform. In addition,
223
		// any extra arguments given for transform() are passed through.
224 7
		$args = func_get_args();
225 7
		array_shift( $args );
226
227 7
		$args[0] = $this->amount;
228 7
		$amount = call_user_func_array( $transformation, $args );
229
230 7
		return new self( $amount, $newUnit );
231
	}
232
233 2
	public function __toString() {
234 2
		return $this->amount->getValue()
235 2
			. ( $this->unit === '1' ? '' : $this->unit );
236
	}
237
238
	/**
239
	 * @see DataValue::getArrayValue
240
	 *
241
	 * @return array
242
	 */
243 15
	public function getArrayValue() {
244
		return [
245 15
			'amount' => $this->amount->getArrayValue(),
246 15
			'unit' => $this->unit,
247
		];
248
	}
249
250
	/**
251
	 * Static helper capable of constructing both unbounded and bounded quantity value objects,
252
	 * depending on the serialization provided. Required for @see DataValueDeserializer.
253
	 * This is expected to round-trip with both @see getArrayValue as well as
254
	 * @see QuantityValue::getArrayValue.
255
	 *
256
	 * @deprecated since 0.8.3. Static DataValue::newFromArray constructors like this are
257
	 *  underspecified (not in the DataValue interface), and misleadingly named (should be named
258
	 *  newFromArrayValue). Instead, use DataValue builder callbacks in @see DataValueDeserializer.
259
	 *
260
	 * @param mixed $data Warning! Even if this is expected to be a value as returned by
261
	 *  @see getArrayValue, callers of this specific newFromArray implementation can not guarantee
262
	 *  this. This is not even guaranteed to be an array!
263
	 *
264
	 * @throws IllegalValueException if $data is not in the expected format. Subclasses of
265
	 *  InvalidArgumentException are expected and properly handled by @see DataValueDeserializer.
266
	 * @return self|QuantityValue Either an unbounded or bounded quantity value object.
267
	 */
268
	public static function newFromArray( $data ) {
269
		self::requireArrayFields( $data, [ 'amount', 'unit' ] );
270
271
		if ( !isset( $data['upperBound'] ) && !isset( $data['lowerBound'] ) ) {
272
			return new self(
273
				DecimalValue::newFromArray( $data['amount'] ),
0 ignored issues
show
Deprecated Code introduced by
The method DataValues\DecimalValue::newFromArray() has been deprecated with message: since 0.8.3. Static DataValue::newFromArray constructors like this are underspecified (not in the DataValue interface), and misleadingly named (should be named newFromArrayValue). Instead, use DataValue builder callbacks in @see DataValueDeserializer.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
274
				$data['unit']
275
			);
276
		} else {
277
			self::requireArrayFields( $data, [ 'upperBound', 'lowerBound' ] );
278
279
			return new QuantityValue(
280
				DecimalValue::newFromArray( $data['amount'] ),
0 ignored issues
show
Deprecated Code introduced by
The method DataValues\DecimalValue::newFromArray() has been deprecated with message: since 0.8.3. Static DataValue::newFromArray constructors like this are underspecified (not in the DataValue interface), and misleadingly named (should be named newFromArrayValue). Instead, use DataValue builder callbacks in @see DataValueDeserializer.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
281
				$data['unit'],
282
				DecimalValue::newFromArray( $data['upperBound'] ),
0 ignored issues
show
Deprecated Code introduced by
The method DataValues\DecimalValue::newFromArray() has been deprecated with message: since 0.8.3. Static DataValue::newFromArray constructors like this are underspecified (not in the DataValue interface), and misleadingly named (should be named newFromArrayValue). Instead, use DataValue builder callbacks in @see DataValueDeserializer.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
283
				DecimalValue::newFromArray( $data['lowerBound'] )
0 ignored issues
show
Deprecated Code introduced by
The method DataValues\DecimalValue::newFromArray() has been deprecated with message: since 0.8.3. Static DataValue::newFromArray constructors like this are underspecified (not in the DataValue interface), and misleadingly named (should be named newFromArrayValue). Instead, use DataValue builder callbacks in @see DataValueDeserializer.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
284
			);
285
		}
286
	}
287
288
	/**
289
	 * @see Comparable::equals
290
	 *
291
	 * @param mixed $target
292
	 *
293
	 * @return bool
294
	 */
295 12
	public function equals( $target ) {
296 12
		if ( $this === $target ) {
297 3
			return true;
298
		}
299
300 12
		return $target instanceof self
301 12
			&& $this->toArray() === $target->toArray();
302
	}
303
304
}
305