Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
Schema
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 3
132
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 toArray
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 validateDefinition
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
90
1<?php
2
3// Abstract checker and schema get functions
4
5namespace QuickSurveys;
6
7use Wikimedia\Assert\Assert;
8use Wikimedia\Assert\ParameterTypeException;
9
10class Schema {
11
12    protected const ARRAY_OF = '_arrayOf';
13    protected const ARRAY = '_array';
14
15    /**
16     * An internal description of the data that matches a schema.
17     * @var array
18     */
19    private $data;
20
21    /**
22     * Validate data against a provided type definition.
23     *
24     * @param array $data data to validate
25     * @param array $typeDefinition the type to validate the data against
26     * @throws ParameterTypeException when a key has the wrong type
27     */
28    public function __construct( array $data, array $typeDefinition ) {
29        $this->data = self::validateDefinition( $data, $typeDefinition );
30    }
31
32    /**
33     * Returns the JSON-encodable, minimal representation of the survey question.
34     *
35     * @return array
36     */
37    public function toArray(): array {
38        return $this->data;
39    }
40
41    /**
42     * Validates an array against a specified type definition and only includes
43     * keys that align with the definition.
44     *
45     * @throws ParameterTypeException when a key has the wrong type
46     */
47    private static function validateDefinition( array $data, array $typeDefinition ): array {
48        $newDefinition = [];
49
50        foreach ( $typeDefinition as $name => $type ) {
51            if ( array_key_exists( $name, $data ) && isset( $data[$name] ) ) {
52                $value = $data[$name];
53
54                if ( is_array( $type ) && $type[0] === self::ARRAY_OF ) {
55                    Assert::parameterType( 'array', $data[$name], $name );
56                    foreach ( $value as $subValue ) {
57                        $newDefinition[$name][] = self::validateDefinition( $subValue, $type[1] );
58                    }
59                } elseif ( is_array( $type ) && $type[0] === self::ARRAY ) {
60                    Assert::parameterType( 'array', $data[$name], $name );
61                    $newDefinition[$name] = self::validateDefinition( $value, $type[1] );
62                } else {
63                    Assert::parameterType( $type, $value, $name );
64                    $newDefinition[$name] = $value;
65                }
66            }
67        }
68
69        return $newDefinition;
70    }
71}