Completed
Push — BoundedQuantityValue ( 544562...86948c )
by Daniel
05:19 queued 02:55
created

QuantityFormatter::formatNumber()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 1
Metric Value
c 4
b 1
f 1
dl 0
loc 26
rs 8.439
cc 5
eloc 16
nc 6
nop 1
1
<?php
2
3
namespace ValueFormatters;
4
5
use DataValues\DecimalMath;
6
use DataValues\DecimalValue;
7
use DataValues\QuantityValue;
8
use DataValues\UnboundedQuantityValue;
9
use InvalidArgumentException;
10
11
/**
12
 * Plain text formatter for quantity values.
13
 *
14
 * @since 0.1
15
 *
16
 * @license GPL-2.0+
17
 * @author Daniel Kinzler
18
 * @author Thiemo Mättig
19
 */
20
class QuantityFormatter extends ValueFormatterBase {
21
22
	/**
23
	 * Option key for enabling or disabling output of the uncertainty margin (e.g. "+/-5").
24
	 * Per default, the uncertainty margin is included in the output.
25
	 * This option must have a boolean value.
26
	 */
27
	const OPT_SHOW_UNCERTAINTY_MARGIN = 'showQuantityUncertaintyMargin';
28
29
	/**
30
	 * Value for the OPT_SHOW_UNCERTAINTY_MARGIN indicating that the uncertainty margin
31
	 * should not be shown.
32
	 */
33
	const SHOW_UNCERTAINTY_MARGIN_NEVER = 'never';
34
35
	/**
36
	 * Value for the OPT_SHOW_UNCERTAINTY_MARGIN indicating that the uncertainty margin
37
	 * should be shown if we are displaying a QuantityValue.
38
	 */
39
	const SHOW_UNCERTAINTY_MARGIN_IF_KNOWN = 'if-known';
40
41
	/**
42
	 * Value for the OPT_SHOW_UNCERTAINTY_MARGIN indicating that the uncertainty margin
43
	 * should be shown if we are displaying a non-exact QuantityValue.
44
	 */
45
	const SHOW_UNCERTAINTY_MARGIN_IF_NOT_ZERO = 'if-not-zero';
46
47
	/**
48
	 * Option key for determining what level of rounding to apply to the numbers
49
	 * included in the output. The value of this option must be an integer or a boolean.
50
	 *
51
	 * If an integer is given, this is the exponent of the last significant decimal digits
52
	 * - that is, -2 would round to two digits after the decimal point, and 1 would round
53
	 * to two digits before the decimal point. 0 would indicate rounding to integers.
54
	 *
55
	 * If the value is a boolean, false means no rounding at all (useful e.g. in diffs),
56
	 * and true means automatic rounding based on what $quantity->getOrderOfUncertainty()
57
	 * returns.
58
	 */
59
	const OPT_APPLY_ROUNDING = 'applyRounding';
60
61
	/**
62
	 * Option key controlling whether the quantity's unit of measurement should be included
63
	 * in the output.
64
	 *
65
	 * @since 0.5
66
	 */
67
	const OPT_APPLY_UNIT = 'applyUnit';
68
69
	/**
70
	 * @var DecimalMath
71
	 */
72
	private $decimalMath;
73
74
	/**
75
	 * @var DecimalFormatter
76
	 */
77
	private $decimalFormatter;
78
79
	/**
80
	 * @var ValueFormatter|null
81
	 */
82
	private $vocabularyUriFormatter;
83
84
	/**
85
	 * @var string
86
	 */
87
	private $quantityWithUnitFormat;
88
89
	/**
90
	 * @since 0.6
91
	 *
92
	 * @param FormatterOptions|null $options
93
	 * @param DecimalFormatter|null $decimalFormatter
94
	 * @param ValueFormatter|null $vocabularyUriFormatter
95
	 * @param string|null $quantityWithUnitFormat Format string with two placeholders, $1 for the
96
	 * number and $2 for the unit. Warning, this must be under the control of the application, not
97
	 * under the control of the user, because it allows HTML injections in subclasses that return
98
	 * HTML.
99
	 */
100
	public function __construct(
101
		FormatterOptions $options = null,
102
		DecimalFormatter $decimalFormatter = null,
103
		ValueFormatter $vocabularyUriFormatter = null,
104
		$quantityWithUnitFormat = null
105
	) {
106
		parent::__construct( $options );
107
108
		$this->defaultOption(
109
			self::OPT_SHOW_UNCERTAINTY_MARGIN,
110
			self::SHOW_UNCERTAINTY_MARGIN_IF_KNOWN
111
		);
112
		$this->defaultOption( self::OPT_APPLY_ROUNDING, true );
113
		$this->defaultOption( self::OPT_APPLY_UNIT, true );
114
115
		$this->decimalFormatter = $decimalFormatter ?: new DecimalFormatter( $this->options );
116
		$this->vocabularyUriFormatter = $vocabularyUriFormatter;
117
		$this->quantityWithUnitFormat = $quantityWithUnitFormat ?: '$1 $2';
118
119
		// plain composition should be sufficient
120
		$this->decimalMath = new DecimalMath();
121
	}
122
123
	/**
124
	 * @since 0.6
125
	 *
126
	 * @return string
127
	 */
128
	final protected function getQuantityWithUnitFormat() {
129
		return $this->quantityWithUnitFormat;
130
	}
131
132
	/**
133
	 * @see ValueFormatter::format
134
	 *
135
	 * @param UnboundedQuantityValue $value
136
	 *
137
	 * @throws InvalidArgumentException
138
	 * @return string Text
139
	 */
140
	public function format( $value ) {
141
		if ( !( $value instanceof UnboundedQuantityValue ) ) {
142
			throw new InvalidArgumentException( 'Data value type mismatch. Expected a QuantityValue.' );
143
		}
144
145
		return $this->formatQuantityValue( $value );
146
	}
147
148
	/**
149
	 * @since 0.6
150
	 *
151
	 * @param UnboundedQuantityValue $quantity
152
	 *
153
	 * @return string Text
154
	 */
155
	protected function formatQuantityValue( UnboundedQuantityValue $quantity ) {
156
		$formatted = $this->formatNumber( $quantity );
157
		$unit = $this->formatUnit( $quantity->getUnit() );
158
159
		if ( $unit !== null ) {
160
			$formatted = strtr(
161
				$this->quantityWithUnitFormat,
162
				array(
163
					'$1' => $formatted,
164
					'$2' => $unit
165
				)
166
			);
167
		}
168
169
		return $formatted;
170
	}
171
172
	/**
173
	 * @since 0.6
174
	 *
175
	 * @param UnboundedQuantityValue $quantity
176
	 *
177
	 * @return string Text
178
	 */
179
	protected function formatNumber( UnboundedQuantityValue $quantity ) {
180
		$roundingMode = $this->options->getOption( self::OPT_APPLY_ROUNDING );
181
		$roundingExponent = $this->getRoundingExponent( $quantity, $roundingMode );
182
183
		$amount = $quantity->getAmount();
184
185
		if ( $roundingExponent === null ) {
186
			$formatted = $this->formatMinimalDecimal( $amount );
187
			$margin = $quantity->getUncertaintyMargin();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DataValues\UnboundedQuantityValue as the method getUncertaintyMargin() does only exist in the following sub-classes of DataValues\UnboundedQuantityValue: DataValues\QuantityValue. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
188
			$margin = $margin->isZero() ? null : $this->formatMinimalDecimal( $margin );
0 ignored issues
show
Unused Code introduced by
$margin is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
189
		} else {
190
			$roundedAmount = $this->decimalMath->roundToExponent( $amount, $roundingExponent );
191
			$formatted = $this->decimalFormatter->format( $roundedAmount );
192
		if ( $quantity instanceof QuantityValue ) {
193
			// TODO: strip trailing zeros from margin
194
			$margin = $this->formatMargin( $quantity->getUncertaintyMargin(), $roundingExponent );
195
		}
196
197
			if ( $margin !== null ) {
198
				// TODO: use localizable pattern for constructing the output.
199
				$formatted .= '±' . $margin;
0 ignored issues
show
Bug introduced by
The variable $margin does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
200
			}
201
		}
202
203
		return $formatted;
204
	}
205
206
	/**
207
	 * Returns the rounding exponent based on the given $quantity.
208
	 *
209
	 * @param UnboundedQuantityValue $quantity
210
	 * @param bool|int $roundingMode The rounding exponent, or true for rounding to the order of
211
	 *        uncertainty (significant digits) of a QuantityValue, or false to not apply
212
	 *        rounding (that is, round to all digits).
213
	 *
214
	 * @return int|null
215
	 */
216
	private function getRoundingExponent( UnboundedQuantityValue $quantity, $roundingMode ) {
217
		if ( is_int( $roundingMode ) ) {
218
			// round to the given exponent
219
			return $roundingMode;
220
		} elseif ( $roundingMode && ( $quantity instanceof  QuantityValue ) ) {
221
			// round to the order of uncertainty (QuantityValue only)
222
			return $this->options->getOption( self::OPT_SHOW_UNCERTAINTY_MARGIN )
223
				? null
224
				// round to the order of uncertainty
225
				: $quantity->getOrderOfUncertainty();
226
		} else {
227
			// to keep all digits, use the negative length of the fractional part
228
			return -strlen( $quantity->getAmount()->getFractionalPart() );
229
		}
230
	}
231
232
	/**
233
	 * @param DecimalValue $decimal
234
	 *
235
	 * @return string
236
	 */
237
	private function formatMinimalDecimal( DecimalValue $decimal ) {
238
		// TODO: This should be an option of DecimalFormatter.
239
		return preg_replace( '/(\.\d+?)0+$/', '$1',
240
			preg_replace( '/(?<=\d)\.0*$/', '', $this->decimalFormatter->format( $decimal ) )
241
		);
242
	}
243
244
	/**
245
	 * @param DecimalValue $margin
246
	 * @param int $roundingExponent
247
	 *
248
	 * @return string|null Text
249
	 */
250
	private function formatMargin( DecimalValue $margin, $roundingExponent ) {
251
		$marginMode = $this->options->getOption( self::OPT_SHOW_UNCERTAINTY_MARGIN );
252
253
		// map legacy option values
254
		if ( $marginMode === true ) {
255
			// old default behavior
256
			$marginMode = self::SHOW_UNCERTAINTY_MARGIN_IF_NOT_ZERO;
257
		} elseif ( $marginMode === false ) {
258
			$marginMode = self::SHOW_UNCERTAINTY_MARGIN_NEVER;
259
		}
260
261
		if ( $marginMode === self::SHOW_UNCERTAINTY_MARGIN_NEVER ) {
262
			return null;
263
			return null;
0 ignored issues
show
Unused Code introduced by
return null; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
264
		}
265
266
		// TODO: never round to 0! See bug #56892
267
		$roundedMargin = $this->decimalMath->roundToExponent( $margin, $roundingExponent );
268
269
		if ( $marginMode === self::SHOW_UNCERTAINTY_MARGIN_IF_NOT_ZERO
270
			&& $roundedMargin->isZero()
271
		) {
272
			return null;
273
		}
274
275
		return $this->decimalFormatter->format( $roundedMargin );
276
	}
277
278
	/**
279
	 * @since 0.6
280
	 *
281
	 * @param string $unit URI
282
	 *
283
	 * @return string|null Text
284
	 */
285
	protected function formatUnit( $unit ) {
286
		if ( $this->vocabularyUriFormatter === null
287
			|| !$this->options->getOption( self::OPT_APPLY_UNIT )
288
			|| $unit === ''
289
			|| $unit === '1'
290
		) {
291
			return null;
292
		}
293
294
		return $this->vocabularyUriFormatter->format( $unit );
295
	}
296
297
}
298