ValidateSchemaTest.php in Schemata 8
File
tests/src/Functional/ValidateSchemaTest.php
View source
<?php
namespace Drupal\Tests\schemata\Functional;
use League\JsonGuard\Validator;
class ValidateSchemaTest extends SchemataBrowserTestBase {
public function testSchemataAreValidJsonSchema() {
foreach ([
'json',
'hal_json',
] as $described_format) {
foreach ($this->entityTypeManager
->getDefinitions() as $entity_type_id => $entity_type) {
try {
$this->schemaFactory
->getSourceEntityPlugin($entity_type_id);
} catch (\Exception $e) {
continue;
}
$this
->validateSchemaAsJsonSchema($described_format, $entity_type_id);
if ($bundle_type = $entity_type
->getBundleEntityType()) {
$bundles = $this->entityTypeManager
->getStorage($bundle_type)
->loadMultiple();
foreach ($bundles as $bundle) {
$this
->validateSchemaAsJsonSchema($described_format, $entity_type_id, $bundle
->id());
}
}
}
}
}
protected function validateSchemaAsJsonSchema($format, $entity_type_id, $bundle_id = NULL) {
$json = $this
->getRawSchemaByOptions($format, $entity_type_id, $bundle_id);
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertTrue(!empty($json), 'Schema request should provide response content instead of a NULL value.');
try {
$data = json_decode($json, FALSE, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
$this
->assertTrue(FALSE, "Could not decode JSON from schema response. Error: " . $e
->getMessage());
}
$this
->assertNotEmpty($data->{'$schema'}, 'JSON Schema should include a $schema reference to a defining schema.');
$schema = $this
->getDereferencedSchema($data->{'$schema'});
$this
->assertTrue(!empty($schema), 'The schema specification must be retrieved and dereferenced for use.');
$validator = new Validator($data, $schema);
if ($validator
->fails()) {
$bundle_label = empty($bundle_id) ? 'no-bundle' : $bundle_id;
$message = "Schema ({$entity_type_id}:{$bundle_label}) failed validation for {$format}:\n";
$errors = $validator
->errors();
$message .= json_encode($errors, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$this
->assertTrue(FALSE, $message);
}
$data->properties = '';
$validator = new Validator($data, $schema);
if (!$validator
->fails()) {
$bundle_label = empty($bundle_id) ? 'no-bundle' : $bundle_id;
$message = "Schema ({$entity_type_id}:{$bundle_label}) should fail validation if it is wrong.\n";
$this
->assertTrue(FALSE, $message);
}
}
}