public function __construct() { parent::__construct(); $this->specs = array(); $this->tests = array(); $parser = new sfYamlParser(); $m = new Proust\Proust(array("enableCache" => true, "cacheDir" => dirname(__FILE__) . "/spec.cache", "compilerOptions" => array("beautify" => false, "includeDynamicPartials" => true))); $m->clearCache(); $methods = array(); foreach (glob(SPEC_DIR . "*.yml") as $file) { $name = str_replace(".yml", "", basename($file)); $contents = file_get_contents($file); /* hack around sfyaml */ $contents = str_replace("!code", "", $contents); $yaml = $parser->parse($contents); $yaml["name"] = $name; $i = 0; foreach ($yaml["tests"] as &$test) { if (array_key_exists("lambda", $test["data"])) { $code = "return function (\$text = \"\") { " . $test["data"]["lambda"]["php"] . " };"; $test["data"]["lambda"] = eval($code); } $name = preg_replace('/[^a-zA-Z0-9]/', '_', $name); $test["method_name"] = "{$name}" . "_" . $i; array_push($methods, array($test["method_name"], $test["template"])); $this->tests[$name . "_{$i}"] = $test; $i++; } $this->specs[$name] = $yaml; } $classCode = $m->compileClass("Specs", $methods); eval($classCode); $m = new Proust\Proust(array("enableCache" => false)); $this->obj = new Specs($m); }
public function __construct($api_conf_file) { $this->api_conf_file = $api_conf_file; if (!class_exists('sfYamlParser')) { $this->api_last_error = "Symfony YAML (https://github.com/fabpot/yaml) not found or misconfigured"; $this->api_created = false; } elseif (!function_exists('curl_init')) { $this->api_last_error = "No support found for cURL (http://www.php.net/manual/en/book.curl.php)"; $this->api_created = false; } elseif (!function_exists('json_decode') || !function_exists('json_encode')) { $this->api_last_error = "No support found for json (http://fr2.php.net/manual/en/book.json.php)"; $this->api_created = false; } else { try { $yaml = new sfYamlParser(); if (!file_exists($api_conf_file) || !is_file($api_conf_file) || !is_readable($api_conf_file)) { $this->api_last_error = "Unable to find/read the YAML api_conf_file : {$api_conf_file}"; $this->api_created = false; } else { $values = $yaml->parse(file_get_contents($api_conf_file)); $this->api_conf = json_decode(json_encode($values)); $this->client_id = $this->api_conf->App->client_id; $this->client_secret = $this->api_conf->App->client_secret; $this->auth_url = $this->api_conf->App->auth_url; $this->access_token_url = $this->api_conf->App->access_token_url; $this->redirect_uri = $this->api_conf->App->redirect_uri; $this->api_base_url = $this->api_conf->App->api_base_url; $this->api_created = true; } } catch (InvalidArgumentException $e) { $this->api_last_error = "Unable to parse the YAML string: " . $e->getMessage(); $this->api_created = false; } } }
/** * Loads YAML into a PHP array. * * The load 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 = sfYaml::load('config.yml'); * print_r($array); * </code> * * @param string $input Path of YAML file or string containing YAML * * @return array The YAML converted to a PHP array * * @throws InvalidArgumentException If the YAML is not valid */ public static function load($input, $encoding = 'UTF-8') { $file = ''; // if input is a file, process it if (strpos($input, "\n") === false && is_file($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; } $mbConvertEncoding = false; $encoding = strtoupper($encoding); if ('UTF-8' != $encoding && function_exists('mb_convert_encoding')) { $input = mb_convert_encoding($input, 'UTF-8', $encoding); $mbConvertEncoding = true; } $yaml = new sfYamlParser(); try { $ret = $yaml->parse($input); } catch (Exception $e) { throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage())); } if ($ret && $mbConvertEncoding) { $ret = self::arrayConvertEncoding($ret, $encoding); } return $ret; }
/** * Handles finding and parsing YAML input as a string or from the contents of a file. * * @see addYAMLConfigFile() on {@link SS_ConfigManifest} from where this logic was taken and adapted. * @param string $source YAML as a string or a filename * @return array */ public function parseYAMLImport($source) { if (is_file($source)) { $source = file_get_contents($source); } require_once 'thirdparty/zend_translate_railsyaml/library/Translate/Adapter/thirdparty/sfYaml/lib/sfYamlParser.php'; $parser = new sfYamlParser(); // Make sure the linefeeds are all converted to \n, PCRE '$' will not match anything else. $convertLF = str_replace(array("\r\n", "\r"), "\n", $source); /* * Remove illegal colons from Transition/Action titles, otherwise sfYamlParser will barf on them * Note: The regex relies on there being single quotes wrapped around these in the export .ss template */ $converted = preg_replace("#('[^:\n][^']+)(:)([^']+')#", "\$1;\$3", $convertLF); $parts = preg_split('#^---$#m', $converted, -1, PREG_SPLIT_NO_EMPTY); // If we got an odd number of parts the config, file doesn't have a header. // We know in advance the number of blocks imported content will have so we settle for a count()==2 check. if (count($parts) != 2) { $msg = _t('WorkflowDefinitionImporter.INVALID_YML_FORMAT_NO_HEADER', 'Invalid YAML format.'); throw new ValidationException($msg); } try { $parsed = $parser->parse($parts[1]); return $parsed; } catch (Exception $e) { $msg = _t('WorkflowDefinitionImporter.INVALID_YML_FORMAT_NO_PARSE', 'Invalid YAML format. Unable to parse.'); throw new ValidationException($msg); } }
/** * Load YAML into a PHP array statically * * The load 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 = sfYAML::Load('config.yml'); * print_r($array); * </code> * * @param string $input Path of YAML file or string containing YAML * * @return array */ public static function load($input) { $file = ''; // if input is a file, process it if (strpos($input, "\n") === false && is_file($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; } require_once dirname(__FILE__) . '/sfYamlParser.class.php'; $yaml = new sfYamlParser(); try { $ret = $yaml->parse($input); } catch (Exception $e) { throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage())); } return $ret; }
function unyaml($file) { static $yaml = false; if (!$yaml) { $yaml = new sfYamlParser(); } $data = $yaml->parse(file_get_contents($file)); $data = fix_comments($data); return $data; }
function yaml_decode($input) { require_once dirname(__FILE__) . '/../lib/yaml/sfYaml.php'; require_once dirname(__FILE__) . '/../lib/yaml/sfYamlParser.php'; $yaml = new sfYamlParser(); try { return $yaml->parse($input); } catch (Exception $e) { return null; } }
/** * Проверяем что из csv получился yaml */ public function testExecuteProducesYaml() { $csvImport = new myImportCsvVkoshelke($this->_csvData); $success = $csvImport->execute($this->_user); $this->assertTrue($success, 'Импорт должен завершиться успешно'); $yaml = $csvImport->getYmlData(); $yamlParser = new sfYamlParser(); $data = $yamlParser->parse($yaml); $this->assertEquals(array('user_id' => $this->_user->getId(), 'date' => '2010-06-08', 'amount' => '20000.00', 'comment' => 'Тане', 'type' => 0, 'Account' => 'Account_1', 'Category' => 'Category_1'), $data['Operation']['Operation_1']); $this->assertEquals(array('user_id' => $this->_user->getId(), 'date' => '2010-06-06', 'amount' => '100.00', 'comment' => '', 'type' => 2, 'Account' => 'Account_2', 'transfer_amount' => '300000.00', 'TransferAccount' => 'Account_1'), $data['Operation']['Operation_4']); }
public function executeStats() { $yaml = new sfYamlParser(); $this->stats = ""; if (file_exists(sfConfig::get('sf_data_dir') . '/stats/stats.yml')) { try { $this->stats = $yaml->parse(file_get_contents(sfConfig::get('sf_data_dir') . '/stats/stats.yml')); } catch (InvalidArgumentException $e) { // an error occurred during parsing echo __("Unable to parse statistics file"); } } }
public static function loadFile($file) { if (!file_exists($file)) { throw new pakeException('file not found: "' . $file . '"'); } if (extension_loaded('yaml')) { return yaml_parse_file($file); } sfYaml::setSpecVersion('1.1'); // more compatible $parser = new sfYamlParser(); return $parser->parse(file_get_contents($file)); }
function yaml_sfyaml_decode($input, $show_error = true) { require_once _DIR_PLUGIN_YAML . 'sfyaml/sfYaml.php'; require_once _DIR_PLUGIN_YAML . 'sfyaml/sfYamlParser.php'; $yaml = new sfYamlParser(); try { $ret = $yaml->parse($input); } catch (Exception $e) { if ($show_error) { throw new InvalidArgumentException(sprintf('Unable to parse string: %s', $e->getMessage())); } else { return false; } } return $ret; }
function unyaml($file) { static $yaml = false; if ($_SERVER['HTTP_HOST'] != 'localhost:8000') { if (cache_exists($file)) { return read_cache($file); } } if (!$yaml) { $yaml = new sfYamlParser(); } $data = $yaml->parse(file_get_contents($file)); $data = fix_comments($data); write_cache($file, $data); return $data; }
public static function loadString($input) { if (extension_loaded('yaml')) { $retval = yaml_parse($input); if (false === $retval) { throw new pakeException("empty yaml document"); } } else { sfYaml::setSpecVersion('1.1'); // more compatible $parser = new sfYamlParser(); $retval = $parser->parse($input); if (null === $retval) { throw new pakeException("empty yaml document"); } } return $retval; }
private function __construct() { //try to figure out the environment if (file_exists('/serverConfig/serverConfig.ini')) { $serverConfig = parse_ini_file('/serverConfig/serverConfig.ini', true); $this->env = $serverConfig['serverType']; } //parse the config file $configFile = sfConfig::get('sf_config_dir') . '/server_env.yml'; if (file_exists($configFile)) { $yaml = new sfYamlParser(); $allOptions = $yaml->parse(file_get_contents($configFile)); if (isset($allOptions[$this->env])) { $this->options = $allOptions[$this->env]; } } else { throw new exception('The \'server_env.yml\' file is missing!'); } }
/** * Data provider for the mustache spec test. * * Loads YAML files from the spec and converts them to PHPisms. * * @param string $name * * @return array */ protected function loadSpec($name) { $filename = dirname(__FILE__) . '/../../../vendor/spec/specs/' . $name . '.yml'; if (!file_exists($filename)) { return array(); } $data = array(); $yaml = new sfYamlParser(); $file = file_get_contents($filename); // @hack: pre-process the 'lambdas' spec so the Symfony YAML parser doesn't complain. if ($name === '~lambdas') { $file = str_replace(" !code\n", "\n", $file); } $spec = $yaml->parse($file); foreach ($spec['tests'] as $test) { $data[] = array($test['name'] . ': ' . $test['desc'], $test['template'], isset($test['partials']) ? $test['partials'] : array(), $test['data'], $test['expected']); } return $data; }
/** * Read any data stored in $data, using options in $options. * * @param string $data The data to read. * @param array $options The options for reading data. * @return string * @access public */ public function input($data, $options = array()) { include_once CURATOR_APP_DIR . DS . 'Vendors' . DS . 'yaml' . DS . 'lib' . DS . 'sfYamlParser.php'; $yaml = new \sfYamlParser(); $result = null; try { if (strpos($data, NL) === false && is_file($data)) { $data = file_get_contents($data); if ($data === false) { throw new \Exception('Could not load yaml: ' . $data); } } $result = $yaml->parse($data); } catch (\InvalidArgumentException $e) { \Curator\Console::stderr('** Unable to parse the YAML string:'); \Curator\Console::stderr(' ' . $e->getMessage()); } catch (\Exception $e) { \Curator\Console::stderr('** Could not handle YAML data:'); \Curator\Console::stderr(' ' . $e->getMessage()); } return $result; }
public static function load($string, $forgiving = false) { if (substr($string, 0, 3) != '---') { $string = "---\n{$string}"; } try { // if syck is available use it if (extension_loaded('syck')) { return syck_load($string); } // if not, use the symfony YAML parser $yaml = new sfYamlParser(); return $yaml->parse($string); } catch (Exception $e) { if ($forgiving) { // if YAML document is not correct, // but we're forgiving, use the Spyc parser return Spyc::YAMLLoadString($string); } throw new Wikidot_Yaml_Exception("Can't parse the YAML string." . $e->getMessage()); } }
public static function load($input) { $file = ''; if (strpos($input, "\n") === false && is_file($input)) { $file = $input; ob_start(); $retval = (include $input); $content = ob_get_clean(); $input = is_array($retval) ? $retval : $content; } if (is_array($input)) { return $input; } require_once dirname(__FILE__) . '/sfYamlParser.php'; $yaml = new sfYamlParser(); try { $ret = $yaml->parse($input); } catch (Exception $e) { throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage())); } return $ret; }
<?php /* * This file is part of the symfony package. * (c) Fabien Potencier <*****@*****.**> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require_once __DIR__ . '/../../bootstrap/unit.php'; sfYaml::setSpecVersion('1.1'); $t = new lime_test(150); $parser = new sfYamlParser(); $path = __DIR__ . '/fixtures'; $files = $parser->parse(file_get_contents($path . '/index.yml')); foreach ($files as $file) { $t->diag($file); $yamls = file_get_contents($path . '/' . $file . '.yml'); // split YAMLs documents foreach (preg_split('/^---( %YAML\\:1\\.0)?/m', $yamls) as $yaml) { if (!$yaml) { continue; } $test = $parser->parse($yaml); if (isset($test['todo']) && $test['todo']) { $t->todo($test['test']); } else { $expected = var_export(eval('return ' . trim($test['php']) . ';'), true); $t->is(var_export($parser->parse($test['yaml']), true), $expected, $test['test']); } }
/** * Parses a YAML string to a PHP value. * * @param string $value A YAML string * * @return mixed A PHP value */ public function parse($value) { $this->value = $this->cleanup($value); $this->currentLineNb = -1; $this->currentLine = ''; $this->lines = explode("\n", $this->value); $data = array(); while ($this->moveToNextLine()) { if ($this->isCurrentLineEmpty()) { continue; } // tab? if (preg_match('#^\\t+#', $this->currentLine)) { throw new InvalidArgumentException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine)); } $isRef = $isInPlace = $isProcessed = false; if (preg_match('#^\\-(\\s+(?P<value>.+?))?\\s*$#', $this->currentLine, $values)) { if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#', $values['value'], $matches)) { $isRef = $matches['ref']; $values['value'] = $matches['value']; } // array if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { $c = $this->getRealCurrentLineNb() + 1; $parser = new sfYamlParser($c); $parser->refs =& $this->refs; $data[] = $parser->parse($this->getNextEmbedBlock()); } else { if (preg_match('/^([^ ]+)\\: +({.*?)$/', $values['value'], $matches)) { $data[] = array($matches[1] => sfYamlInline::load($matches[2])); } else { $data[] = $this->parseValue($values['value']); } } } else { if (preg_match('#^(?P<key>[^ ].*?) *\\:(\\s+(?P<value>.+?))?\\s*$#', $this->currentLine, $values)) { $key = sfYamlInline::parseScalar($values['key']); if ('<<' === $key) { if (isset($values['value']) && '*' === substr($values['value'], 0, 1)) { $isInPlace = substr($values['value'], 1); if (!array_key_exists($isInPlace, $this->refs)) { throw new InvalidArgumentException(sprintf('Reference "%s" does not exist at line %s (%s).', $isInPlace, $this->getRealCurrentLineNb() + 1, $this->currentLine)); } } else { if (isset($values['value']) && $values['value'] !== '') { $value = $values['value']; } else { $value = $this->getNextEmbedBlock(); } $c = $this->getRealCurrentLineNb() + 1; $parser = new sfYamlParser($c); $parser->refs =& $this->refs; $parsed = $parser->parse($value); $merged = array(); if (!is_array($parsed)) { throw new InvalidArgumentException(sprintf("YAML merge keys used with a scalar value instead of an array at line %s (%s)", $this->getRealCurrentLineNb() + 1, $this->currentLine)); } else { if (isset($parsed[0])) { // Numeric array, merge individual elements foreach (array_reverse($parsed) as $parsedItem) { if (!is_array($parsedItem)) { throw new InvalidArgumentException(sprintf("Merge items must be arrays at line %s (%s).", $this->getRealCurrentLineNb() + 1, $parsedItem)); } $merged = array_merge($parsedItem, $merged); } } else { // Associative array, merge $merged = array_merge($merge, $parsed); } } $isProcessed = $merged; } } else { if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#', $values['value'], $matches)) { $isRef = $matches['ref']; $values['value'] = $matches['value']; } } if ($isProcessed) { // Merge keys $data = $isProcessed; } else { if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { // if next line is less indented or equal, then it means that the current value is null if ($this->isNextLineIndented()) { $data[$key] = null; } else { $c = $this->getRealCurrentLineNb() + 1; $parser = new sfYamlParser($c); $parser->refs =& $this->refs; $data[$key] = $parser->parse($this->getNextEmbedBlock()); } } else { if ($isInPlace) { $data = $this->refs[$isInPlace]; } else { $data[$key] = $this->parseValue($values['value']); } } } } else { // one liner? if (1 == count(explode("\n", rtrim($this->value, "\n")))) { $value = sfYamlInline::load($this->lines[0]); if (is_array($value)) { $first = reset($value); if ('*' === substr($first, 0, 1)) { $data = array(); foreach ($value as $alias) { $data[] = $this->refs[substr($alias, 1)]; } $value = $data; } } return $value; } throw new InvalidArgumentException(sprintf('Unable to parse line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine)); } } if ($isRef) { $this->refs[$isRef] = end($data); } } return empty($data) ? null : $data; }
/** * Handle finding a yml file. Parse the file by spliting it into header/fragment pairs, * and normalising some of the header values (especially: give anonymous name if none assigned, * splt/complete before and after matchers) * * Public so that ManifestFileFinder can call it. Not for general use. */ public function addYAMLConfigFile($basename, $pathname, $depth) { if (!preg_match('{/([^/]+)/_config/}', $pathname, $match)) return; // Keep track of all the modules we've seen $this->addModule(dirname(dirname($pathname))); // Use the Zend copy of this script to prevent class conflicts when RailsYaml is included require_once 'thirdparty/zend_translate_railsyaml/library/Translate/Adapter/thirdparty/sfYaml/lib/sfYamlParser.php'; $parser = new sfYamlParser(); // The base header $base = array( 'module' => $match[1], 'file' => basename(basename($basename, '.yml'), '.yaml') ); // Make sure the linefeeds are all converted to \n, PCRE '$' will not match anything else. $fileContents = str_replace(array("\r\n", "\r"), "\n", file_get_contents($pathname)); // YAML parsers really should handle this properly themselves, but neither spyc nor symfony-yaml do. So we // follow in their vein and just do what we need, not what the spec says $parts = preg_split('/^---$/m', $fileContents, -1, PREG_SPLIT_NO_EMPTY); // If only one document, it's a headerless fragment. So just add it with an anonymous name if (count($parts) == 1) { $this->yamlConfigFragments[] = $base + array( 'name' => 'anonymous-1', 'fragment' => $parser->parse($parts[0]) ); } // Otherwise it's a set of header/document pairs else { // If we got an odd number of parts the config file doesn't have a header for every document if (count($parts) % 2 != 0) user_error("Configuration file $basename does not have an equal number of headers and config blocks"); // Step through each pair for ($i = 0; $i < count($parts); $i+=2) { // Make all the first-level keys of the header lower case $header = array_change_key_case($parser->parse($parts[$i]), CASE_LOWER); // Assign a name if non assigned already if (!isset($header['name'])) $header['name'] = 'anonymous-'.(1+$i/2); // Parse & normalise the before and after if present foreach (array('before', 'after') as $order) { if (isset($header[$order])) { // First, splice into parts (multiple before or after parts are allowed, comma separated) $orderparts = preg_split('/\s+,\s+/', $header[$order], PREG_SPLIT_NO_EMPTY); // For each, parse out into module/file#name, and set any missing to "*" $header[$order] = array(); foreach($orderparts as $part) { preg_match('! (\*|\w+) (?:\/(\*|\w+) (?:\*|\#(\w+))? )? !x', $part, $match); $header[$order][] = array( 'module' => $match[1], 'file' => isset($match[2]) ? $match[2] : '*', 'name' => isset($match[3]) ? $match[3] : '*' ); } } } // And add to the fragments list $this->yamlConfigFragments[] = $base + $header + array( 'fragment' => $parser->parse($parts[$i+1]) ); } } }
private static function parseFile($path) { ob_start(); require $path; $config = ob_get_clean(); require_once 'vendor/yaml/lib/sfYamlParser.php'; $yaml = new \sfYamlParser(); return $yaml->parse($config); }
/** * Parse a YAML String */ public function parseYamlString($contents) { $contents = $this->ensureYamlString($contents); $Yaml = new sfYamlParser(); return $Yaml->parse($contents); }
/** * Data provider for the mustache spec test. * * Loads YAML files from the spec and converts them to PHPisms. * * @access public * @return array */ protected function loadSpec($name) { $filename = dirname(__FILE__) . '/spec/specs/' . $name . '.yml'; if (!file_exists($filename)) { return array(); } $data = array(); $yaml = new sfYamlParser(); $spec = $yaml->parse(file_get_contents($filename)); foreach ($spec['tests'] as $test) { $data[] = array($test['name'] . ': ' . $test['desc'], $test['template'], $test['data'], isset($test['partials']) ? $test['partials'] : array(), $test['expected']); } return $data; }
private function __construct() { $yaml = new sfYamlParser(); self::$aSettings = $yaml->parse(file_get_contents(__DIR__ . '/config/schema.yml')); }
<?php /* * This file is part of the symfony package. * (c) Fabien Potencier <*****@*****.**> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require_once dirname(__FILE__) . '/../../bootstrap/unit.php'; sfYaml::setSpecVersion('1.1'); $t = new lime_test(149); $parser = new sfYamlParser(); $dumper = new sfYamlDumper(); $path = dirname(__FILE__) . '/fixtures'; $files = $parser->parse(file_get_contents($path . '/index.yml')); foreach ($files as $file) { $t->diag($file); $yamls = file_get_contents($path . '/' . $file . '.yml'); // split YAMLs documents foreach (preg_split('/^---( %YAML\\:1\\.0)?/m', $yamls) as $yaml) { if (!$yaml) { continue; } $test = $parser->parse($yaml); if (isset($test['dump_skip']) && $test['dump_skip']) { continue; } else { if (isset($test['todo']) && $test['todo']) { $t->todo($test['test']); } else {
public static function parse($yaml_path) { $yamlParser = new sfYamlParser(); return $yamlParser->parse($yaml_path); }
/** * Parses a YAML string to a PHP value. * * @param string $value A YAML string * * @return mixed A PHP value * * @throws InvalidArgumentException If the YAML is not valid */ public function parse($value) { $this->currentLineNb = -1; $this->currentLine = ''; $this->lines = explode("\n", $this->cleanup($value)); if (function_exists('mb_internal_encoding') && (int) ini_get('mbstring.func_overload') & 2) { $mbEncoding = mb_internal_encoding(); mb_internal_encoding('UTF-8'); } $data = array(); while ($this->moveToNextLine()) { if ($this->isCurrentLineEmpty()) { continue; } // tab? if (preg_match('#^\\t+#', $this->currentLine)) { throw new InvalidArgumentException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine)); } $isRef = $isInPlace = $isProcessed = false; if (preg_match('#^\\-(\\s+(?P<value>.+?))?\\s*$#u', $this->currentLine, $values)) { if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) { $isRef = $matches['ref']; $values['value'] = $matches['value']; } // array if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { $c = $this->getRealCurrentLineNb() + 1; $parser = new sfYamlParser($c); $parser->refs =& $this->refs; $data[] = $parser->parse($this->getNextEmbedBlock()); } else { if (preg_match('/^([^ ]+)\\: +({.*?)$/u', $values['value'], $matches)) { $data[] = array($matches[1] => sfYamlInline::load($matches[2])); } else { $data[] = $this->parseValue($values['value']); } } } else { if (preg_match('#^(?P<key>' . sfYamlInline::REGEX_QUOTED_STRING . '|[^ ].*?) *\\:(\\s+(?P<value>.+?))?\\s*$#u', $this->currentLine, $values)) { $key = sfYamlInline::parseScalar($values['key']); if ('<<' === $key) { if (isset($values['value']) && '*' === substr($values['value'], 0, 1)) { $isInPlace = substr($values['value'], 1); if (!array_key_exists($isInPlace, $this->refs)) { throw new InvalidArgumentException(sprintf('Reference "%s" does not exist at line %s (%s).', $isInPlace, $this->getRealCurrentLineNb() + 1, $this->currentLine)); } } else { if (isset($values['value']) && $values['value'] !== '') { $value = $values['value']; } else { $value = $this->getNextEmbedBlock(); } $c = $this->getRealCurrentLineNb() + 1; $parser = new sfYamlParser($c); $parser->refs =& $this->refs; $parsed = $parser->parse($value); $merged = array(); if (!is_array($parsed)) { throw new InvalidArgumentException(sprintf("YAML merge keys used with a scalar value instead of an array at line %s (%s)", $this->getRealCurrentLineNb() + 1, $this->currentLine)); } else { if (isset($parsed[0])) { // Numeric array, merge individual elements foreach (array_reverse($parsed) as $parsedItem) { if (!is_array($parsedItem)) { throw new InvalidArgumentException(sprintf("Merge items must be arrays at line %s (%s).", $this->getRealCurrentLineNb() + 1, $parsedItem)); } $merged = array_merge($parsedItem, $merged); } } else { // Associative array, merge $merged = array_merge($merge, $parsed); } } $isProcessed = $merged; } } else { if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) { $isRef = $matches['ref']; $values['value'] = $matches['value']; } } if ($isProcessed) { // Merge keys $data = $isProcessed; } else { if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { // if next line is less indented or equal, then it means that the current value is null if ($this->isNextLineIndented()) { $data[$key] = null; } else { $c = $this->getRealCurrentLineNb() + 1; $parser = new sfYamlParser($c); $parser->refs =& $this->refs; $data[$key] = $parser->parse($this->getNextEmbedBlock()); } } else { if ($isInPlace) { $data = $this->refs[$isInPlace]; } else { $data[$key] = $this->parseValue($values['value']); } } } } else { // 1-liner followed by newline if (2 == count($this->lines) && empty($this->lines[1])) { $value = sfYamlInline::load($this->lines[0]); if (is_array($value)) { $first = reset($value); if ('*' === substr($first, 0, 1)) { $data = array(); foreach ($value as $alias) { $data[] = $this->refs[substr($alias, 1)]; } $value = $data; } } if (isset($mbEncoding)) { mb_internal_encoding($mbEncoding); } return $value; } switch (preg_last_error()) { case PREG_INTERNAL_ERROR: $error = 'Internal PCRE error on line'; break; case PREG_BACKTRACK_LIMIT_ERROR: $error = 'pcre.backtrack_limit reached on line'; break; case PREG_RECURSION_LIMIT_ERROR: $error = 'pcre.recursion_limit reached on line'; break; case PREG_BAD_UTF8_ERROR: $error = 'Malformed UTF-8 data on line'; break; case PREG_BAD_UTF8_OFFSET_ERROR: $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point on line'; break; default: $error = 'Unable to parse line'; } throw new InvalidArgumentException(sprintf('%s %d (%s).', $error, $this->getRealCurrentLineNb() + 1, $this->currentLine)); } } if ($isRef) { $this->refs[$isRef] = end($data); } } if (isset($mbEncoding)) { mb_internal_encoding($mbEncoding); } return empty($data) ? null : $data; }
/** * Loads YAML into a PHP array. * * The load 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 = sfYaml::load('config.yml'); * print_r($array); * </code> * * @param string $input Path of YAML file or string containing YAML * * @return array The YAML converted to a PHP array * * @throws InvalidArgumentException If the YAML is not valid */ public static function load($input) { $file = ''; // if input is a file, load it if (strpos($input, "\n") === false && is_file($input)) { $file = $input; $content = $yaml = file_get_contents($input); // if the file contains valid PHP, process it if (strpos($content, '<' . '?') !== false and !(defined('_YAML_EVAL_PHP') and !_YAML_EVAL_PHP)) { ob_start(); $retval = eval('?' . '>' . $yaml); $content = ob_get_clean(); // syntax error? if ($retval === FALSE) { $content = $yaml; } } // 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; } require_once dirname(__FILE__) . '/sfYamlParser.php'; $yaml = new sfYamlParser(); try { $ret = $yaml->parse($input); } catch (Exception $e) { throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage())); } return $ret; }
/** * Parses a YAML string to a PHP value. * * @param string A YAML string * * @return mixed A PHP value */ public function parse($value) { $this->value = $this->cleanup($value); $this->currentLineNb = -1; $this->currentLine = ''; $this->lines = explode("\n", $this->value); $data = array(); while ($this->moveToNextLine()) { if ($this->isCurrentLineEmpty()) { continue; } // tab? if (preg_match('#^\\t+#', $this->currentLine)) { throw new InvalidArgumentException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb(), $this->currentLine)); } $isRef = $isInPlace = false; if (preg_match('#^\\-(\\s+(?P<value>.+?))?\\s*$#', $this->currentLine, $values)) { if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#', $values['value'], $matches)) { $isRef = $matches['ref']; $values['value'] = $matches['value']; } // array if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { $c = $this->getRealCurrentLineNb() + 1; $parser = new sfYamlParser($c); $parser->refs =& $this->refs; $data[] = $parser->parse($this->getNextEmbedBlock()); } else { if (preg_match('/^([^ ]+)\\: +({.*?)$/', $values['value'], $matches)) { $data[] = array($matches[1] => sfYamlInline::load($matches[2])); } else { $data[] = $this->parseValue($values['value']); } } } else { if (preg_match('#^(?P<key>[^ ].*?) *\\:(\\s+(?P<value>.+?))?\\s*$#', $this->currentLine, $values)) { $key = sfYamlInline::parseScalar($values['key']); if ('<<' === $key) { if (isset($values['value']) && '*' === substr($values['value'], 0, 1)) { $isInPlace = substr($values['value'], 1); if (!array_key_exists($isInPlace, $this->refs)) { throw new InvalidArgumentException(sprintf('Reference "%s" does not exist on line %s.', $isInPlace, $this->currentLine)); } } else { throw new InvalidArgumentException(sprintf('In place substitution must point to a reference on line %s.', $this->currentLine)); } } else { if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#', $values['value'], $matches)) { $isRef = $matches['ref']; $values['value'] = $matches['value']; } } // hash if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { // if next line is less indented or equal, then it means that the current value is null if ($this->isNextLineIndented()) { $data[$key] = null; } else { $c = $this->getRealCurrentLineNb() + 1; $parser = new sfYamlParser($c); $parser->refs =& $this->refs; $data[$key] = $parser->parse($this->getNextEmbedBlock()); } } else { if ($isInPlace) { $data = $this->refs[$isInPlace]; } else { $data[$key] = $this->parseValue($values['value']); } } } else { // one liner? if (1 == count(explode("\n", rtrim($this->value, "\n")))) { return sfYamlInline::load($this->lines[0]); } throw new InvalidArgumentException(sprintf('Unable to parse line %d (%s).', $this->getRealCurrentLineNb(), $this->currentLine)); } } if ($isRef) { $this->refs[$isRef] = end($data); } } return empty($data) ? null : $data; }