Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.00% |
0 / 16 |
|
0.00% |
0 / 2 |
CRAP | |
0.00% |
0 / 1 |
| JsonValidator | |
0.00% |
0 / 16 |
|
0.00% |
0 / 2 |
42 | |
0.00% |
0 / 1 |
| validate | |
0.00% |
0 / 7 |
|
0.00% |
0 / 1 |
12 | |||
| readSchema | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
12 | |||
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * This program is free software; you can redistribute it and/or |
| 5 | * modify it under the terms of the GNU General Public License |
| 6 | * as published by the Free Software Foundation; under version 2 |
| 7 | * of the License (non-upgradable). |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU General Public License |
| 15 | * along with this program; if not, write to the Free Software |
| 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 17 | * |
| 18 | * Copyright (c) 2019 (original work) Open Assessment Technologies SA; |
| 19 | */ |
| 20 | |
| 21 | namespace oat\tao\model\webhooks\task; |
| 22 | |
| 23 | use JsonSchema\Validator; |
| 24 | use oat\oatbox\service\ConfigurableService; |
| 25 | |
| 26 | class JsonValidator extends ConfigurableService |
| 27 | { |
| 28 | public const FILE_PATH = __DIR__ . '/webhookResponseSchema.json'; |
| 29 | |
| 30 | /** |
| 31 | * @param mixed $data |
| 32 | * @throws InvalidJsonException |
| 33 | * @throws \common_exception_FileReadFailedException |
| 34 | */ |
| 35 | public function validate($data) |
| 36 | { |
| 37 | $validator = new Validator(); |
| 38 | $validator->validate($data, $this->readSchema()); |
| 39 | |
| 40 | if (!$validator->isValid()) { |
| 41 | $validationErrors = []; |
| 42 | foreach ($validator->getErrors() as $error) { |
| 43 | $validationErrors[] = sprintf('[%s] %s', $error['property'], $error['message']); |
| 44 | } |
| 45 | throw new InvalidJsonException('JSON check against schema failed', 0, $validationErrors); |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * @return object |
| 51 | * @throws \common_exception_FileReadFailedException |
| 52 | */ |
| 53 | private function readSchema() |
| 54 | { |
| 55 | $contents = @file_get_contents(self::FILE_PATH); |
| 56 | if ($contents === false) { |
| 57 | throw new \common_exception_FileReadFailedException('JSON schema for response could not be loaded'); |
| 58 | } |
| 59 | $obj = json_decode($contents, false); |
| 60 | if ($obj === false) { |
| 61 | throw new \common_exception_FileReadFailedException( |
| 62 | 'JSON schema for response is not a valid JSON: ' . json_last_error_msg() |
| 63 | ); |
| 64 | } |
| 65 | return $obj; |
| 66 | } |
| 67 | } |