/** * Load configuration file by it's type and put it into a Zend_Config object * * @param string $configFile Configuration file path * @param string $fileType Configuration file type * @param string $section Configuration section to load * @return Zend_Config */ public static function load($configFile, $fileType = self::YAML, $section = 'default') { switch ($fileType) { case self::YAML: $yaml = file_get_contents($configFile); if (extension_loaded('syck')) { $data = syck_load($yaml); } else { require_once 'Spyc.php'; $data = Spyc::YAMLLoad($yaml); } require_once 'Zend/Config.php'; return new Zend_Config($data[$section]); break; case self::INI: require_once 'Zend/Config/Ini.php'; return new Zend_Config_Ini($configFile, $section); break; case self::XML: require_once 'Zend/Config/Xml.php'; return new Zend_Config_Xml($configFile, $section); break; default: require_once 'Spizer/Exception.php'; throw new Spizer_Exception("Configuration files of type '{$fileType}' are not (yet?) supported"); break; } }
protected function load_translation_file($file) { if (!function_exists('syck_load')) throw new SI18nException('Syck extension is not installed'); return syck_load(file_get_contents($file)); }
public static function loadFile($file) { if (function_exists('yaml_parse_file')) { // returns array() if no data, NULL if error. $a = yaml_parse_file($file); if ($a === NULL || $a === false) { throw new WFException("Error processing YAML file: {$file}"); } return $a; } else { if (function_exists('syck_load')) { // php-lib-c version, much faster! // ******* NOTE: if using libsyck with PHP, you should install from pear/pecl (http://trac.symfony-project.com/wiki/InstallingSyck) // ******* NOTE: as it escalates YAML syntax errors to PHP Exceptions. // ******* NOTE: without this, if your YAML has a syntax error, you will be really confused when trying to debug it b/c syck_load will just return NULL. $yaml = NULL; $yamlfile = file_get_contents($file); if (strlen($yamlfile) != 0) { $yaml = syck_load($yamlfile); } if ($yaml === NULL) { $yaml = array(); } return $yaml; } else { // php version return Horde_Yaml::loadFile($file); } } }
public static function load($filename) { // cache object # $oCache = Days_Cache::instance(); // load configuration file from cache # if ($oCache->isCached($filename)) { # $config = $oCache->getCache($filename); # } // load configuration file and set to cache # else { // check file if (!file_exists($filename)) { throw new Days_Exception("Configuration file '{$filename}' not found"); } // use fast Yaml module for php (if exists) if (function_exists('syck_load')) { $config = syck_load(file_get_contents($filename)); } else { $config = Spyc::YAMLLoad($filename); } // renew cache # $oCache->setCache($filename, $config); # } // return result array return $config; }
public function load($file_name) { if (($file = file_get_contents($file_name)) !== false) { return syck_load($file); } YamlErrors::fileNotFound($file_name); return null; }
static function get($path, $graceful = false) { // TODO: Implement using http://spyc.sourceforge.net/ if syck is not available if ($graceful) { $content = midcom_core_helpers_snippet::get_contents_graceful($path); } else { $content = midcom_core_helpers_snippet::get_contents($path); } return syck_load($content); }
/** * Loads any .yml file * @return array */ private static function load_yaml($config_file) { if (is_readable($config_file)) { if (function_exists("syck_load")) { return syck_load(file_get_contents($config_file)); } else { return Spyc::YAMLLoad($config_file); } } else { return false; } }
public function testSimple() { $yaml = <<<YAML --- define: &pointer_to_define - 1 - 2 - 3 reference: *pointer_to_define YAML; $arr = syck_load($yaml); $this->assertEquals($arr['define'], $arr['reference']); }
public static function load($input) { // syck is prefered over spyc if (function_exists('syck_load')) { if (!empty($input) && is_readable($input)) { $input = file_get_contents($input); } return syck_load($input); } else { $spyc = new pakeSpyc(); return $spyc->load($input); } }
/** * Transform data and return the result. * * @param string $data Yaml string or file * @return array */ public function process($data) { if ($this->chainInput) { $data = $this->chainInput->process($data); } if ($data instanceof Fs_Node) { $data = $data->getContents(); } else { $data = (string) $data; } $data = syck_load($data); return $data; }
function yaml_load($input = null) { if (is_null($input)) { return array(); } $input = yaml_include_contents($input); if (is_array($input)) { return $input; } if (function_exists('syck_load')) { $datas = syck_load($input); return is_array($datas) ? $datas : array(); } else { return spyc_load($input); } }
/** * 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> * * @return array * @param string $input Path of YAML file or string containing YAML */ public static function load($input) { $input = self::getIncludeContents($input); // 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; } // syck is prefered over spyc if (function_exists('syck_load')) { $retval = syck_load($input); return is_array($retval) ? $retval : array(); } else { require_once dirname(__FILE__) . '/Spyc.class.php'; $spyc = new Spyc(); return $spyc->load($input); } }
/** * @param $text string * @return array * @throws MWException */ public static function loadString( $text ) { global $wgTranslateYamlLibrary; switch ( $wgTranslateYamlLibrary ) { case 'spyc': require_once( dirname( __FILE__ ) . '/../spyc/spyc.php' ); $yaml = spyc_load( $text ); return self::fixSpycSpaces( $yaml ); case 'syck': $yaml = self::syckLoad( $text ); return self::fixSyckBooleans( $yaml ); case 'syck-pecl': $text = preg_replace( '~^(\s*)no(\s*:\s*[a-zA-Z-_]+\s*)$~m', '\1"no"\2', $text ); return syck_load( $text ); default: throw new MWException( "Unknown Yaml library" ); } }
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()); } }
private function loadWithSource($Source) { if (empty($Source)) { return array(); } if ($this->setting_use_syck_is_possible && function_exists('syck_load')) { $array = syck_load(implode("\n", $Source)); return is_array($array) ? $array : array(); } $this->path = array(); $this->result = array(); $cnt = count($Source); for ($i = 0; $i < $cnt; $i++) { $line = $Source[$i]; $this->indent = strlen($line) - strlen(ltrim($line)); $tempPath = $this->getParentPathByIndent($this->indent); $line = self::stripIndent($line, $this->indent); if (self::isComment($line)) { continue; } if (self::isEmpty($line)) { continue; } $this->path = $tempPath; $literalBlockStyle = self::startsLiteralBlock($line); if ($literalBlockStyle) { $line = rtrim($line, $literalBlockStyle . " \n"); $literalBlock = ''; $line .= ' ' . $this->LiteralPlaceHolder; $literal_block_indent = strlen($Source[$i + 1]) - strlen(ltrim($Source[$i + 1])); while (++$i < $cnt && $this->literalBlockContinues($Source[$i], $this->indent)) { $literalBlock = $this->addLiteralLine($literalBlock, $Source[$i], $literalBlockStyle, $literal_block_indent); } $i--; } // Strip out comments if (strpos($line, '#')) { $line = preg_replace('/\\s*#([^"\']+)$/', '', $line); } while (++$i < $cnt && self::greedilyNeedNextLine($line)) { $line = rtrim($line, " \n\t\r") . ' ' . ltrim($Source[$i], " \t"); } $i--; $lineArray = $this->_parseLine($line); if ($literalBlockStyle) { $lineArray = $this->revertLiteralPlaceHolder($lineArray, $literalBlock); } $this->addArray($lineArray, $this->indent); foreach ($this->delayedPath as $indent => $delayedPath) { $this->path[$indent] = $delayedPath; } $this->delayedPath = array(); } return $this->result; }
echo "+----------+{$br}"; if (function_exists('date_create')) { eval('class MyDateTime extends DateTime { static public function create($timestamp) { return new MyDateTime($timestamp); } public function __toString() { return $this->format(self::ISO8601); } }'); var_dump($y = yaml_parse($data, 0, $ndocs, array('tag:yaml.org,2002:timestamp' => array('MyDateTime', 'create')))); } else { var_dump($y = yaml_parse($data)); } echo $br; echo "+----------+{$br}"; echo "| Syck |{$br}"; echo "+----------+{$br}"; var_dump($s = syck_load($data)); $s = array(); echo $br; echo "+----------+{$br}"; echo "| diff |{$br}"; echo "+----------+{$br}"; if (gettype($y) != gettype($s)) { var_dump(false); } elseif (is_array($y)) { var_dump(array_diff($y, $s)); } else { var_dump($y == $s); }
/** * * @param $file * @return unknown_type */ public function parseSchema($file) { if (!extension_loaded('syck')) { throw new Exception('The syck extension is required'); } // One can also use this: Doctrine_Parser::load('test.yml', 'yml'); /* load the yaml data from the filesystem */ try { $schema = syck_load(file_get_contents('/srv/www/courses/htdocs/Data/Db/courses_schema.yml')); } catch (SyckException $e) { echo self::INVALID_SCHEMA; echo $e->getMessage(); echo $e->getFile(); echo $e->getLine(); } return $schema; }
function startMigration($file, $direction) { $yml = $this->_parsePhp($file); if (function_exists('syck_load')) { $array = @syck_load($yml); } else { vendor('Spyc'); $array = Spyc::YAMLLoad($yml); } if (!is_array($array)) { return "Unable to parse YAML Migration file"; } if (!$array[up($direction)]) { return "Direction does not exist!"; } return $this->_array_to_sql($array[up($direction)]); }
private static function _buildMenu() { $app = KX_CURRENT_APP; if (KX_CURRENT_APP == 'core' && !isset(kxEnv::$request['module']) && !isset(kxEnv::$request['app'])) { $modules = array(array('module_file' => 'index')); } else { $modules = kxDB::getinstance()->select("modules", "", array('fetch' => PDO::FETCH_ASSOC))->fields("modules", array("module_name", "module_file"))->condition("module_application", $app)->condition("module_manage", 1)->orderBy("module_position")->execute()->fetchAll(); } //print_r($modules); foreach ($modules as $module) { $_file = kxFunc::getAppDir($app) . "/modules/manage/" . $module['module_file'] . '/menu.yml'; //echo "<p>Getting menu from {$_file}</p>"; if (file_exists($_file)) { if (function_exists("syck_load")) { $menu[$module['module_file']] = syck_load(file_get_contents($_file)); } else { $menu[$module['module_file']] = spyc_load_file($_file); } self::assign('menu', $menu); self::assign('module', $module['module_file']); } } }
public function testLargeArrays() { $obj = range(1, 10000); $this->assertSame($obj, syck_load(syck_dump($obj))); }
public function testBugPECL_14384() { $broken_string = 'test: var: value var2: value2'; try { syck_load($broken_string); $this->assertTrue(false); } catch (SyckException $e) { $this->assertTrue(true); } }
/** * 連想配列の取得 * * <pre> * PHPの連想配列を指定すればそのまま、ファイルパスを指定すれば * 設定ファイルから読み込み連想配列として渡します。 * またURLのクエリー形式も使用できます。 * BEARで広く使われています。BEARの全てのクラスのコンストラクタ * (シングルトン含む)、リソースへの引数、 * オプションにこの連想配列フォーマットが使われます。 * * array -- 連想配列としてオプションが入力されます * * string -- ファイルから拡張子によりフォーマットが異なります * URLクエリー形式 ?foo1=bar1&hoge=fugaのようなフォーマットを連想配列にします * *.ini iniフォーマット * *.xml XMLフォーマット * *.php phpのdefineが連想配列として読み込まれます * *.yml yamlファイル * * $options * 'extention' string オーバーロード拡張子 * </pre> * * @param mixed $target ターゲット ファイルパス,URLなど * @param array $options オプション * * @return array * * @see http://pear.php.net/manual/ja/package.configuration.config.php * @see BEAR/test/files/example.ini * @see BEAR/test/files/example.xml * @see BEAR/test/files/example.php * @throws BEAR_Exception */ public static function loadValues($target, $options = array()) { if (!is_file((string) $target)) { // arrayならそのまま if (is_array($target) || is_object($target)) { return (array) $target; } // false | null なら 設定な if (!$target) { return null; } // クエリーがあるときはクエリーをパースした連想配列を返す $parseUrl = parse_url($target); if (isset($parseUrl['query'])) { $options = array(); parse_str($parseUrl['query'], $options); return $options; } else { return null; } } else { $cache = self::factory('BEAR_Cache'); $cache->setLife(BEAR_Cache::LIFE_UNLIMITED); $key = $target . filemtime($target); $cacheResult = $cache->get($key); if ($cacheResult) { return $cacheResult; } // PEAR::Configを使って設定ファイルをパース $pathinfo = pathinfo($target); // 相対パスなら絶対パスに (/:linux :win) $target = substr($target, 0, 1) == '/' || substr($target, 1, 1) == ':' ? $target : _BEAR_APP_HOME . '/App/Ro/' . $target; $extension = isset($options['extention']) ? $options['extention'] : $pathinfo['extension']; switch ($extension) { case 'yml': if (function_exists('syck_load')) { $content = file_get_contents($target); $yaml = syck_load($content); } else { include_once 'BEAR/vendors/spyc-0.2.5/spyc.php'; $yaml = Spyc::YAMLLoad($target); } $cache->set($key, $yaml); return $yaml; case 'csv': $conf = File_CSV::discoverFormat($target); $csv = array(); while ($fields = File_CSV::read($target, $conf)) { array_push($csv, $fields); } $result = $cache->set($key, $csv); return $csv; case 'ini': $parse = 'inicommented'; break; case 'xml': $unserializer = new XML_Unserializer(); $unserializer->setOption('parseAttributes', true); $xml = file_get_contents($target); $unserializer->unserialize($xml); $result = $unserializer->getUnserializedData(); return $result; break; case 'php': $parse = 'PHPConstants'; break; default: return file_get_contents($target, FILE_TEXT); break; } $config = new Config(); $root =& $config->parseConfig($target, $parse); if (PEAR::isError($root)) { $msg = '設定を読み込む際のエラー: '; $msg .= $root->getMessage(); $info = array('parse' => $parse, 'input' => $target); throw new BEAR_Exception($msg, compact('info')); return false; } else { $result = $root->toArray(); return $result['root']; } } }
$test_obj = syck_load($doc); } $syck_stop = microtime(); $test_str = serialize($test_obj); $unser_start = microtime(); foreach (range(0, $iter) as $i) { $test_obj = unserialize($test_str); } $unser_stop = microtime(); $doc2 = ""; foreach (range(0, $iter) as $i) { $doc2 .= $doc . "\n"; } echo "DOC #2 = 1 x " . strlen($doc2) . "\n"; $syck2_start = microtime(); $test_obj = syck_load($doc2); $syck2_stop = microtime(); $test_str = serialize($test_obj); $unser2_start = microtime(); $test_obj = unserialize($test_str); $unser2_stop = microtime(); function elapsed($start, $stop) { $start_mt = explode(" ", $start); $stop_mt = explode(" ", $stop); $start_total = doubleval($start_mt[0]) + $start_mt[1]; $stop_total = doubleval($stop_mt[0]) + $stop_mt[1]; return sprintf("%0.6f", $stop_total - $start_total); } echo "syck: " . elapsed($syck_start, $syck_stop) . " " . elapsed($syck2_start, $syck2_stop) . "\n"; echo "php: " . elapsed($unser_start, $unser_stop) . " " . elapsed($unser2_start, $unser2_stop) . "\n";
/** * parse yaml string, using syck_load if available, Spyc otherwise * @param string $YAML yaml string. no tabs!! * @return array */ public function parse($YAML) { return $this->useSyck ? syck_load($YAML) : Spyc::YAMLLoad($YAML); }
/** * Read the complete config file *.yaml. * * @param string The yaml file. * * @return array PHP array of the yaml file. */ public static function read($file) { if (is_file($file) === false or is_readable($file) === false) { throw new \Koch\Exception\Exception('YAML File ' . $file . ' not existing or not readable.'); } if (extension_loaded('yaml')) { return yaml_parse_file($file); } elseif (extension_loaded('syck')) { $yaml = file_get_contents($file); return syck_load($yaml); } elseif (class_exists('Spyc')) { $spyc = new Spyc(); $yaml = file_get_contents($file); return $spyc->load($yaml); } throw new \Koch\Exception\Exception('No YAML Parser available. Get Spyc or Syck!'); }
private static function loadConfigFile($configfile) { if (self::isCached($configfile)) { return self::loadCached($configfile); } else { if (function_exists("syck_load")) { return syck_load(file_get_contents($configfile)); } else { require_once KX_ROOT . "/application/lib/spyc/spyc.php"; return spyc_load_file($configfile); } } }
/** * This class mirrors Zend_Config_Ini with a few exceptions. Notably, * there is no need to parse dots in property names, and a bug has been * corrected where in values being set as properties on the object cause * an error when access is then attempted (since the __get function is * overwritten in the parent object), the fix for this being to store the * passed in options locally. * * Loads the section $section from the config file $filename for * access facilitated by nested object properties. * * If the section name contains a < then the section name to the right * is loaded and included into the properties. Note that the keys in * this $section will override any keys of the same * name in the sections that have been included via <. * * If the $section is null, then all sections in the yaml file are loaded. * * example yaml file: * production: * debug: false * db: * adapter: PDO_MYSQL * params: * host: someserver * username: wiz_user * password: "******" * dbname: system_wiz * nonesense: value * * staging < production: * debug: true * db: * params: * host: localhost * username: wiz * password: "******" * dbname: wiz * * after calling $data = new ZExt_Config_Yaml($file, 'staging'); then * $data->debug === true * $data->db->params->host === "localhost" * $data->db->params->nonesense === "value" * * The $options parameter may be provided as either a boolean or an array. * If provided as a boolean, this sets the $allowModifications option of * Zend_Config. If provided as an array, there are two configuration * directives that may be set. For example: * * $options = array( * 'allowModifications' => false, * 'skipExtends' => false * ); * * @param string $filename * @param string|null $section * @param boolean|array $options * @throws Zend_Config_Exception * @return void */ public function __construct($filename, $section = null, $options = false) { // If filename is empy, we cannot proceed. if (empty($filename)) { /** * @see Zend_Config_Exception */ require_once 'Zend/Config/Exception.php'; throw new Zend_Config_Exception('Filename is not set'); } // if syck has not been loaded, we cannot proceeed. if (!function_exists('syck_load')) { require_once 'Zend/Config/Exception.php'; throw new Zend_Config_Exception('Syck extension is not loaded'); } // check to see what options have been passed and store them $allowModifications = false; $this->_options = array(); if (is_bool($options)) { // boolean passed in for optins, so assume this is meant as the // allowModifications settings $allowModifications = $options; } elseif (is_array($options)) { // if options is an array, then collect several settings if (isset($options['allowModifications'])) { $allowModifications = (bool) $options['allowModifications']; } if (isset($options['skipExtends'])) { $this->_options['skipExtends'] = (bool) $options['skipExtends']; } } // If the yaml file cannot be read without errors, then we cannot proceed. // use error handler from the parent config object //set_error_handler(array($this, '_loadFileErrorHandler')); // Warnings and errors are suppressed $ymlArray = syck_load(file_get_contents($filename)); //restore_error_handler(); // Check if there was a error while loading file if ($this->_loadFileErrorStr !== null) { /** * @see Zend_Config_Exception */ require_once 'Zend/Config/Exception.php'; throw new Zend_Config_Exception($this->_loadFileErrorStr); } // load and process the section requested by the "Section" variable (or return // all sections if no section specified) $preProcessedArray = array(); foreach ($ymlArray as $key => $data) { $bits = explode('<', $key); $thisSection = trim($bits[0]); switch (count($bits)) { // no parent section specified, so make no modification case 1: $preProcessedArray[$thisSection] = $data; break; // store the name of the parent section in a special array key AT THE TOP // of the array. // store the name of the parent section in a special array key AT THE TOP // of the array. case 2: $extendedSection = trim($bits[1]); $preProcessedArray[$thisSection] = array_merge(array(';extends' => $extendedSection), $data); break; default: // this cannot be! /** * @see Zend_Config_Exception */ require_once 'Zend/Config/Exception.php'; throw new Zend_Config_Exception('Section "' . $thisSection . '" may not extend multiple sections in $filename'); } } if (null === $section) { // if no section specified, then process and return all sections $dataArray = array(); foreach ($preProcessedArray as $sectionName => $sectionData) { if (!is_array($sectionData)) { $dataArray = array_merge_recursive($dataArray, array($sectionName => $sectionData)); } else { $dataArray[$sectionName] = $this->_processExtends($preProcessedArray, $sectionName); } } parent::__construct($dataArray, $allowModifications); } elseif (is_array($section)) { // if multiple sections specified, then return them $dataArray = array(); foreach ($section as $sectionName) { if (!isset($preProcessedArray[$sectionName])) { /** * @see Zend_Config_Exception */ require_once 'Zend/Config/Exception.php'; throw new Zend_Config_Exception("Section '{$sectionName}' cannot be found in {$filename}"); } $processedArray = $this->_processExtends($preProcessedArray, $sectionName); $dataArray = $this->array_merge_recursive_distinct($processedArray, $dataArray); } parent::__construct($dataArray, $allowModifications); } else { if (!isset($preProcessedArray[$section])) { /** * @see Zend_Config_Exception */ require_once 'Zend/Config/Exception.php'; throw new Zend_Config_Exception("Section '{$section}' cannot be found in {$filename}"); } parent::__construct($this->_processExtends($preProcessedArray, $section), $allowModifications); } $this->_loadedSection = $section; }
private function unyaml($in_string) { if ($this->auto_unyaml) { return syck_load($in_string); } return $in_string; }
/** * Load a component manifest file * * @param string $manifest_file Path of the manifest file */ private function load_manifest($manifest_file) { $manifest_yaml = file_get_contents($manifest_file); // TODO: Implement using http://spyc.sourceforge.net/ if syck is not available $manifest = syck_load($manifest_yaml); if (!isset($this->manifests[$manifest['component']])) { $this->manifests[$manifest['component']] = $manifest; } }
public function loadFile($file) { Debug::checkArgs(0, 1, 'string', $file, 1, 'nonempty', $file); if (!is_file($file) || !is_readable($file)) { throw new FtpException("{$file} is not readable or doesn’t exists."); } try { return syck_load(file_get_contents($file)); } catch (\SyckException $e) { throw new ParserException($e->getMessage()); } }