private static function loadConfig(Container $container) { global $argv; $configPaths = array(); foreach ($argv as $arg) { if (0 === strpos($arg, '--config=')) { $configFile = substr($arg, 9); if (!file_exists($configFile)) { echo sprintf('Config file "%s" does not exist', $configFile) . PHP_EOL; exit(1); } $configPaths = array($configFile); } } if (empty($configPaths)) { $configPaths = array(getcwd() . '/phpbench.json', getcwd() . '/phpbench.json.dist'); } foreach ($configPaths as $configPath) { if (!file_exists($configPath)) { continue; } $config = file_get_contents($configPath); try { $parser = new JsonParser(); $parser->parse($config); } catch (ParsingException $e) { echo 'Error parsing config file:' . PHP_EOL . PHP_EOL; echo $e->getMessage(); exit(1); } $config = json_decode($config, true); $config['config_path'] = $configPath; $container->mergeParameters($config); } }
protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Running data verification.'); $parser = new JsonParser(); $rootPath = __DIR__ . '/../../..'; $dataFiles = scandir($rootPath . '/data/'); $numFiles = 0; $numErrors = 0; foreach ($dataFiles as $filename) { if (preg_match('/.+\\.json$/i', $filename) === 1) { $numFiles++; $output->writeln(sprintf('#%s Testing %s', $numFiles, $filename)); $json = file_get_contents(sprintf('%s/data/%s', $rootPath, $filename)); try { $return = $parser->parse($json); } catch (Parsing\Exception $e) { $numErrors++; $output->writeln(sprintf(PHP_EOL . ' <error>%s</error>' . PHP_EOL, $e->getMessage())); continue; } $ppData = json_decode($json, true); try { $this->dataIntegrityTest($ppData); } catch (\Exception $e) { $numErrors++; $output->writeln(sprintf(PHP_EOL . ' <error>%s</error>' . PHP_EOL, $e->getMessage())); } } } if ($numErrors !== 0) { $output->writeln(sprintf(PHP_EOL . ' <error>%s errors found!</error>', $numErrors)); } else { $output->writeln(PHP_EOL . '<info>No errors found!</info>'); } }
/** * 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; } }
/** * 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; }
public function validateJson($json) { $parser = new JsonParser(); $lintResult = $parser->lint($json); if (null === $lintResult) { return true; } return $lintResult; }
/** * {@inheritdoc} */ public function parse($content) { try { $parser = new JsonLintParser(); return $parser->parse($content, JsonLintParser::PARSE_TO_ASSOC); } catch (\Exception $e) { throw new ParsingException($this->getMetaParser()->getName(), null, $e); } }
/** * Parse json file into definition format. * * @param string $filename * @return Definition */ public static function loadJSON($filename) { if (!is_readable($filename)) { throw new \RuntimeException('JSON file "' . $filename . '" doesn\'t readable'); } $json = file_get_contents($filename); $parser = new JsonParser(); $parsed = $parser->parse($json); return static::load((array) $parsed); }
/** * 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); } }
private static function loadConfig() { global $argv; $configPaths = array(); $bootstrapOverride = null; $extensions = array(); foreach ($argv as $arg) { if ($configFile = self::parseOption($arg, 'config')) { if (!file_exists($configFile)) { echo sprintf('Config file "%s" does not exist', $configFile) . PHP_EOL; exit(1); } $configPaths = array($configFile); } if ($value = self::parseOption($arg, 'bootstrap', 'b')) { $bootstrapOverride = $value; } if ($value = self::parseOption($arg, 'extension')) { $extensions[] = $value; } } if (empty($configPaths)) { $configPaths = array(getcwd() . '/phpbench.json', getcwd() . '/phpbench.json.dist'); } $config = array('extensions' => array(), 'bootstrap' => null); foreach ($configPaths as $configPath) { if (!file_exists($configPath)) { continue; } $configRaw = file_get_contents($configPath); try { $parser = new JsonParser(); $parser->parse($configRaw); } catch (ParsingException $e) { echo 'Error parsing config file:' . PHP_EOL . PHP_EOL; echo $e->getMessage(); exit(1); } $config = array_merge($config, json_decode($configRaw, true)); $config['config_path'] = $configPath; if ($config['bootstrap']) { $config['bootstrap'] = self::getBootstrapPath(dirname($configPath), $config['bootstrap']); } break; } if ($bootstrapOverride) { $config['bootstrap'] = self::getBootstrapPath(getcwd(), $bootstrapOverride); } // add any manually specified extensions foreach ($extensions as $extension) { $config['extensions'][] = $extension; } return $config; }
/** * {@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 ""; }
/** * Validates the syntax of a JSON string. * * @param string $json * * @throws ParseException */ private static function validateSyntax($json) { $parser = new JsonParser(); try { $parser->parse($json); } catch (ParsingException $e) { throw ParseException::castFromJson($e); } if (json_last_error() === JSON_ERROR_UTF8) { throw new ParseException('JSON parsing failed: ' . static::errorToString(JSON_ERROR_UTF8)); } }
/** * @param SplFileInfo $file * * @return mixed * @throws \Seld\JsonLint\ParsingException */ public function lint(SplFileInfo $file) { $errors = new LintErrorsCollection(); $flags = $this->calculateFlags(); try { $json = $this->filesystem->readFromFileInfo($file); $this->jsonParser->parse($json, $flags); } catch (ParsingException $exception) { $errors->add(JsonLintError::fromParsingException($file, $exception)); } return $errors; }
/** * @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); }
/** * @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 ""; }
/** * @param SplFileInfo $file * * @return mixed * @throws \Seld\JsonLint\ParsingException */ public function lint(SplFileInfo $file) { $parser = new JsonParser(); $errors = new LintErrorsCollection(); $flags = $this->calculateFlags(); try { $json = file_get_contents($file->getPathname()); $parser->parse($json, $flags); } catch (ParsingException $exception) { $errors->add(JsonLintError::fromParsingException($file, $exception)); } return $errors; }
public function load($file_path, $values = array()) { if (!file_exists($file_path) || false === ($data = file_get_contents($file_path))) { throw new RuntimeException(sprintf('Unable to read file: %s', $file_path)); } $parser = new JsonParser(); try { $data = Utils::toArray($parser->parse($this->doReplace($data, $values), true)); } catch (\Exception $e) { throw new \Exception(sprintf('Unable to parse file %s: %s', $file_path, $e->getMessage())); } return $data; }
public function __construct($app, Filesystem $fs) { $this->app = $app; $this->fs = $fs; $json_parser = new JsonParser(); $this->extensions = ['json' => function ($raw) use($json_parser) { $parsed = $json_parser->parse($raw); return $parsed; }, 'yml' => function ($raw) { $parsed = Yaml::parse($raw, false, false, true); return $parsed; }]; $this->index(); $this->parse(); }
/** * {@inheritdoc} */ public function process(ProcessorConfig $config, $input) { if (!is_string($input)) { throw new UnexpectedTypeException($input, 'string'); } $input = trim($input); if (empty($input)) { return; } try { $parser = new JsonParser(); $array = $parser->parse($input, JsonParser::PARSE_TO_ASSOC); } catch (ParsingException $e) { throw new InputProcessorException('Input does not contain valid JSON: ' . "\n" . $e->getMessage(), 0, $e); } return parent::process($config, $array); }
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()); } }
private static function loadConfig(Container $container) { global $argv; $configPaths = array(); $bootstrapOverride = null; foreach ($argv as $arg) { if ($configFile = self::parseOption($arg, 'config')) { if (!file_exists($configFile)) { echo sprintf('Config file "%s" does not exist', $configFile) . PHP_EOL; exit(1); } $configPaths = array($configFile); } if ($value = self::parseOption($arg, 'bootstrap', 'b')) { $bootstrapOverride = $value; } } if (empty($configPaths)) { $configPaths = array(getcwd() . '/phpbench.json', getcwd() . '/phpbench.json.dist'); } foreach ($configPaths as $configPath) { if (!file_exists($configPath)) { continue; } $config = file_get_contents($configPath); try { $parser = new JsonParser(); $parser->parse($config); } catch (ParsingException $e) { echo 'Error parsing config file:' . PHP_EOL . PHP_EOL; echo $e->getMessage(); exit(1); } $config = json_decode($config, true); $config['config_path'] = $configPath; if (isset($config['bootstrap'])) { $config['bootstrap'] = self::getBootstrapPath(dirname($configPath), $config['bootstrap']); } $container->mergeParameters($config); } if ($bootstrapOverride) { $container->setParameter('bootstrap', self::getBootstrapPath(getcwd(), $bootstrapOverride)); } }
public function prettify() { $parser = new JsonParser(); foreach ($this->files as $file) { $raw = $this->fs->get($file); $data = $parser->parse($raw); $pretty = json_encode($data, JSON_PRETTY_PRINT); $tmp_name = $file . '.tmp'; if ($this->fs->put($tmp_name, $pretty) === false) { throw new \Exception('Couldn\'t write to ' . $tmp_name); } if (!$this->fs->delete($file)) { throw new \Exception('Couldn\'t delete ' . $file); } if (!$this->fs->move($tmp_name, $file)) { throw new \Exception('Couldn\'t rename ' . $tmp_name); } } }
public function load() { $parser = new JsonParser(); $contents = $this->file->fread($this->file->getSize()); try { $options = JsonParser::PARSE_TO_ASSOC; if ($this->getOption('allow_duplicate_keys')) { $options = $options | JsonParser::ALLOW_DUPLICATE_KEYS; } $contents = $parser->parse($contents, $options); } catch (ParsingException $e) { throw new FileNotParseableException($this->filename, 'JSON', $e->getMessage()); } if (is_array($contents)) { $reader = new ArrayReader($contents); return $this->setReader($reader); } throw new FileNotParseableException($this->filename, 'JSON', 'The file is not an array.'); }
/** * @depends testWhitespace */ public function testJSON($games) { try { $parser = new JsonParser(); $games = $parser->parse($games, JsonParser::DETECT_KEY_CONFLICTS + JsonParser::PARSE_TO_ASSOC); } catch (Exception $e) { $this->assertTrue('parsing', $e->getMessage()); } $allowedKeys = array('Hidden' => 'is_bool', 'Beta' => 'is_bool', 'Comment' => 'is_string', 'CommentURL' => 'is_string'); foreach ($games as $appID => $keys) { $this->assertTrue(is_numeric($appID), 'Key "' . $appID . '" must be numeric'); if ($keys === true) { // We're golden! } else { if (is_array($keys)) { $this->assertNotEmpty($keys, '"' . $appID . '" can not be an empty array'); foreach ($keys as $key => $value) { $this->assertArrayHasKey($key, $allowedKeys, 'Invalid key "' . $key . '" in "' . $appID . '"'); $this->assertTrue($allowedKeys[$key]($value), '"' . $key . '" in "' . $appID . '" is not "' . $allowedKeys[$key] . '"'); if ($key === 'Beta') { $this->assertTrue($value, $key . ' key in "' . $appID . '" can only be set to true'); } else { if ($key === 'Hidden') { $this->assertTrue($value, $key . ' key in "' . $appID . '" can only be set to true'); $this->assertArrayNotHasKey('Beta', $keys, 'Beta key can not be used along with Hidden key in "' . $appID . '"'); $this->assertArrayHasKey('Comment', $keys, 'Hidden app "' . $appID . '" must contain a Comment explaining why it was hidden'); } else { if ($key === 'CommentURL') { $this->assertArrayHasKey('Comment', $keys, 'CommentURL key can not be without Comment key in "' . $appID . '"'); $this->assertStringStartsWith('http', $value, 'CommentURL must be an url in "' . $appID . '"'); } } } } } else { $this->assertTrue(false, 'Key "' . $appID . '" has an invalid value'); } } } return $games; }
/** * @see \Bolt\Database\Migration\Input\InputFileInterface::readFile() */ public function readFile() { $filename = (string) $this->file; if ($this->file->isReadable()) { try { $data = $this->parser->parse(file_get_contents($filename)); $this->import->setData($data); return true; } catch (ParsingException $e) { $this->import->setError(true)->setErrorMessage("File '{$filename}' has invalid JSON!"); $details = $e->getDetails(); foreach ($details as $detail) { $this->import->setErrorMessage($detail); } return false; } } else { $this->import->setError(true)->setErrorMessage("File '{$filename}' not readable!"); return false; } }
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)); } }
$class->getClassDocBlock()->addSimpleAnnotation('compiled jqx-widget-specification console-command on ' . date('d.m.Y H:i')); $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));
public function testFileWithBOM() { try { $parser = new JsonParser(); $parser->parse(file_get_contents(dirname(__FILE__) . '/bom.json')); $this->fail('BOM should be detected'); } catch (ParsingException $e) { $this->assertContains('BOM detected', $e->getMessage()); } }
/** * Creates a Composer instance * * @param IOInterface $io IO instance * @param array|string|null $localConfig either a configuration array or a filename to read from, if null it will * read from the default filename * @param bool $disablePlugins Whether plugins should not be loaded * @param bool $fullLoad Whether to initialize everything or only main project stuff (used when loading the global composer) * @throws \InvalidArgumentException * @throws \UnexpectedValueException * @return Composer */ public function createComposer(IOInterface $io, $localConfig = null, $disablePlugins = false, $cwd = null, $fullLoad = true) { $cwd = $cwd ?: getcwd(); // load Composer configuration if (null === $localConfig) { $localConfig = static::getComposerFile(); } if (is_string($localConfig)) { $composerFile = $localConfig; $file = new JsonFile($localConfig, null, $io); if (!$file->exists()) { if ($localConfig === './composer.json' || $localConfig === 'composer.json') { $message = 'Composer could not find a composer.json file in ' . $cwd; } else { $message = 'Composer could not find the config file: ' . $localConfig; } $instructions = 'To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section'; throw new \InvalidArgumentException($message . PHP_EOL . $instructions); } $file->validateSchema(JsonFile::LAX_SCHEMA); $jsonParser = new JsonParser(); try { $jsonParser->parse(file_get_contents($localConfig), JsonParser::DETECT_KEY_CONFLICTS); } catch (\Seld\JsonLint\DuplicateKeyException $e) { $details = $e->getDetails(); $io->writeError('<warning>Key ' . $details['key'] . ' is a duplicate in ' . $localConfig . ' at line ' . $details['line'] . '</warning>'); } $localConfig = $file->read(); } // Load config and override with local config/auth config $config = static::createConfig($io, $cwd); $config->merge($localConfig); if (isset($composerFile)) { $io->writeError('Loading config file ' . $composerFile, true, IOInterface::DEBUG); $localAuthFile = new JsonFile(dirname(realpath($composerFile)) . '/auth.json'); if ($localAuthFile->exists()) { $io->writeError('Loading config file ' . $localAuthFile->getPath(), true, IOInterface::DEBUG); $config->merge(array('config' => $localAuthFile->read())); $config->setAuthConfigSource(new JsonConfigSource($localAuthFile, true)); } } $vendorDir = $config->get('vendor-dir'); $binDir = $config->get('bin-dir'); // initialize composer $composer = new Composer(); $composer->setConfig($config); if ($fullLoad) { // load auth configs into the IO instance $io->loadConfiguration($config); } $rfs = self::createRemoteFilesystem($io, $config); // initialize event dispatcher $dispatcher = new EventDispatcher($composer, $io); $composer->setEventDispatcher($dispatcher); // initialize repository manager $rm = $this->createRepositoryManager($io, $config, $dispatcher, $rfs); $composer->setRepositoryManager($rm); // load local repository $this->addLocalRepository($io, $rm, $vendorDir); // force-set the version of the global package if not defined as // guessing it adds no value and only takes time if (!$fullLoad && !isset($localConfig['version'])) { $localConfig['version'] = '1.0.0'; } // load package $parser = new VersionParser(); $guesser = new VersionGuesser($config, new ProcessExecutor($io), $parser); $loader = new Package\Loader\RootPackageLoader($rm, $config, $parser, $guesser); $package = $loader->load($localConfig, 'Composer\\Package\\RootPackage', $cwd); $composer->setPackage($package); // initialize installation manager $im = $this->createInstallationManager(); $composer->setInstallationManager($im); if ($fullLoad) { // initialize download manager $dm = $this->createDownloadManager($io, $config, $dispatcher, $rfs); $composer->setDownloadManager($dm); // initialize autoload generator $generator = new AutoloadGenerator($dispatcher, $io); $composer->setAutoloadGenerator($generator); } // add installers to the manager (must happen after download manager is created since they read it out of $composer) $this->createDefaultInstallers($im, $composer, $io); if ($fullLoad) { $globalComposer = $this->createGlobalComposer($io, $config, $disablePlugins); $pm = $this->createPluginManager($io, $composer, $globalComposer, $disablePlugins); $composer->setPluginManager($pm); $pm->loadInstalledPlugins(); // once we have plugins and custom installers we can // purge packages from local repos if they have been deleted on the filesystem if ($rm->getLocalRepository()) { $this->purgePackages($rm->getLocalRepository(), $im); } } // init locker if possible if ($fullLoad && isset($composerFile)) { $lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION) ? substr($composerFile, 0, -4) . 'lock' : $composerFile . '.lock'; $locker = new Package\Locker($io, new JsonFile($lockFile, null, $io), $rm, $im, file_get_contents($composerFile)); $composer->setLocker($locker); } return $composer; }
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; }