Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
6 / 6
CRAP
100.00% covered (success)
100.00%
1 / 1
ValidationContext
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
6 / 6
9
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 create
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 at
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 addViolation
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 toApiUsageException
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 getParts
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3namespace Wikibase\Lexeme\Presentation\ChangeOp\Deserialization;
4
5use MediaWiki\Api\ApiUsageException;
6use MediaWiki\Status\Status;
7use Wikibase\Lexeme\MediaWiki\Api\Error\ApiError;
8
9/**
10 * @license GPL-2.0-or-later
11 */
12class ValidationContext {
13
14    /**
15     * @var self|null
16     */
17    private $parentContext;
18
19    /** @var string */
20    private $field;
21
22    /** @var string */
23    private $level = '';
24
25    /**
26     * @var ApiError[]
27     */
28    private $violations = [];
29
30    private function __construct( ?self $parentContext, $field, $level = null ) {
31        $this->parentContext = $parentContext;
32        $this->field = $field;
33        if ( $level !== null ) {
34            $this->level = $level;
35        }
36    }
37
38    public static function create( $field ) {
39        return new self( null, $field );
40    }
41
42    /**
43     * Start a new level
44     *
45     * @param string $level
46     * @return self
47     */
48    public function at( $level ) {
49        return new self( $this, $this->field, $level );
50    }
51
52    public function addViolation( ApiError $error ) {
53        $this->violations[] = $error;
54
55        $this->toApiUsageException();
56    }
57
58    private function toApiUsageException() {
59        foreach ( $this->violations as $violation ) {
60            /** @var ApiError $error */
61            $msg = $violation->asApiMessage( $this->field, $this->getParts() );
62            $msg->setApiData( [ 'parameterName' => $this->field, 'fieldPath' => $this->getParts() ] );
63
64            $status = Status::newGood();
65            $status->fatal( $msg );
66
67            throw new ApiUsageException( null, $status );
68        }
69    }
70
71    private function getParts() {
72        if ( $this->parentContext === null ) {
73            return [];
74        }
75        return array_merge(
76            $this->parentContext->getParts(),
77            [ $this->level ]
78        );
79    }
80
81}