作者:QianmiHu
项目:crypto-j
/**
* Parses YAML into a PHP array.
*
* The parse method, when supplied with a YAML stream (string or file),
* will do its best to convert YAML in a file into a PHP array.
*
* Usage:
* <code>
* $array = Yaml::parse('config.yml');
* print_r($array);
* </code>
*
* @param string $input Path to a YAML file or a string containing YAML
*
* @return array The YAML converted to a PHP array
*
* @throws \InvalidArgumentException If the YAML is not valid
*
* @api
*/
public static function parse($input)
{
// if input is a file, process it
$file = '';
if (strpos($input, "\n") === false && is_file($input)) {
if (false === is_readable($input)) {
throw new ParseException(sprintf('Unable to parse "%s" as the file is not readable.', $input));
}
$file = $input;
if (self::$enablePhpParsing) {
ob_start();
$retval = (include $file);
$content = ob_get_clean();
// if an array is returned by the config file assume it's in plain php form else in YAML
$input = is_array($retval) ? $retval : $content;
// if an array is returned by the config file assume it's in plain php form else in YAML
if (is_array($input)) {
return $input;
}
} else {
$input = file_get_contents($file);
}
}
$yaml = new Parser();
try {
return $yaml->parse($input);
} catch (ParseException $e) {
if ($file) {
$e->setParsedFile($file);
}
throw $e;
}
}
作者:joshlope
项目:dota2.mapap
private function configureParameters()
{
$yaml = new Parser();
$this['root_dir'] = __DIR__ . '/../..';
$this['config_dir'] = __DIR__ . '/Resources/config';
$this['config'] = ['settings' => $yaml->parse(file_get_contents($this['config_dir'] . '/settings.yml')), 'heroes' => $yaml->parse(file_get_contents($this['config_dir'] . '/heroes.yml')), 'items' => $yaml->parse(file_get_contents($this['config_dir'] . '/items.yml')), 'map' => $yaml->parse(file_get_contents($this['config_dir'] . '/map.yml'))];
}
作者:Sententiaregu
项目:LocaleBundl
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$this->bindParameters($container, $this->getAlias(), $config);
// Fallback for missing intl extension
$intlExtensionInstalled = extension_loaded('intl');
$container->setParameter('lunetics_locale.intl_extension_installed', $intlExtensionInstalled);
$iso3166 = array();
$iso639one = array();
$iso639two = array();
$localeScript = array();
if (!$intlExtensionInstalled) {
$yamlParser = new YamlParser();
$file = new FileLocator(__DIR__ . '/../Resources/config');
$iso3166 = $yamlParser->parse(file_get_contents($file->locate('iso3166-1-alpha-2.yml')));
$iso639one = $yamlParser->parse(file_get_contents($file->locate('iso639-1.yml')));
$iso639two = $yamlParser->parse(file_get_contents($file->locate('iso639-2.yml')));
$localeScript = $yamlParser->parse(file_get_contents($file->locate('locale_script.yml')));
}
$container->setParameter('lunetics_locale.intl_extension_fallback.iso3166', $iso3166);
$mergedValues = array_merge($iso639one, $iso639two);
$container->setParameter('lunetics_locale.intl_extension_fallback.iso639', $mergedValues);
$container->setParameter('lunetics_locale.intl_extension_fallback.script', $localeScript);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('validator.xml');
$loader->load('guessers.xml');
$loader->load('services.xml');
$loader->load('switcher.xml');
$loader->load('form.xml');
if (!$config['strict_match']) {
$container->removeDefinition('lunetics_locale.best_locale_matcher');
}
}
作者:amira2
项目:DrupalConsol
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$configName = $input->getArgument('config-name');
$editor = $input->getArgument('editor');
$config = $this->getConfigFactory()->getEditable($configName);
$configSystem = $this->getConfigFactory()->get('system.file');
$temporalyDirectory = $configSystem->get('path.temporary') ?: '/tmp';
$configFile = $temporalyDirectory . '/config-edit/' . $configName . '.yml';
$ymlFile = new Parser();
$fileSystem = new Filesystem();
try {
$fileSystem->mkdir($temporalyDirectory);
$fileSystem->dumpFile($configFile, $this->getYamlConfig($configName));
} catch (IOExceptionInterface $e) {
throw new \Exception($this->trans('commands.config.edit.messages.no-directory') . ' ' . $e->getPath());
}
if (!$editor) {
$editor = $this->getEditor();
}
$processBuilder = new ProcessBuilder(array($editor, $configFile));
$process = $processBuilder->getProcess();
$process->setTty('true');
$process->run();
if ($process->isSuccessful()) {
$value = $ymlFile->parse(file_get_contents($configFile));
$config->setData($value);
$config->save();
$fileSystem->remove($configFile);
}
if (!$process->isSuccessful()) {
throw new \RuntimeException($process->getErrorOutput());
}
}
作者:2marten
项目:web-platfor
/**
* Prepares test environment.
*/
public function setUp()
{
$finder = new Finder();
$finder->files()->in(__DIR__ . '/config/');
$finder->name('*.yml');
$this->dummyParser = $this->getMock('Symfony\\Component\\Yaml\\Parser');
$this->dummyDumper = $this->getMock('Symfony\\Component\\Yaml\\Dumper');
$this->dummyFilesystem = $this->getMock('Symfony\\Component\\Filesystem\\Filesystem');
$dummyDispatcher = $this->getMock('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface');
$dummyDispatcher->expects($this->once())->method('dispatch')->willReturnCallback(function ($name, $event) {
/** @var GroupOptionTypeEvent $event */
$optionTypes = ['acp' => ['twomartens.core' => ['access' => new BooleanOptionType()]]];
$event->addOptions($optionTypes);
});
$this->yamlData = [];
$this->optionData = [];
foreach ($finder as $file) {
/** @var SplFileInfo $file */
$basename = $file->getBasename('.yml');
$this->yamlData[$basename] = Yaml::parse($file->getContents());
$this->optionData[$basename] = ConfigUtil::convertToOptions($this->yamlData[$basename]);
}
$this->dummyParser->expects($this->any())->method('parse')->willReturnCallback(function ($content) {
return Yaml::parse($content);
});
/** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $dummyDispatcher */
$this->groupService = new GroupService($finder, $this->dummyParser, $this->dummyDumper, $this->dummyFilesystem, $dummyDispatcher);
}
作者:justas
项目:symfony2-front-back-structur
public function processFile(array $config)
{
$config = $this->processConfig($config);
$realFile = $config['file'];
$parameterKey = $config['parameter-key'];
$exists = is_file($realFile);
$yamlParser = new Parser();
$action = $exists ? 'Updating' : 'Creating';
$this->io->write(sprintf('<info>%s the "%s" file</info>', $action, $realFile));
// Find the expected params
$expectedValues = $yamlParser->parse(file_get_contents($config['dist-file']));
if (!isset($expectedValues[$parameterKey])) {
throw new \InvalidArgumentException(sprintf('The top-level key %s is missing.', $parameterKey));
}
$expectedParams = (array) $expectedValues[$parameterKey];
// find the actual params
$actualValues = array_merge($expectedValues, array($parameterKey => array()));
if ($exists) {
$existingValues = $yamlParser->parse(file_get_contents($realFile));
if ($existingValues === null) {
$existingValues = array();
}
if (!is_array($existingValues)) {
throw new \InvalidArgumentException(sprintf('The existing "%s" file does not contain an array', $realFile));
}
$actualValues = array_merge($actualValues, $existingValues);
}
$actualValues[$parameterKey] = $this->processParams($config, $expectedParams, (array) $actualValues[$parameterKey]);
if (!is_dir($dir = dirname($realFile))) {
mkdir($dir, 0755, true);
}
file_put_contents($realFile, "# This file is auto-generated during the composer install\n" . Yaml::dump($actualValues, 99));
}
作者:prome
项目:settings_compil
function __construct($configFile)
{
$yaml = new Parser();
$config = $yaml->parse(file_get_contents($configFile));
$processor = new Processor();
$this->config = $processor->processConfiguration(new Schema(), $config);
}
作者:millola
项目:quaver-cor
/**
* Read yml file to load config vars.
*
* @param string $file
*
* @return self
*/
public function loadFile($file = '')
{
try {
$yaml = new Parser();
if (empty($file)) {
$file = GLOBAL_PATH . '/App/Config.yml';
}
$elements = $yaml->parse(file_get_contents($file));
if (!empty($this->vars)) {
$this->vars += $elements;
} else {
$this->vars = $elements;
$this->setParams();
}
// Enable debugBar
if ($this['core']['DEBUG_BAR'] === true) {
$debugbarResourcesPath = '/vendor/maximebf/debugbar/src/DebugBar/Resources';
if (isset($this['app']['RESOURCES'][GLOBAL_PATH . $debugbarResourcesPath])) {
$debugbarResourcesPath = $this['app']['RESOURCES'][GLOBAL_PATH . $debugbarResourcesPath];
}
$this->debugbar = new StandardDebugBar();
$this->debugbarRenderer = $this->debugbar->getJavascriptRenderer($debugbarResourcesPath)->setEnableJqueryNoConflict(false);
$this->debugbar['time']->startMeasure('render');
$this->debugbar->addCollector(new \DebugBar\DataCollector\ConfigCollector($this->vars));
}
return $this;
} catch (ParseException $e) {
throw new QException(sprintf('Unable to parse the YAML string: %s', $e->getMessage()));
}
}
作者:manish43
项目:zfor
/**
* Parses YAML into a PHP array.
*
* The parse method, when supplied with a YAML stream (string or file),
* will do its best to convert YAML in a file into a PHP array.
*
* Usage:
* <code>
* $array = Yaml::parse('config.yml');
* print_r($array);
* </code>
*
* @param string $input Path to a YAML file or a string containing YAML
*
* @return array The YAML converted to a PHP array
*
* @throws \InvalidArgumentException If the YAML is not valid
*
* @api
*/
public static function parse($input)
{
$file = '';
// if input is a file, process it
if (strpos($input, "\n") === false && is_file($input) && is_readable($input)) {
$file = $input;
ob_start();
$retval = (include $input);
$content = ob_get_clean();
// if an array is returned by the config file assume it's in plain php form else in YAML
$input = is_array($retval) ? $retval : $content;
}
// if an array is returned by the config file assume it's in plain php form else in YAML
if (is_array($input)) {
return $input;
}
$yaml = new Parser();
try {
return $yaml->parse($input);
} catch (ParseException $e) {
if ($file) {
$e->setParsedFile($file);
}
throw $e;
}
}
作者:legovae
项目:DrupalConsol
protected function execute(InputInterface $input, OutputInterface $output)
{
$yaml = new Parser();
$dumper = new Dumper();
$yaml_file = $input->getArgument('yaml-file');
$yaml_key = $input->getArgument('yaml-key');
$yaml_value = $input->getArgument('yaml-value');
try {
$yaml_parsed = $yaml->parse(file_get_contents($yaml_file));
} catch (\Exception $e) {
$output->writeln('[+] <error>' . $this->trans('commands.yaml.merge.messages.error-parsing') . ': ' . $e->getMessage() . '</error>');
return;
}
if (empty($yaml_parsed)) {
$output->writeln('[+] <info>' . sprintf($this->trans('commands.yaml.merge.messages.wrong-parse'), $yaml_file) . '</info>');
}
$nested_array = $this->getNestedArrayHelper();
$parents = explode(".", $yaml_key);
$nested_array->setValue($yaml_parsed, $parents, $yaml_value, true);
try {
$yaml = $dumper->dump($yaml_parsed, 10);
} catch (\Exception $e) {
$output->writeln('[+] <error>' . $this->trans('commands.yaml.merge.messages.error-generating') . ': ' . $e->getMessage() . '</error>');
return;
}
try {
file_put_contents($yaml_file, $yaml);
} catch (\Exception $e) {
$output->writeln('[+] <error>' . $this->trans('commands.yaml.merge.messages.error-writing') . ': ' . $e->getMessage() . '</error>');
return;
}
$output->writeln('[+] <info>' . sprintf($this->trans('commands.yaml.update.value.messages.updated'), $yaml_file) . '</info>');
}
作者:jeremycherfa
项目:grav-blo
/**
* Filter value against a blueprint field definition.
*
* @param mixed $value
* @param array $field
* @return mixed Filtered value.
*/
public static function filter($value, array $field)
{
$validate = isset($field['validate']) ? (array) $field['validate'] : array();
// If value isn't required, we will return null if empty value is given.
if (empty($validate['required']) && ($value === null || $value === '')) {
return null;
}
// special case for files, value is never empty and errors with code 4 instead
if (empty($validate['required']) && $field['type'] == 'file' && (isset($value['error']) && ($value['error'] == UPLOAD_ERR_NO_FILE || in_array(UPLOAD_ERR_NO_FILE, $value['error'])))) {
return null;
}
// if this is a YAML field, simply parse it and return the value
if (isset($field['yaml']) && $field['yaml'] === true) {
try {
$yaml = new Parser();
return $yaml->parse($value);
} catch (ParseException $e) {
throw new \RuntimeException($e->getMessage());
}
}
// Validate type with fallback type text.
$type = (string) isset($field['validate']['type']) ? $field['validate']['type'] : $field['type'];
$method = 'filter' . strtr($type, '-', '_');
if (method_exists(__CLASS__, $method)) {
$value = self::$method($value, $validate, $field);
} else {
$value = self::filterText($value, $validate, $field);
}
return $value;
}
作者:TobeyYan
项目:TranslationEditorBundl
public function import($filename)
{
$fname = basename($filename);
$this->output->writeln("Processing <info>" . $filename . "</info>...");
list($name, $locale, $type) = explode('.', $fname);
$this->setIndexes();
switch ($type) {
case 'yml':
$yaml = new Parser();
$value = $yaml->parse(file_get_contents($filename));
$data = $this->getContainer()->get('server_grove_translation_editor.storage_manager')->getCollection()->findOne(array('filename' => $filename));
if (!$data) {
$data = array('filename' => $filename, 'locale' => $locale, 'type' => $type, 'entries' => array());
}
$this->output->writeln(" Found " . count($value) . " entries...");
$data['entries'] = $value;
if (!$this->input->getOption('dry-run')) {
$this->updateValue($data);
}
break;
case 'xliff':
$this->output->writeln(" Skipping, not implemented");
break;
}
}
作者:ldno
项目:GeneratorBundl
public function updateBundleRouting()
{
$filename = $this->parameters['bundlePath'] . '/' . $this->filename;
switch ($this->format) {
case 'yml':
if (file_exists($filename)) {
$current = file_get_contents($filename);
$parser = new Parser();
$array = $parser->parse($current);
} else {
$array = array();
$current = '';
}
if (empty($array[$this->parameters['bundleAlias'] . '_' . $this->parameters['entityUS']])) {
$code = $this->parameters['bundleAlias'] . '_' . $this->parameters['entityUS'] . ':';
$code .= "\n";
$code .= sprintf(" resource: \"@%s/Controller/%sController.php\"", $this->parameters['bundleName'], $this->parameters['entity']);
$code .= "\n";
$code .= sprintf(" type: annotation ");
$code .= "\n \n";
$code .= $current;
if (false === file_put_contents($filename, $code)) {
throw new \RuntimeException('Could not write to routing.yml');
}
}
break;
}
}
作者:hexa2k
项目:typo3-typoscript-lin
/**
* Loads a resource.
*
* @param mixed $resource The resource
* @param string $type The resource type
* @return array
*/
public function load($resource, $type = NULL)
{
$path = $this->locator->locate($resource);
$file = $this->filesystem->openFile($path);
$configValues = $this->yamlParser->parse($file->getContents());
return $configValues;
}
作者:nicolaslebru
项目:OpsiWebManage
public function detailAction($pkg)
{
$paquets = shell_exec("sudo /usr/bin/opsi-admin -rd method getProduct_hash '" . $pkg . "'");
$yaml = new Parser();
$paquets = $yaml->parse($paquets);
return $this->render('OWMBundle:Paquets:detail.html.twig', array('paquets' => $paquets));
}
作者:santhap
项目:ci-mag-cm
public static function readModules()
{
$filePermissions = array();
$permissions = array();
$modulePermissions = array();
foreach (glob(APPPATH . 'modules/*', GLOB_ONLYDIR) as $m) {
$module = substr(strrchr($m, "/"), 1);
$file = $m . '/config/permissions.yml';
if (file_exists($file)) {
$yaml = new Parser();
$perms = $yaml->parse(file_get_contents($file));
$filePermissions[$module] = $perms;
foreach ($perms as $p) {
$permissions[] = $p['name'];
$modulePermissions[$module][] = $p['name'];
// store permission per modules for db entry
// $p['module'] = $module;
// $filePermissions[] = $p;
}
}
}
self::$permissions = $permissions;
self::$filePermissions = $filePermissions;
self::$modulePermissions = $modulePermissions;
}
作者:nicolaslebru
项目:OpsiWebManage
public function modifierAction()
{
$conf = shell_exec("sudo opsi-admin -rd method getNetworkConfig_hash");
$yaml = new Parser();
$conf = $yaml->parse($conf);
return $this->render('OWMBundle:Configuration:modifier.html.twig', array('depotDrive' => $conf['depotDrive'], 'nextBootServiceURL' => $conf['nextBootServiceURL'], 'utilsUrl' => $conf['utilsUrl'], 'configUrl' => $conf['configUrl'], 'utilsDrive' => $conf['utilsDrive'], 'opsiServer' => $conf['opsiServer'], 'nextBootServerType' => $conf['nextBootServerType'], 'depotUrl' => $conf['depotUrl'], 'depotId' => $conf['depotId'], 'configDrive' => $conf['configDrive'], 'winDomain' => $conf['winDomain']));
}
作者:necatikarta
项目:oj
public function configureAction()
{
$data = [];
$data['data']['page'] = 'config';
$parametersFile = __DIR__ . '/../../../../app/config/parameters.yml';
$parametersFileDist = $parametersFile . '.dist';
$formData = new Config();
$parser = new Parser();
if (file_exists($parametersFile)) {
$formDataFile = $parser->parse(file_get_contents($parametersFile));
} else {
$formDataFile = $parser->parse(file_get_contents($parametersFileDist));
}
foreach ($formDataFile['parameters'] as $key => $value) {
$setter = 'set' . implode('', array_map(function ($s) {
return ucfirst($s);
}, explode('_', $key)));
if (method_exists($formData, $setter)) {
$formData->{$setter}($value);
}
}
$form = $this->createForm(new ConfigType(), $formData, ['method' => 'post', 'action' => $this->get('router')->generate('ojs_installer_save_configure')]);
$data['form'] = $form->createView();
return $this->render("OjsInstallerBundle:Default:configure.html.twig", $data);
}
作者:jeyra
项目:DrupalConsol
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new DrupalStyle($input, $output);
$configName = $input->getArgument('name');
$fileName = $input->getArgument('file');
$ymlFile = new Parser();
if (!empty($fileName) && file_exists($fileName)) {
$value = $ymlFile->parse(file_get_contents($fileName));
} else {
$value = $ymlFile->parse(stream_get_contents(fopen("php://stdin", "r")));
}
if (empty($value)) {
$io->error($this->trans('commands.config.import.single.messages.empty-value'));
return;
}
try {
$source_storage = new StorageReplaceDataWrapper($this->configStorage);
$source_storage->replaceData($configName, $value);
$storage_comparer = new StorageComparer($source_storage, $this->configStorage, $this->configManager);
if ($this->configImport($io, $storage_comparer)) {
$io->success(sprintf($this->trans('commands.config.import.single.messages.success'), $configName));
}
} catch (\Exception $e) {
$io->error($e->getMessage());
return 1;
}
}
作者:siwap
项目:siwapp-sf
public function load(ObjectManager $manager)
{
$yaml = new Parser();
// TODO: find a way of obtainin Bundle's path with the help of $this->container
$bpath = $this->container->get('kernel')->getBundle('SiwappEstimateBundle')->getPath();
$value = $yaml->parse(file_get_contents($bpath . '/DataFixtures/estimates.yml'));
foreach ($value['Item'] as $ref => $values) {
$item = new Item();
$estimate = new Estimate();
foreach ($values as $fname => $fvalue) {
if ($fname == 'Estimate') {
$fvalue = $manager->merge($this->getReference($fvalue));
$fvalue->addItem($item);
$manager->persist($fvalue);
}
$method = 'set' . Inflector::camelize($fname);
if (is_callable(array($item, $method))) {
call_user_func(array($item, $method), $fvalue);
}
}
$manager->persist($item);
$manager->flush();
$this->addReference($ref, $item);
}
foreach ($value['ItemTax'] as $ref => $values) {
$item = $this->getReference($values['Item']);
$tax = $this->getReference($values['Tax']);
$item->addTax($tax);
$manager->persist($item);
$manager->flush();
}
}