Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
AssertValidTopLevelFields
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
2 / 2
6
100.00% covered (success)
100.00%
1 / 1
 assertValidTopLevelTypes
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 assertType
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
1<?php declare( strict_types = 1 );
2
3namespace Wikibase\Lexeme\MediaWiki\RestApi;
4
5use InvalidArgumentException;
6use MediaWiki\Rest\HttpException;
7use Wikibase\Lexeme\Interactors\UseCaseError;
8use Wikimedia\Assert\Assert;
9use Wikimedia\ParamValidator\ParamValidator;
10
11/**
12 * @license GPL-2.0-or-later
13 */
14trait AssertValidTopLevelFields {
15
16    /**
17     * @throws HttpException
18     */
19    public function assertValidTopLevelTypes( ?array $body, array $paramSettings ): void {
20        foreach ( $paramSettings as $fieldName => $fieldSettings ) {
21            if ( isset( $body[$fieldName] ) ) {
22                $this->assertType( $fieldSettings[ParamValidator::PARAM_TYPE], $fieldName, $body[$fieldName] );
23            } elseif ( $fieldSettings[ParamValidator::PARAM_REQUIRED] === true ) {
24                throw ( new ResponseFactory() )->newHttpExceptionFromError(
25                    UseCaseError::newMissingField( '', $fieldName )
26                );
27            }
28        }
29    }
30
31    /**
32     * @throws HttpException
33     */
34    private function assertType( string $type, string $fieldName, mixed $value ): void {
35        try {
36            Assert::parameterType( $type, $value, '$field' );
37        } catch ( InvalidArgumentException ) {
38            throw ( new ResponseFactory() )->newHttpExceptionFromError(
39                UseCaseError::newInvalidValue( "/$fieldName" )
40            );
41        }
42    }
43
44}