Passed
Push — main ( c73e00...0a00da )
by
unknown
15:13 queued 14s
created

ScalarTypeConverter::toInt()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 2
rs 10
ccs 0
cts 2
cp 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
declare( strict_types=1 );
3
4
namespace WMDE\Fundraising\AddressChangeContext;
5
6
/**
7
 * This class converts "mixed" values from libraries like Doctrine or Symfony into scalar values, without tripping up
8
 * PHPStan, which disallows calling "strval" and "intval" on variables with "mixed" type, because calling them
9
 * with objects or arrays will generate a warning.
10
 *
11
 * DO NOT USE THIS IN LOOPS! (E.g. iterating over database results).
12
 * The constant type checking will slow down the application, use PHPStan-specific comments to ignore this error instead:
13
 * https://phpstan.org/user-guide/ignoring-errors
14
 *
15
 * Hopefully, in the future libraries will return fewer "mixed" types. Please check from time to time if this class is still needed.
16
 * Check the usage of the class methods to detect libraries that return mixed.
17
 */
18
class ScalarTypeConverter {
19
	public static function toInt( mixed $value ): int {
20
		return intval( self::assertScalarType( $value ) );
21
	}
22
23
	public static function toString( mixed $value ): string {
24
		return strval( self::assertScalarType( $value ) );
25
	}
26
27
	private static function assertScalarType( mixed $value ): int|string|bool|float {
28
		if ( is_scalar( $value ) ) {
29
			return $value;
30
		}
31
		throw new \InvalidArgumentException( "Given value is not a scalar type" );
32
	}
33
}
34