1 <?php
2
3 4 5 6 7 8 9 10
11
12 namespace ICanBoogie\AutoConfig;
13
14 use Composer\Json\JsonFile;
15 use Composer\Json\JsonValidationException;
16 use JsonSchema\Validator;
17
18 19 20
21 class ConfigValidator
22 {
23 protected $schema;
24 protected $validator;
25
26 public function __construct()
27 {
28 $this->schema = json_decode(file_get_contents(__DIR__ . '/icanboogie-schema.json'));
29
30 if (!$this->schema)
31 {
32 throw \Exception('Unable to load icanboogie schema.');
33 }
34
35 $this->validator = new Validator;
36 }
37
38 public function validate($pathname)
39 {
40 $json = file_get_contents($pathname);
41
42 if (!$json)
43 {
44 throw new \Exception("Unable to read JSON from $pathname.");
45 }
46
47 JsonFile::parseJson($json, $pathname);
48
49 $data = json_decode($json);
50
51 $validator = $this->validator;
52 $validator->check($data, $this->schema);
53
54 if (!$validator->isValid())
55 {
56 $errors = '';
57
58 foreach ((array) $validator->getErrors() as $error)
59 {
60 $errors .= "\n- " . ($error['property'] ? $error['property'] . ': ' : '') . $error['message'];
61 }
62
63 throw new \Exception("$pathname does not match the expected JSON schema:\n$errors");
64 }
65
66 return true;
67 }
68 }