Completed
Push — master ( fec4dc...4de4c0 )
by
unknown
03:25
created

AllowedUnitsChecker::checkConstraint()   B

Complexity

Conditions 9
Paths 15

Size

Total Lines 55
Code Lines 39

Duplication

Lines 17
Ratio 30.91 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 17
loc 55
rs 7.2446
cc 9
eloc 39
nc 15
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace WikibaseQuality\ConstraintReport\ConstraintCheck\Checker;
4
5
use DataValues\UnboundedQuantityValue;
6
use Wikibase\DataModel\Entity\ItemId;
7
use Wikibase\DataModel\Snak\PropertyValueSnak;
8
use Wikibase\Lib\Units\UnitConverter;
9
use WikibaseQuality\ConstraintReport\Constraint;
10
use WikibaseQuality\ConstraintReport\ConstraintCheck\ConstraintChecker;
11
use WikibaseQuality\ConstraintReport\ConstraintCheck\Context\Context;
12
use WikibaseQuality\ConstraintReport\ConstraintCheck\Helper\ConstraintParameterException;
13
use WikibaseQuality\ConstraintReport\ConstraintCheck\Helper\ConstraintParameterParser;
14
use WikibaseQuality\ConstraintReport\ConstraintCheck\Helper\UnitsParameter;
15
use WikibaseQuality\ConstraintReport\ConstraintCheck\Message\ViolationMessage;
16
use WikibaseQuality\ConstraintReport\ConstraintCheck\Result\CheckResult;
17
use WikibaseQuality\ConstraintReport\Role;
18
19
/**
20
 * @author Lucas Werkmeister
21
 * @license GPL-2.0-or-later
22
 */
