This class is a wrapper for {@link Validator} that adds exceptions and validation of schema files. A few edge cases that are not handled by {@link Validator} are handled by this class.
Since: 1.0
Author: Bernhard Schussek (bschussek@gmail.com)
コード例 #1
0
ファイル: JsonValidatorTest.php プロジェクト: bburnichon/json
 /**
  * @expectedException \Webmozart\Json\InvalidSchemaException
  */
 public function testValidateFailsIfInvalidSchemaNotRecognized()
 {
     // justinrainbow/json-schema cannot validate "anyOf", so the following
     // will load the schema successfully and fail when the file is validated
     // against the schema
     $this->validator->validate((object) array('name' => 'Bernhard'), (object) array('type' => 12345));
 }
コード例 #2
0
 /**
  * @expectedException \Webmozart\Json\Conversion\ConversionFailedException
  */
 public function testConvertValidationErrorsToConversionException()
 {
     $options = array('option' => 'value');
     $jsonData = (object) array('foo' => 'bar');
     $this->innerConverter->expects($this->once())->method('toJson')->with('DATA', $options)->willReturn($jsonData);
     $this->jsonValidator->expects($this->once())->method('validate')->willReturn(array('First error', 'Second error'));
     $this->converter->toJson('DATA', $options);
 }
コード例 #3
0
ファイル: JsonDecoder.php プロジェクト: bburnichon/json
 /**
  * Decodes and validates a JSON string.
  *
  * If a schema is passed, the decoded object is validated against that
  * schema. The schema may be passed as file path or as object returned from
  * `JsonDecoder::decodeFile($schemaFile)`.
  *
  * You can adjust the decoding with {@link setObjectDecoding()},
  * {@link setBigIntDecoding()} and {@link setMaxDepth()}.
  *
  * Schema validation is not supported when objects are decoded as
  * associative arrays.
  *
  * @param string        $json   The JSON string.
  * @param string|object $schema The schema file or object.
  *
  * @return mixed The decoded value.
  *
  * @throws DecodingFailedException   If the JSON string could not be decoded.
  * @throws ValidationFailedException If the decoded string fails schema
  *                                   validation.
  * @throws InvalidSchemaException    If the schema is invalid.
  */
 public function decode($json, $schema = null)
 {
     if (self::ASSOC_ARRAY === $this->objectDecoding && null !== $schema) {
         throw new \InvalidArgumentException('Schema validation is not supported when objects are decoded ' . 'as associative arrays. Call ' . 'JsonDecoder::setObjectDecoding(JsonDecoder::JSON_OBJECT) to fix.');
     }
     $decoded = $this->decodeJson($json);
     if (null !== $schema) {
         $errors = $this->validator->validate($decoded, $schema);
         if (count($errors) > 0) {
             throw ValidationFailedException::fromErrors($errors);
         }
     }
     return $decoded;
 }
コード例 #4
0
 private function validate($jsonData)
 {
     $schema = $this->schema;
     if (is_callable($schema)) {
         $schema = $schema($jsonData);
     }
     try {
         $errors = $this->jsonValidator->validate($jsonData, $schema);
     } catch (InvalidSchemaException $e) {
         throw new ConversionFailedException(sprintf('An error occurred while loading the JSON schema (%s): %s', is_string($schema) ? '"' . $schema . '"' : gettype($schema), $e->getMessage()), 0, $e);
     }
     if (count($errors) > 0) {
         throw new ConversionFailedException(sprintf("The passed JSON did not match the schema:\n%s", implode("\n", $errors)));
     }
 }
コード例 #5
0
 private function loadInstallers(Module $module)
 {
     foreach (self::$builtinInstallers as $name => $installerData) {
         $installer = $this->dataToInstaller($name, (object) $installerData);
         $this->installerDescriptors[$name] = $installer;
     }
     $moduleFile = $module->getModuleFile();
     if (null === $moduleFile) {
         return;
     }
     $moduleName = $module->getName();
     $installersData = $moduleFile->getExtraKey(self::INSTALLERS_KEY);
     if (!$installersData) {
         return;
     }
     $jsonValidator = new JsonValidator();
     $errors = $jsonValidator->validate($installersData, __DIR__ . '/../../res/schema/installers-schema-1.0.json');
     if (count($errors) > 0) {
         throw new ValidationFailedException(sprintf("The extra key \"%s\" of module \"%s\" is invalid:\n%s", self::INSTALLERS_KEY, $moduleName, implode("\n", $errors)));
     }
     foreach ($installersData as $name => $installerData) {
         $installer = $this->dataToInstaller($name, $installerData);
         $this->installerDescriptors[$name] = $installer;
         if ($module instanceof RootModule) {
             $this->rootInstallerDescriptors[$name] = $installer;
         }
     }
 }
