1
|
|
|
<?php |
2
|
|
|
namespace frictionlessdata\tableschema; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* Table Schema representation. |
6
|
|
|
* Loads and validates a Table Schema descriptor from a descriptor / path to file / url containing the descriptor |
7
|
|
|
*/ |
8
|
|
|
class Schema |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Schema constructor. |
12
|
|
|
* @param mixed $descriptor |
13
|
|
|
* @throws Exceptions\SchemaLoadException |
14
|
|
|
* @throws Exceptions\SchemaValidationFailedException |
15
|
|
|
*/ |
16
|
|
|
public function __construct($descriptor) |
17
|
|
|
{ |
18
|
|
|
if (Utils::isJsonString($descriptor)) { |
19
|
|
|
// it's a json encoded string |
20
|
|
|
try { |
21
|
|
|
$this->descriptor = json_decode($descriptor); |
22
|
|
|
} catch (\Exception $e) { |
23
|
|
|
throw new Exceptions\SchemaLoadException($descriptor, null, $e->getMessage()); |
24
|
|
|
} |
25
|
|
|
} elseif (is_string($descriptor)) { |
26
|
|
|
// it's a url or file path |
27
|
|
|
$descriptorSource = $descriptor; |
28
|
|
|
try { |
29
|
|
|
$descriptor = file_get_contents($descriptorSource); |
30
|
|
|
} catch (\Exception $e) { |
31
|
|
|
throw new Exceptions\SchemaLoadException(null, $descriptorSource, $e->getMessage()); |
32
|
|
|
} |
33
|
|
|
try { |
34
|
|
|
$this->descriptor = json_decode($descriptor); |
35
|
|
|
} catch (\Exception $e) { |
36
|
|
|
throw new Exceptions\SchemaLoadException($descriptor, $descriptorSource, $e->getMessage()); |
37
|
|
|
} |
38
|
|
|
} else { |
39
|
|
|
$this->descriptor = $descriptor; |
40
|
|
|
} |
41
|
|
|
if (!is_object($this->descriptor())) { |
42
|
|
|
throw new Exceptions\SchemaLoadException($descriptor, null, "descriptor must be an object"); |
43
|
|
|
} |
44
|
|
|
$validationErrors = SchemaValidator::validate($this->descriptor()); |
45
|
|
|
if (count($validationErrors) > 0) { |
46
|
|
|
throw new Exceptions\SchemaValidationFailedException($validationErrors); |
47
|
|
|
}; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* loads and validates the given descriptor source (php object / string / path to file / url) |
52
|
|
|
* returns an array of validation error objects |
53
|
|
|
* @param mixed $descriptor |
54
|
|
|
* @return array |
55
|
|
|
*/ |
56
|
|
|
public static function validate($descriptor) |
57
|
|
|
{ |
58
|
|
|
try { |
59
|
|
|
new static($descriptor); |
60
|
|
|
return []; |
61
|
|
|
} catch (Exceptions\SchemaLoadException $e) { |
62
|
|
|
return [ |
63
|
|
|
new SchemaValidationError(SchemaValidationError::LOAD_FAILED, $e->getMessage()) |
64
|
|
|
]; |
65
|
|
|
} catch (Exceptions\SchemaValidationFailedException $e) { |
66
|
|
|
return $e->validationErrors; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @return object |
72
|
|
|
*/ |
73
|
|
|
public function descriptor() |
74
|
|
|
{ |
75
|
|
|
return $this->descriptor; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
protected $descriptor; |
79
|
|
|
} |