/** * find all config files, decode content to PHP and merge together in the correct order * * @return array * * @todo add a way to cache (e.g. using APC) * @todo support yaml and ini config loading * @todo throw exceptions ;) * @todo loading errors need to throw concise exceptions and not fail silently * (e.g. use a json lib so we can identify errors in a specific file at a specific line) */ public function load() { $compiledConfig = array(); $parser = new JsonParser(); try { foreach ($this->finder as $file) { $config = null; switch ($file->getExtension()) { case 'json': $config = $this->doReplace($file->getContents()); $e = $parser->lint($config); if ($e) { throw $e; } $config = json_decode($config, true); break; } if ($config) { $compiledConfig = array_replace_recursive($compiledConfig, $config); } } } catch (\Seld\JsonLint\ParsingException $e) { throw new InvalidConfigException((string) $e); } return $compiledConfig; }
/** * Checks the syntax of the JSON string. * * @param string $json The JSON string. * * @throws JsonException If the JSON string is invalid. * @throws ParseException If the JSON string is invalid. * * @throws ParsingException If the JSON string contains lint. * * @api */ public function checkSyntax($json) { $parser = new JsonParser(); if (($result = $parser->lint($json)) instanceof ParsingException) { throw $result; } }
public function validateJson($json) { $parser = new JsonParser(); $lintResult = $parser->lint($json); if (null === $lintResult) { return true; } return $lintResult; }
/** * Returns the last error message when building a JSON file. Mimics json_last_error_msg() from PHP 5.5 * @param {String} the file that generated the error */ public static function lastErrorMsg($file, $message, $data) { Console::writeLine(PHP_EOL . "<error>The JSON file, " . $file . ", wasn't loaded. The error: " . $message . "</error>"); if ($message == "Syntax error, malformed JSON") { Console::writeLine(""); $parser = new JsonLint\JsonParser(); $error = $parser->lint($data); Console::writeError($error->getMessage(), false, true); } }
/** * @coversNothing */ public function testLintServiceDescription() { if (!$this->canServiceDescriptionBeLoaded()) { $json = file_get_contents(Client::getDescriptionFilename()); $parser = new JsonParser(); $result = $parser->lint($json); if ($result) { $this->fail($result->getMessage()); } } $this->assertTrue(true); }
/** * {@inheritdoc} */ public function getValue($key) { $parser = new JsonParser(); $plist = $this->getStoragePath(); $value = Util::run("defaults read \"{$plist}\" {$key}"); try { $parser->lint($json); return $parser->parse($json); } catch (Exception $e) { throw $e; } }
/** * @param string $message * @return string */ protected function lintMessage($message) { if (empty($message)) { return ""; } $linter = new JsonParser(); $result = $linter->lint($message); if ($result instanceof ParsingException) { return $result->getMessage(); } return ""; }
/** * @param string $message * @return string */ public function lintMessage($message) { if (empty($message) === true) { return null; } try { $linter = new JsonParser(); $linter->lint($message); } catch (ParsingException $e) { return $e->getMessage(); } return ""; }
protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('input-file'); $content = file_get_contents("{$name}", FILE_USE_INCLUDE_PATH); // validate json $parser = new JsonParser(); try { // if lint is null , no validation errors $lint = $parser->lint($content); // returns and exception if not null if (!is_null($lint)) { throw $lint; } $this->generateTex(json_decode($content, true)); } catch (\Exception $e) { $output->writeln($e->getMessage()); } }
public function onRequestStart(GetResponseEvent $responseEvent) { $request = $responseEvent->getRequest(); $jsonContent = $request->getContent(); if (empty($jsonContent)) { return; } $parser = new JsonParser(); $result = $parser->lint($jsonContent); if ($result instanceof ParsingException) { $appPrefix = null; if (is_callable(array($this->app, "getClientName"))) { $appPrefix = ucwords($this->app->getClientName()); } if (is_callable(array($this->app, "getAppName"))) { $appPrefix = ucwords($this->app->getAppName()); } /** * @todo make use configurable DI injected error handler provider */ $responseEvent->setResponse(ErrorHandler::jsonExceptionError($result, $appPrefix)); } }
/** * Validates the syntax of $json. * * @param string $json * * @throws ParsingException */ private function validateSyntax($json) { $parser = new JsonParser(); $result = $parser->lint($json); if ($result === null) { return; } throw new ParsingException(sprintf("The configuration file \"%s\" does not contain valid JSON.\n%s", $this->configurationFile, $result->getMessage()), $result->getDetails()); }
private function decodeJson($json) { $assoc = self::ASSOC_ARRAY === $this->objectDecoding; if (PHP_VERSION_ID >= 50400 && !defined('JSON_C_VERSION')) { $options = self::STRING === $this->bigIntDecoding ? JSON_BIGINT_AS_STRING : 0; $decoded = json_decode($json, $assoc, $this->maxDepth, $options); } else { $decoded = json_decode($json, $assoc, $this->maxDepth); } // Data could not be decoded if (null === $decoded && 'null' !== $json) { $parser = new JsonParser(); $e = $parser->lint($json); if ($e instanceof ParsingException) { throw new DecodingFailedException(sprintf('The JSON data could not be decoded: %s.', $e->getMessage()), 0, $e); } // $e is null if json_decode() failed, but the linter did not find // any problems. Happens for example when the max depth is exceeded. throw new DecodingFailedException(sprintf('The JSON data could not be decoded: %s.', JsonError::getLastErrorMessage()), json_last_error()); } return $decoded; }
public function parse($string) { $tokens = preg_split('~ ( ^ \\h* : # start - ":key" must be the first non-hwsp thing on the line | = | ; \\h* $ # end - ";" must be the last non-hwsp thing on the line ) ~xm', $string, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); $state = self::S_NONE; $curName = null; $jsonBuf = null; $jsonDepth = 0; $parsed = []; foreach ($tokens as $tok) { if ($state == self::S_NONE) { if (ltrim($tok) == ':') { $state = self::S_NAME; $curName = null; } } elseif ($state == self::S_NAME) { if ($tok == '=') { if (!$curName) { throw new Exception("Unexpected token '=', expected annotation name"); } $state = self::S_JSON; } else { $curName = trim($tok); } } elseif ($state == self::S_JSON) { if ($tok[0] == ';') { $parsed[$curName] = $jsonBuf; $curName = null; $jsonBuf = null; $state = self::S_NONE; } else { $jsonBuf .= $tok; } } } if ($state == self::S_JSON) { throw new Exception("Unexpected end of JSON for key '{$curName}'"); } elseif ($state != self::S_NONE) { throw new Exception("Unexpected end of definition for key '{$curName}'"); } $out = []; foreach ($parsed as $key => $json) { $cur = json_decode($json, !!'assoc'); if ($cur === null && ($err = json_last_error())) { $parser = new JsonParser(); $message = $parser->lint(trim($json))->getMessage(); throw new Exception("JSON parsing failed for '{$key}' - " . $message); } $out[$key] = $cur; } return $out; }
public static function lint($json) { $parser = new JsonParser(); return $parser->lint($json); }
/** * Validates the syntax of a JSON string. * * @param string $json * * @return bool true on success * * @throws JsonException */ public function validateJson($json) { $parser = new JsonParser(); $lintResult = $parser->lint($json); if (null === $lintResult) { return true; } $errors = array(); $errors[] = $lintResult->getMessage(); throw new JsonException(sprintf('Syntax of a "%s" file inside "%s" does not validate.', $this->getFileName(), $this->getFilePath()), $errors); }
/** * Validates the syntax of a JSON string * * @param string $json * @return Boolean true on success * @throws \UnexpectedValueException */ protected static function validateSyntax($json) { $parser = new JsonParser(); $result = $parser->lint($json); if (null === $result) { if (defined('JSON_ERROR_UTF8') && JSON_ERROR_UTF8 === json_last_error()) { throw new \UnexpectedValueException('JSON file is not UTF-8 encoded'); } return true; } throw $result; }
/** * Validates the syntax and the schema of the current config json file * according to satis-schema.json rules. * * @param string $configFile The json file to use * * @throws ParsingException if the json file has an invalid syntax * @throws JsonValidationException if the json file doesn't match the schema * * @return bool true on success */ private function check($configFile) { $content = file_get_contents($configFile); $parser = new JsonParser(); $result = $parser->lint($content); if (null === $result) { if (defined('JSON_ERROR_UTF8') && JSON_ERROR_UTF8 === json_last_error()) { throw new \UnexpectedValueException('"' . $configFile . '" is not UTF-8, could not parse as JSON'); } $data = json_decode($content); $schemaFile = __DIR__ . '/../../../../res/satis-schema.json'; $schema = json_decode(file_get_contents($schemaFile)); $validator = new Validator(); $validator->check($data, $schema); if (!$validator->isValid()) { $errors = array(); foreach ((array) $validator->getErrors() as $error) { $errors[] = ($error['property'] ? $error['property'] . ' : ' : '') . $error['message']; } throw new JsonValidationException('The json config file does not match the expected JSON schema', $errors); } return true; } throw new ParsingException('"' . $configFile . '" does not contain valid JSON' . "\n" . $result->getMessage(), $result->getDetails()); }
/** * Validates the syntax of a JSON string * * @param string $json * @param string $file * @return bool true on success * @throws \UnexpectedValueException * @throws JsonValidationException * @throws ParsingException */ protected static function validateSyntax($json, $file = null) { $parser = new JsonParser(); $result = $parser->lint($json); if (null === $result) { if (defined('JSON_ERROR_UTF8') && JSON_ERROR_UTF8 === json_last_error()) { throw new \UnexpectedValueException('"' . $file . '" is not UTF-8, could not parse as JSON'); } return true; } throw new ParsingException('"' . $file . '" does not contain valid JSON' . "\n" . $result->getMessage(), $result->getDetails()); }
/** * Validates the syntax of the theme Info JSON file. * * @param string $json * @param string $file * @return bool * @throws \UnexpectedValueException * @throws \RuntimeException */ protected function validateSyntax($json, $file = null) { $parser = new JsonParser(); $result = $parser->lint($json); if (is_null($result)) { if (defined('JSON_ERROR_UTF8') and JSON_ERROR_UTF8 === json_last_error()) { throw new UnexpectedValueException("[{$file}] is not UTF-8, could not parse as JSON."); } return true; } throw new RuntimeException("[{$file}] does not contain valid JSON. {$result->getMessage()}."); }
/** * Validates the syntax of a JSON string * * @param string $json * @return Boolean true on success * @throws \UnexpectedValueException */ protected static function validateSyntax($json) { $parser = new JsonParser(); $result = $parser->lint($json); if (null === $result) { return true; } throw $result; }
/** * Lints the JSON string. * * @param string $json The JSON data. * * @throws ParsingException If the JSON has lint. */ public function lint($json) { if (($result = $this->linter->lint($json)) instanceof ParsingException) { throw $result; } }
public function getConfig() { if (!empty($this->config)) { return $this->config; } if (empty($this->params['conf'])) { throw new Exception('no configuration specified', 500); } $configName = $this->params['conf']; $configFile = $this->findFileOnPath($configName . '.js', $this->getConfigPath()); if (!is_file($configFile)) { $configFile = $this->findFileOnPath($configName . '.json', $this->getConfigPath()); } if (!is_file($configFile)) { $error = "Configuration file `{$this->params['conf']}` not found."; $code = '404'; return $this->handleError($error, $code); } // get configuration $configJson = file_get_contents($configFile); $this->config = json_decode($configJson, true); if (empty($this->config)) { $parser = new JsonParser(); $jsonError = $parser->lint($configJson); $error = "You have an error in your configuration. {$jsonError->getMessage()}"; $code = '500'; return $this->handleError($error, $code); } return $this->config; }
private function decodeJson($json) { $assoc = self::ASSOC_ARRAY === $this->objectDecoding; if (PHP_VERSION_ID >= 50400 && !defined('JSON_C_VERSION')) { $options = self::STRING === $this->bigIntDecoding ? JSON_BIGINT_AS_STRING : 0; $decoded = json_decode($json, $assoc, $this->maxDepth, $options); } else { $decoded = json_decode($json, $assoc, $this->maxDepth); } if (null === $decoded && 'null' !== $json) { $parser = new JsonParser(); $e = $parser->lint($json); if ($e instanceof ParsingException) { throw new DecodingFailedException(sprintf('داده JSON نمی تواند رمزگشایی شود: %s.', $e->getMessage()), 0, $e); } throw new DecodingFailedException(sprintf('داده JSON نمی تواند رمزگشایی شود: %s.', JsonError::getLastErrorMessage()), json_last_error()); } return $decoded; }
$cw = new ClassWriter($gClass = $class->getGClass()); $cw->setUseStyle(ClassWriter::USE_STYLE_LINES); $phpFile = $command->getProject()->getClassFile($gClass); $cw->write($phpFile, array(), $overwrite = ClassWriter::OVERWRITE); $output->writeln($phpFile . ' written.'); }); $createCommand('tests:build-from-json', array($arg('file')), function ($input, $output, $command) { $jsonc = JSONConverter::create(); $root = Dir::factoryTS(__DIR__)->sub('../'); $json = $root->getFile($input->getArgument('file'))->getContents(); $json = '[' . str_replace('}{', '},{', $json) . ']'; try { $report = $jsonc->parse($json); } catch (\Webforge\Common\JS\JSONParsingException $e) { $parser = new JsonParser(); $parsingException = $parser->lint($root->getFile('output.json')->getContents()); throw $parsingException; } $toRun = array(); foreach ($report as $event) { if ($event->event === 'test' && ($event->status === 'fail' || $event->status === 'error')) { $testFQN = $event->suite; $file = Code::mapClassToFile($testFQN, $root->sub('tests/')); $file->getDirectory()->resolvePath(); $toRun[(string) $file] = (string) $file; } } $toRun = array_filter($toRun); $output->writeln(count($toRun) . ' tests have failed'); $root->getFile('to-run.json')->writeContents($jsonc->stringify($toRun)); });
protected function setHostByConfig($configPath, $group) { if (!$group) { $group = 'default'; } if (!is_file($configPath)) { throw new \RuntimeException("configuration path for hosts is not a valid file: {$configPath}"); } $configData = file_get_contents($configPath); $parser = new JsonParser(); $result = $parser->lint($configData); if ($result instanceof ParsingException) { throw $result; } $configData = json_decode($configData); if (!$configData->{$group}) { throw new \RuntimeException("group {$group} not found"); } $dbGroup = $configData->{$group}; if (!isset($dbGroup->username) && !isset($dbGroup->password)) { throw new \RuntimeException("Group {$group} did not have a valid username/password set"); } $this->username = $dbGroup->username; $this->password = $dbGroup->password; if (!isset($dbGroup->master)) { throw new \RunTimeException("Group: {$group} in config path did not have a master host setup"); } $this->registerHost('master', $dbGroup->master); // no slave set use the master if (!isset($dbGroup->slave)) { $this->registerHost('slave', $dbGroup->master); } if (isset($dbGroup->slave)) { if (is_string($dbGroup->slave)) { $this->registerHost('slave', $dbGroup->slave); } if (is_array($dbGroup->slave)) { foreach ($dbGroup->slave as $host) { if (is_string($host)) { $this->registerHost('slave', $host); } } } } }