コード例 #6
0
 private function assertServersLoaded()
 {
     if (null !== $this->servers) {
         return;
     }
     $serversData = $this->rootPackageFileManager->getExtraKey(self::SERVERS_KEY);
     if ($serversData) {
         $jsonValidator = new JsonValidator();
         $errors = $jsonValidator->validate($serversData, __DIR__ . '/../../res/schema/servers-schema-1.0.json');
         if (count($errors) > 0) {
             throw new ValidationFailedException(sprintf("The extra key \"%s\" is invalid:\n%s", self::SERVERS_KEY, implode("\n", $errors)));
         }
     }
     $this->servers = new ServerCollection();
     $this->serversData = (array) $serversData;
     foreach ($this->serversData as $serverName => $serverData) {
         $this->servers->add($this->dataToServer($serverName, $serverData));
     }
 }
コード例 #7
0
 private function decodeFile($path)
 {
     $decoder = new JsonDecoder();
     $validator = new JsonValidator();
     // We can't use realpath(), which doesn't work inside PHARs.
     // However, we want to display nice paths if the file is not found.
     $schema = Path::canonicalize(__DIR__ . '/../../res/schema/package-schema-1.0.json');
     if (!file_exists($path)) {
         throw FileNotFoundException::forPath($path);
     }
     try {
         $jsonData = $decoder->decodeFile($path);
     } catch (DecodingFailedException $e) {
         throw new InvalidConfigException(sprintf("The configuration in %s could not be decoded:\n%s", $path, $e->getMessage()), $e->getCode(), $e);
     }
     if (version_compare($jsonData->version, '1.0', '<')) {
         throw UnsupportedVersionException::versionTooLow($jsonData->version, '1.0', $path);
     }
     if (version_compare($jsonData->version, '1.0', '>')) {
         throw UnsupportedVersionException::versionTooHigh($jsonData->version, '1.0', $path);
     }
     $errors = $validator->validate($jsonData, $schema);
     if (count($errors) > 0) {
         throw new InvalidConfigException(sprintf("The configuration in %s is invalid:\n%s", $path, implode("\n", $errors)));
     }
     return $jsonData;
 }
コード例 #8
0
 private function validate($jsonData, $path = null)
 {
     $validator = new JsonValidator();
     $schema = $this->schemaDir . '/package-schema-' . $jsonData->version . '.json';
     if (!file_exists($schema)) {
         throw new InvalidConfigException(sprintf('The JSON schema file for version %s was not found%s.', $jsonData->version, $path ? ' in ' . $path : ''));
     }
     $errors = $validator->validate($jsonData, $schema);
     if (count($errors) > 0) {
         throw new InvalidConfigException(sprintf("The configuration%s is invalid:\n%s", $path ? ' in ' . $path : '', implode("\n", $errors)));
     }
 }
コード例 #9
0
 private function assertTargetsLoaded()
 {
     if (null !== $this->targets) {
         return;
     }
     $targetsData = $this->rootPackageFileManager->getExtraKey(AssetPlugin::INSTALL_TARGETS_KEY);
     if ($targetsData) {
         $jsonValidator = new JsonValidator();
         $errors = $jsonValidator->validate($targetsData, __DIR__ . '/../../res/schema/install-targets-schema-1.0.json');
         if (count($errors) > 0) {
             throw new ValidationFailedException(sprintf("The extra key \"%s\" is invalid:\n%s", AssetPlugin::INSTALL_TARGETS_KEY, implode("\n", $errors)));
         }
     }
     $this->targets = new InstallTargetCollection();
     $this->targetsData = (array) $targetsData;
     foreach ($this->targetsData as $targetName => $targetData) {
         $this->targets->add($this->dataToTarget($targetName, $targetData));
         if (isset($targetData->default) && $targetData->default) {
             $this->targets->setDefaultTarget($targetName);
         }
     }
 }
コード例 #10
0
 private function loadInstallers(Package $package)
 {
     $packageFile = $package->getPackageFile();
     $packageName = $package->getName();
     $installersData = $packageFile->getExtraKey(AssetPlugin::INSTALLERS_KEY);
     if (!$installersData) {
         return;
     }
     $jsonValidator = new JsonValidator();
     $errors = $jsonValidator->validate($installersData, __DIR__ . '/../../res/schema/installers-schema-1.0.json');
     if (count($errors) > 0) {
         throw new ValidationFailedException(sprintf("The extra key \"%s\" of package \"%s\" is invalid:\n%s", AssetPlugin::INSTALLERS_KEY, $packageName, implode("\n", $errors)));
     }
     foreach ($installersData as $name => $installerData) {
         $installer = $this->dataToInstaller($name, $installerData);
         $this->installerDescriptors[$name] = $installer;
         if ($package instanceof RootPackage) {
             $this->rootInstallerDescriptors[$name] = $installer;
         }
     }
 }
コード例 #11
0
ファイル: JsonValidatorTest.php プロジェクト: webmozart/json
 /**
  * @expectedException \Webmozart\Json\InvalidSchemaException
  */
 public function testValidateFailsIfInvalidSchemaType()
 {
     $this->validator->validate((object) array('name' => 'Bernhard'), 1234);
 }