23
class AllowedUnitsChecker implements ConstraintChecker {
24
25
	/**
26
	 * @var ConstraintParameterParser
27
	 */
28
	private $constraintParameterParser;
29
30
	/**
31
	 * @var UnitConverter|null
32
	 */
33
	private $unitConverter;
34
35
	/**
36
	 * @param ConstraintParameterParser $constraintParameterParser
37
	 * @param UnitConverter|null $unitConverter
38
	 */
39
	public function __construct(
40
		ConstraintParameterParser $constraintParameterParser,
41
		UnitConverter $unitConverter = null
42
	) {
43
		$this->constraintParameterParser = $constraintParameterParser;
44
		$this->unitConverter = $unitConverter;
45
	}
46
47
	/**
48
	 * @codeCoverageIgnore This method is purely declarative.
49
	 */
50
	public function getSupportedContextTypes() {
51
		return [
52
			Context::TYPE_STATEMENT => CheckResult::STATUS_COMPLIANCE,
53
			Context::TYPE_QUALIFIER => CheckResult::STATUS_COMPLIANCE,
54
			Context::TYPE_REFERENCE => CheckResult::STATUS_COMPLIANCE,
55
		];
56
	}
57
58
	/**
59
	 * @codeCoverageIgnore This method is purely declarative.
60
	 */
61
	public function getDefaultContextTypes() {
62
		return [
63
			Context::TYPE_STATEMENT,
64
			Context::TYPE_QUALIFIER,
65
			Context::TYPE_REFERENCE,
66
		];
67
	}
68
69
	/**
70
	 * Checks an “allowed units” constraint.
71
	 *
72
	 * @param Context $context
73
	 * @param Constraint $constraint
74
	 *
75
	 * @throws ConstraintParameterException
76
	 * @return CheckResult
77
	 */
78
	public function checkConstraint( Context $context, Constraint $constraint ) {
79
		$parameters = [];
80
		$constraintParameters = $constraint->getConstraintParameters();
81
		$unitsParameter = $this->constraintParameterParser
82
			->parseUnitsParameter(
83
				$constraintParameters,
84
				$constraint->getConstraintTypeItemId()
85
			);
86
87
		$snak = $context->getSnak();
88
		if ( !$snak instanceof PropertyValueSnak ) {
89
			// nothing to check
90
			return new CheckResult( $context, $constraint, $parameters, CheckResult::STATUS_COMPLIANCE );
91
		}
92
93
		$dataValue = $snak->getDataValue();
94 View Code Duplication
		if ( !$dataValue instanceof UnboundedQuantityValue ) {
0 ignored issues
show
Bug introduced by
The class DataValues\UnboundedQuantityValue does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
			$message = ( new ViolationMessage( 'wbqc-violation-message-value-needed-of-type' ) )
96
				->withEntityId( new ItemId( $constraint->getConstraintTypeItemId() ), Role::CONSTRAINT_TYPE_ITEM )
97
				->withDataValueType( 'quantity' );
98
			return new CheckResult( $context, $constraint, $parameters, CheckResult::STATUS_VIOLATION, $message );
99
		}
100
101
		if ( $dataValue->getUnit() === '1' ) {
102
			return $this->checkUnitless( $context, $constraint, $unitsParameter, $snak );
103
		}
104
105
		$status = CheckResult::STATUS_VIOLATION;
106
		$actualUnit = $this->standardize( $dataValue )->getUnit();
107
		foreach ( $unitsParameter->getUnitQuantities() as $unitQuantity ) {
108
			$allowedUnit = $this->standardize( $unitQuantity )->getUnit();
109
			if ( $actualUnit === $allowedUnit ) {
110
				$status = CheckResult::STATUS_COMPLIANCE;
111
				break;
112
			}
113
		}
114
115
		if ( $status === CheckResult::STATUS_VIOLATION ) {
116 View Code Duplication
			if ( $unitsParameter->getUnitItemIds() === [] ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
117
				$message = ( new ViolationMessage( 'wbqc-violation-message-units-none' ) )
118
					->withEntityId( $snak->getPropertyId(), Role::CONSTRAINT_PROPERTY );
119
			} else {
120
				$messageKey = $unitsParameter->getUnitlessAllowed() ?
121
					'wbqc-violation-message-units-or-none' :
122
					'wbqc-violation-message-units';
123
				$message = ( new ViolationMessage( $messageKey ) )
124
					->withEntityId( $snak->getPropertyId(), Role::CONSTRAINT_PROPERTY )
125
					->withEntityIdList( $unitsParameter->getUnitItemIds(), Role::CONSTRAINT_PARAMETER_VALUE );
126
			}
127
		} else {
128
			$message = null;
129
		}
130
131
		return new CheckResult( $context, $constraint, $parameters, $status, $message );
132
	}
133
134
	/**
135
	 * @param Context $context
136
	 * @param Constraint $constraint
137
	 * @param UnitsParameter $unitsParameter
138
	 * @param PropertyValueSnak $snak
139
	 * @return CheckResult
140
	 */
141
	private function checkUnitless(
142
		Context $context,
143
		Constraint $constraint,
144
		UnitsParameter $unitsParameter,
145
		PropertyValueSnak $snak
146
	) {
147
		if ( $unitsParameter->getUnitlessAllowed() ) {
148
			$message = null;
149
			$status = CheckResult::STATUS_COMPLIANCE;
150
		} else {
151
			$message = ( new ViolationMessage( 'wbqc-violation-message-units' ) )
152
				->withEntityId( $snak->getPropertyId(), Role::CONSTRAINT_PROPERTY )
153
				->withEntityIdList( $unitsParameter->getUnitItemIds(), Role::CONSTRAINT_PARAMETER_VALUE );
154
			$status = CheckResult::STATUS_VIOLATION;
155
		}
156
157
		return new CheckResult( $context, $constraint, [], $status, $message );
158
	}
159
160
	/**
161
	 * Convert $value to standard units.
162
	 *
163
	 * @param UnboundedQuantityValue $value
164
	 * @return UnboundedQuantityValue
165
	 */
166 View Code Duplication
	private function standardize( UnboundedQuantityValue $value ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
167
		if ( $this->unitConverter === null ) {
168
			return $value;
169
		}
170
171
		$standard = $this->unitConverter->toStandardUnits( $value );
172
		if ( $standard !== null ) {
173
			return $standard;
174
		} else {
175
			return $value;
176
		}
177
	}
178
179 View Code Duplication
	public function checkConstraintParameters( Constraint $constraint ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
180
		$constraintParameters = $constraint->getConstraintParameters();
181
		$exceptions = [];
182
		try {
183
			$this->constraintParameterParser->parseItemsParameter(
184
				$constraintParameters,
185
				$constraint->getConstraintTypeItemId(),
186
				true
187
			);
188
		} catch ( ConstraintParameterException $e ) {
189
			$exceptions[] = $e;
190
		}
191
		return $exceptions;
192
	}
193
194
}
195