DimensionParser::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace ParamProcessor\PackagePrivate;
4
5
use ValueParsers\ParseException;
6
use ValueParsers\ParserOptions;
7
use ValueParsers\ValueParser;
8
9
/**
10
 * Package private
11
 */
12
class DimensionParser implements ValueParser {
13
14
	public const DEFAULT_UNIT = 'defaultunit';
15
16
	public const PIXELS = 'px';
17
18
	private $defaultUnit;
19
20 52
	public function __construct( ParserOptions $options = null ) {
21 52
		$options = $options ?? new ParserOptions();
22
23 52
		$this->defaultUnit = $options->hasOption( self::DEFAULT_UNIT ) ? $options->getOption( self::DEFAULT_UNIT ) : self::PIXELS;
24 52
	}
25
26 52
	public function parse( $value ) {
27 52
		if ( !is_string( $value ) ) {
28 1
			throw new ParseException( 'Not a string' );
29
		}
30
31 51
		$value = $this->removeWhitespace( $value );
32
33 51
		if ( preg_match( '/^(\d|\.)+$/', $value ) ) {
34 13
			$value .= $this->defaultUnit;
35
		}
36
37 51
		return $value;
38
	}
39
40 51
	private function removeWhitespace( string $string ): string {
41 51
		return preg_replace( '/\s+/', '', $string );
42
	}
43
44
}
45