This class can be used to read a YAML file and convert its contents
into a PHP array. It currently supports a very limited subsection of
the YAML spec.
Usage:
$parser = new Spyc;
$array = $parser->load($file);
/** * SysMisNeural::CargarArchivoYAMLAplicacion($Ruta); * * Metodo para cargar los archivos YAML que se encuentran dentro de la carpeta Aplicacion * @param $Ruta: se utilliza la el nombre de la caperta / archivo * Ejemplo: SysMisNeural::CargarArchivoYAMLAplicacion('Configuracion/Archivo.yaml'); * **/ public static function CargarArchivoYAMLAplicacion($Ruta) { //Validacion de Activacion de Cache if (__SysNeuralCoreCache__ == 'HABILITADO') { $RutaArray = explode('/', $Ruta); $AplicacionArray = explode('.', $RutaArray[1]); $Llave = md5($AplicacionArray[0]); $Cache = new NeuralCacheSimple('NeuralNFZyosSetUp', $Llave); $Cache->DefinirTiempoExpiracion(__SysNeuralCoreCacheExpiracion__); if ($Cache->ExistenciaCache(base64_encode($Llave))) { return $Cache->ObtenerCache(base64_encode($Llave)); } else { //Leemos el archivo de configuracion de accesos y lo convertimos en un array $YML = new Spyc(); $Array = $YML->YAMLLoad(__SysNeuralFileRootAplicacion__ . $Ruta); $Cache->GuardarCache($Llave, $Array); return $Array; } } else { //Leemos el archivo de configuracion de accesos y lo convertimos en un array $YML = new Spyc(); $Array = $YML->YAMLLoad(__SysNeuralFileRootAplicacion__ . $Ruta); return $Array; } }
/** * Mostly rewritten from parent, but allows circular dependencies - goes through the relation loop only after * the dictionary is fully populated. */ public function saveIntoDatabase(DataModel $model) { // Custom plumbing: this has to be executed only once per fixture. $testDataTag = basename($this->fixtureFile); $this->latestVersion = DB::query("SELECT MAX(\"Version\") FROM \"TestDataTag\" WHERE \"FixtureFile\"='{$testDataTag}'")->value(); // We have to disable validation while we import the fixtures, as the order in // which they are imported doesnt guarantee valid relations until after the // import is complete. $validationenabled = DataObject::get_validation_enabled(); DataObject::set_validation_enabled(false); $parser = new Spyc(); $fixtureContent = $parser->loadFile($this->fixtureFile); $this->fixtureDictionary = array(); foreach ($fixtureContent as $dataClass => $items) { if (ClassInfo::exists($dataClass)) { $this->writeDataObject($model, $dataClass, $items); } else { $this->writeSQL($dataClass, $items); } } // Dictionary is now fully built, inject the relations. foreach ($fixtureContent as $dataClass => $items) { if (ClassInfo::exists($dataClass)) { $this->writeRelations($dataClass, $items); } } DataObject::set_validation_enabled($validationenabled); }
public function requireDefaultRecords() { parent::requireDefaultRecords(); // get schemas that need creating $schemas = $this->config()->get('default_schemas'); require_once 'spyc/spyc.php'; foreach ($schemas as $file) { if (file_exists(Director::baseFolder() . '/' . $file)) { $parser = new Spyc(); $factory = new FixtureFactory(); $fixtureContent = $parser->loadFile(Director::baseFolder() . '/' . $file); if (isset($fixtureContent['MetadataSchema'])) { $toBuild = array(); // check if it exists or not, if so don't re-create it foreach ($fixtureContent['MetadataSchema'] as $id => $desc) { $name = isset($desc['Name']) ? $desc['Name'] : null; if (!$name) { throw new Exception("Cannot create metadata schema without a name"); } $existing = MetadataSchema::get()->filter('Name', $name)->first(); if ($existing) { $factory->setId('MetadataSchema', $id, $existing->ID); } else { $factory->createObject('MetadataSchema', $id, $desc); DB::alteration_message('Metadata schema ' . $id . ' created', 'created'); } } // don't need this now unset($fixtureContent['MetadataSchema']); // go through and unset any existing fields $toBuild = array(); foreach ($fixtureContent as $class => $items) { foreach ($items as $identifier => $data) { $nameField = isset($data['Name']) ? 'Name' : (isset($data['Key']) ? 'Key' : ''); if (!strlen($nameField)) { throw new Exception("Metadata fields must have a Name or Key field defined"); } if (!isset($data['Title'])) { $data['Title'] = $data[$nameField]; } $existing = $class::get()->filter($nameField, $data[$nameField])->first(); if ($existing) { $factory->setId($class, $identifier, $existing->ID); } else { $factory->createObject($class, $identifier, $data); DB::alteration_message('Metadata field ' . $data[$nameField] . ' created', 'created'); } } } } } } }
public function __construct() { $base = Site::model('Environment')->database_atheist_tables_base; $page = Site::model('Environment')->database_atheist_tables_page; $page['fields'] = array_merge($base['fields'], $page['fields']); $dbPage = 'page'; $dbPage = $this->describe('profiles_fields'); echo '<pre>'; print_r($dbPage); echo $this->create_table($dbPage); echo '====='; $spyc = new Spyc(); echo $spyc->YAMLDump($dbPage, true); die; }
/** * Load config file * * Get array from config file and save it to variable * * @static * @access public * @param string $sConfigPath * @param string $sFormat * @return bool * @throws Exception * @since 1.0.0-alpha * @version 1.0.0-alpha */ private static function load($sConfigPath, $sFormat = 'php') { $oConfigData = static::findConfigFile($sConfigPath, $sFormat); // load config data if ($oConfigData !== FALSE) { switch ($sFormat) { # PHP case 'php': $aConfig = (include $oConfigData->getPath()); break; # YAML # YAML case "yml": $aConfig = \Spyc::YAMLLoad($oConfigData->getPath()); break; } } // assign data to storage if (isset($aConfig)) { Helper\Arrays::createMultiKeys(static::$aConfigs, $sConfigPath, $aConfig); unset($aConfig); Log::insert('Config ' . $sConfigPath . ' (' . $sFormat . ') loaded'); return TRUE; } // if there is no data to assign (because the config file does not exists), create ERROR message and return FALSE (or throw exception) $sMsg = 'Unable to load ' . $sConfigPath . ' config file with "' . $sFormat . '" format.'; Log::insert($sMsg, Log::ERROR); if (Core::getAppMode() === Core::MODE_DEVELOPMENT) { throw new Exception($sMsg); } return FALSE; }
function __construct($database_type, $db_file) { $Data = Spyc::YAMLLoad(BMARK . 'db.yaml'); if ($database_type == 'mysql') { $this->database_type = $database_type; $this->user = $Data['mysqld']['user']; $this->pass = $Data['mysqld']['pass']; $this->host = $Data['mysqld']['host']; $this->port = $Data['mysqld']['port']; $this->database = $Data['mysqld']['dbname']; $this->connection = ''; } if ($database_type == 'drizzle') { $this->database_type = $database_type; $this->user = $Data['drizzled']['user']; $this->pass = $Data['drizzled']['pass']; $this->host = $Data['drizzled']['host']; $this->port = $Data['drizzled']['port']; $this->database = $Data['drizzled']['dbname']; $this->connection = ''; } if (strlen($this->port) <= 0) { if (strcmp($this->database_type, "mysql") == 0) { $this->port = '3306'; } if (strcmp($this->database_type, "drizzle") == 0) { $this->port = '4427'; } } }
function i18n($prompt, $lang) { $fileName = 'locales/' . $lang . '.yml'; // Retrieve complete list of translations as a single string $yaml = Spyc::YAMLLoad($fileName); $contents = $yaml[$lang]; $promptArray = explode(".", $prompt); $result = $contents; for ($i = 0; $i < count($promptArray); $i++) { if (is_array($result)) { $result = $result[$promptArray[$i]]; } else { if (isset($result)) { return $result; } else { return $prompt; } } } if (isset($result)) { return $result; } else { return $prompt; } }
function compile_apps_yaml() { # Load Spyc and serialize apps.yaml. include 'spyc.lib.php'; $data = Spyc::YAMLLoad('apps.yaml'); return serialize($data); }
function remoteFunction(&$controller, $options) { $javascript_options = JavascriptHelper::optionsForAjax($options); $update = ''; if (isset($options['update']) && is_string($options['update'])) { require_once 'vendor/spyc.php'; $val = @Spyc::YAMLLoad($options['update']); if (!empty($val)) { // it's a YAML array, so load it into options['update'] $options['update'] = $val; } } if (isset($options['update']) && is_array($options['update'])) { $update = array(); if (isset($options['update']['success'])) { $update[] = "success:'{$options['update']['success']}'"; } if (isset($options['update']['failure'])) { $update[] = "failure:'{$options['update']['failure']}'"; } $update = implode(',', $update); } else { if (isset($options['update'])) { $update = $options['update']; } } $function = isset($options['update']) ? "new Ajax.Updater('{$update}', " : 'new Ajax.Request('; $function .= "'" . UrlHelper::urlFor($controller, $options['url']) . "'"; $function .= ', ' . $javascript_options . ')'; $function = (isset($options['before']) ? "{$options['before']}; " : '') . $function; $function .= isset($options['after']) ? "; {$options['after']};" : ''; $function = isset($options['condition']) ? 'if(' . $options['condition'] . '){' . $function . '}' : $function; $function = isset($options['confirm']) ? 'if(confirm' . $options['condition'] . '){' . $function . '}' : $function; return $function; }
static function read($filename) { if (!file_exists($filename)) { trigger_error("YAML error: file '{$filename}' does not exist"); } return Spyc::YAMLLoad($filename); }
public function read() { if (file_exists($this->file)) { $configuration = file_get_contents($this->file); $this->registry = \Spyc::YAMLLoadString($configuration); } }
function __construct() { # Include the SPYC library for yaml parsing: require_once '3rd-party/spyc/spyc.php'; # Loads an array with the config: $this->aConfig = Spyc::YAMLLoad('config.yml'); }
function output() { global $config, $pages, $ums, $blog, $user, $coms, $editor; //First Requirements (Components) $error = ""; foreach ($pages['pacedit']['reqs'] as $req) { if (!in_array($req, $config['coms'])) { $error .= "Component: " . $req . " is missing<br>"; } } if ($error != "") { $out = $error; } else { if (!in_array($user['id'], $coms['pacman']['admins'])) { $out = "You are not a package manager"; } else { $out = "<h1>Package Manager - Edit</h1>"; if (!$_GET['pac']) { $out .= 'Please Go back and try again'; } else { $com = $_GET['pac']; $content = Spyc::YAMLDump($coms[$com]); $out .= '<form action="?var=pacsub" method="POST"> <input type="hidden" value="' . $com . '" name="com" /> <textarea name="yaml" id="yaml" cols="70" rows="15">' . str_replace("- --\n", '', $content) . '</textarea><input type="submit" value="Save" /></form>'; } } } return $out; }
/** * The method that runs the task * * @return void */ public function main() { $this->map = Spyc::YAMLLoad($this->mapFile); if (!isset($this->map['symlinks'])) { throw new Exception("Invalid symlinks map file", 1); } }
/** * Gets all labels for a defined type. * * @param string $type Name of the array group. * @param string $locale Locale code. * * @access public * @static * @uses Config() * @uses \Spyc * * @return array */ public static function getAll($type, $locale = '') { if (!$locale) { $locale = Core\Registry()->get('locale'); } return \Spyc::YAMLLoad(Core\Config()->paths('labels') . $locale . DIRECTORY_SEPARATOR . $type . '.yaml'); }
protected function _read() { $settingsFile = CONFIGS . DS . 'settings.php'; include $settingsFile; if (!isset($settings)) { trigger_error(sprintf(__('Missing settings file[%s] or $settings could not be found', true), $settingsFile)); return array(); } $records = $this->find('all'); foreach ($records as $record) { switch ($record['Setting']['name']) { case 'per_page_options': $settings[$record['Setting']['name']] = explode(',', $record['Setting']['value']); break; case 'issue_list_default_columns': $settings[$record['Setting']['name']] = Spyc::YAMLLoad($record['Setting']['value']); // array_slice(array_map('trim',explode('- ',$v['Setting']['value'])),1); break; default: $settings[$record['Setting']['name']] = $record['Setting']['value']; } } Cache::write(self::$__cacheKey, $settings); return $settings; }
/** * edit * * @return void */ public function edit() { //リクエストセット if ($this->request->is('post')) { //登録処理 if (!$this->request->data['SiteSetting']['only_session']) { unset($this->request->data['SiteSetting']['only_session']); $this->Session->write('debug', null); //application.ymlに書き込み $conf = Spyc::YAMLLoad(APP . 'Config' . DS . 'application.yml'); $conf['debug'] = (int) $this->request->data['SiteSetting']['debug']['0']['value']; $file = new File(APP . 'Config' . DS . $this->appYmlPrefix . 'application.yml', true); $file->write(Spyc::YAMLDump($conf)); $this->SiteManager->saveData(); } else { $this->SiteSetting->validateDeveloper($this->request->data); if (!$this->SiteSetting->validationErrors) { $this->Session->write('debug', (int) $this->request->data['SiteSetting']['debug']['0']['value']); $this->NetCommons->setFlashNotification(__d('net_commons', 'Successfully saved.'), array('class' => 'success')); $this->redirect($this->referer()); } else { $this->NetCommons->handleValidationError($this->SiteSetting->validationErrors); } } } else { $this->request->data['SiteSetting'] = $this->SiteSetting->getSiteSettingForEdit(array('SiteSetting.key' => array('debug'))); $onlySession = $this->Session->read('debug'); $this->request->data['SiteSetting']['only_session'] = isset($onlySession); if ($this->request->data['SiteSetting']['only_session']) { $this->request->data['SiteSetting']['debug']['0']['value'] = $onlySession; } } }
function beforeSave($options = array()) { if ($this->data[$this->name]['type'] == 'IssueCustomField' && !empty($this->data['CustomField']['id'])) { $assoc_trackers = Set::extract('{n}.CustomFieldsTracker.tracker_id', $this->CustomFieldsTracker->find('all', array('conditions' => array('custom_field_id' => $this->data['CustomField']['id'])))); $tracker_ids = empty($this->data[$this->name]['tracker_id']) ? array() : $this->data[$this->name]['tracker_id']; $this->__add_trackers = array_diff($tracker_ids, $assoc_trackers); $this->__del_trackers = array_diff($assoc_trackers, $tracker_ids); } unset($this->data[$this->name]['tracker_id']); App::Import('vendor', 'spyc'); if (!empty($this->data[$this->name]['possible_values']) && $this->data[$this->name]['field_format'] == 'list') { if (empty($this->data[$this->name]['possible_values'][count($this->data[$this->name]['possible_values']) - 1])) { unset($this->data[$this->name]['possible_values'][count($this->data[$this->name]['possible_values']) - 1]); } $this->data[$this->name]['possible_values'] = Spyc::YAMLDump($this->data[$this->name]['possible_values'], true); } else { $this->data[$this->name]['possible_values'] = '--- []'; } if (empty($this->data[$this->name]['min_length'])) { $this->data[$this->name]['min_length'] = 0; } if (empty($this->data[$this->name]['max_length'])) { $this->data[$this->name]['max_length'] = 0; } return true; }
/** * versionCheck - Get the most current version of nterchange and cache the result. * * @return array Information about the newest version of nterchange. **/ function versionCheck() { require_once 'Cache/Lite.php'; $options = array('cacheDir' => CACHE_DIR . '/ntercache/', 'lifeTime' => $this->check_version_interval); $cache = new Cache_Lite($options); $yaml = $cache->get($this->cache_name, $this->cache_group); if (empty($yaml)) { include_once 'HTTP/Request.php'; $req = new HTTP_Request($this->check_version_url); if (!PEAR::isError($req->sendRequest())) { $yaml = $req->getResponseBody(); $cached = $cache->save($yaml, $this->cache_name, $this->cache_group); if ($cached == true) { NDebug::debug('Version check - data is from the web and is now cached.', N_DEBUGTYPE_INFO); } else { NDebug::debug('Version check - data is from the web and is NOT cached.', N_DEBUGTYPE_INFO); } } } else { NDebug::debug('Version check - data is from the cache.', N_DEBUGTYPE_INFO); } require_once 'vendor/spyc.php'; $newest_version_info = @Spyc::YAMLLoad($yaml); return $newest_version_info; }
/** * 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; } }
public function beforeSave($options = array()) { if (isset($this->data[$this->name]['type']) && $this->data[$this->name]['type'] == 'IssueCustomField' && !empty($this->data['CustomField']['id'])) { $this->bindModel(array('hasMany' => array('CustomFieldsTracker')), false); $assoc_trackers = Set::extract('{n}.CustomFieldsTracker.tracker_id', $this->CustomFieldsTracker->find('all', array('conditions' => array('custom_field_id' => $this->data['CustomField']['id'])))); $tracker_ids = empty($this->data[$this->name]['tracker_id']) ? array() : $this->data[$this->name]['tracker_id']; $this->__add_trackers = array_diff($tracker_ids, $assoc_trackers ? $assoc_trackers : array()); $this->__del_trackers = array_diff($assoc_trackers ? $assoc_trackers : array(), $tracker_ids); } unset($this->data[$this->name]['tracker_id']); App::Import('vendor', 'georgious-cakephp-yaml-migrations-and-fixtures/spyc/spyc'); if (!empty($this->data[$this->name]['possible_values']) && $this->data[$this->name]['field_format'] == 'list') { if (empty($this->data[$this->name]['possible_values'][count($this->data[$this->name]['possible_values']) - 1])) { unset($this->data[$this->name]['possible_values'][count($this->data[$this->name]['possible_values']) - 1]); } $this->data[$this->name]['possible_values'] = Spyc::YAMLDump($this->data[$this->name]['possible_values'], true); } else { $this->data[$this->name]['possible_values'] = '--- []'; } if (empty($this->data[$this->name]['min_length'])) { $this->data[$this->name]['min_length'] = 0; } if (empty($this->data[$this->name]['max_length'])) { $this->data[$this->name]['max_length'] = 0; } return true; }
function find($conditions = null, $fields = array(), $order = null, $recursive = null) { if ($conditions != 'range') { return parent::find($conditions, $fields, $order, $recursive); } $file = Set::extract($fields, 'file'); if (empty($file)) { $file = ROOT . DS . APP_DIR . DS . 'plugins/mobileip/config/mobile_ips.yml'; } if (!file_exists($file)) { return false; } $cacheDir = $this->getCacheDir(); $folder = new Folder($cacheDir); $folder->create($cacheDir, 0777); $cacheFile = $this->getCacheFile(); if (file_exists($cacheFile) && $this->_getLastModified($file) <= filemtime($cacheFile)) { return include $cacheFile; } $mobile_ips =& Spyc::YAMLLoad($file); if (!is_array($mobile_ips)) { return false; } $data = $this->_get_ranges($mobile_ips); $file = new File($cacheFile, true); $file->write($data); $file->close(); return include $cacheFile; }
function save_data($obj) { global $wpdb; require_once "../../../../../wp-load.php"; require_once ABSPATH . 'wp-content/plugins/UiGEN-Core/class/Spyc.php'; require_once ABSPATH . 'wp-content/plugins/UiGEN-Core/core-files/defines-const.php'; if (!current_user_can('manage_options')) { echo 'ADMIN BABY !!!'; die; } /* echo '<h2>Save</h2>'; echo '<pre>'; var_dump($obj['data']); echo '</pre>';*/ $prop_path = GLOBALDATA_PATH . 'template-hierarchy'; $posttypes_array = Spyc::YAMLLoad($prop_path . '/arguments/' . $obj['ui_page_name'] . '-slots-properties.yaml'); //var_dump($posttypes_array[$_POST['slotname']]); //echo '<br>---<br>'; //var_dump($_POST['data']); $execute_array = array_merge($posttypes_array[$obj['slotname']], $obj['data']); //echo '<br>---<br>'; //var_dump($execute_array); $posttypes_array[$obj['slotname']] = $execute_array; //var_dump($posttypes_array); file_put_contents($prop_path . '/arguments/' . $obj['ui_page_name'] . '-slots-properties.yaml', Spyc::YAMLDump($posttypes_array)); }
function doTheHooks($name, $branch, $repo, $transport) { $result = null; chdir($repo['dir']); ob_start(); echo "~> git pull origin " . $branch . " 3>&1\n"; system(__ENV_PATH__ . ' ' . __GIT_PATH__ . ' pull origin ' . $branch . ' 2>&1'); echo "\n"; if (file_exists($repo['dir'] . '/' . __HOOKS_FILE__)) { $yaml = Spyc::YAMLLoad($repo['dir'] . '/' . __HOOKS_FILE__); $cmds = array(); if (is_array($yaml[$repo['branch']])) { $cmds = $yaml[$repo['branch']]; } elseif (is_array($yaml['all'])) { $cmds = $yaml['all']; } foreach ($cmds as $cmd) { echo "~> " . $cmd . "\n"; system(__ENV_PATH__ . ' ' . $cmd); echo "\n"; } $result = ob_get_contents(); if (is_array($yaml['emails'])) { foreach ($yaml['emails'] as $email) { $mailer = Swift_Mailer::newInstance($transport); $message = Swift_Message::newInstance()->setSubject(sprintf(__MAIL_SUBJECT__, $name))->setFrom(array(__MAIL_FROM_ADDRESS__ => __MAIL_FROM__))->setTo(array($email))->setBody($result); $result = $mailer->send($message); } } } ob_end_clean(); }
protected function setUp() { global $SAP_CONFIG; $this->config = Spyc::YAMLLoad($SAP_CONFIG); echo "sapnwrfc version: " . sapnwrfc_version() . "\n"; echo "nw rfc sdk version: " . sapnwrfc_rfcversion() . "\n"; }
function imageTag($src, $alt = '', $options = array()) { if (is_file($_SERVER['DOCUMENT_ROOT'] . $src)) { $file = $_SERVER['DOCUMENT_ROOT'] . $src; } else { if (is_file(BASE_DIR . $src)) { $file = BASE_DIR . $src; } else { return ''; } } if (is_string($options)) { require_once 'vendor/spyc.php'; $val = @Spyc::YAMLLoad($options); if (!empty($val)) { // it's a YAML array, so load it into options['update'] $options = $val; } } $code = ''; if (is_array($options)) { $options['style'] = 'border:0;' . (isset($options['style']) ? $options['style'] : ''); foreach ($options as $key => $val) { $code .= " {$key}=\"{$val}\""; } } else { $code = ' style="border:0;" ' . $options; } $size = getImageSize($file); $src = (defined('EXTERNAL_CACHE') && constant('EXTERNAL_CACHE') ? EXTERNAL_CACHE : '') . $src; return '<img src="' . $src . '" alt="' . $alt . '" width="' . $size[0] . '" height="' . $size[1] . '"' . $code . ' />'; }
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; }
/** * Convert YAML to Array using Spyc converter * * @param string $data Data to convert * * @return array */ public final function fromYaml($data) { if (!is_string($data)) { throw new Exception("Invalid data for YAML deserialization"); } return \Spyc::YAMLLoadString($data); }
function subTest($p, $s) { // we really need do this right and to set up a yaml module that abstracts away the underlying yaml engine include_once zoop_dir . '/spyc/spyc.php'; $array = Spyc::YAMLLoad($_SERVER['HOME'] . '/.zoop/install.yaml'); print_r($array); }
public static function load_schema_from_yaml($table) { $schema = Spyc::YAMLLoad('db/' . $table . '.yaml'); $sqlite = new sqlite(); $pragma = $sqlite->query("PRAGMA table_info({$table})"); foreach ($pragma as $k => $v) { $pragma_fields[] = $v->name; } // If pragma returns info, table exists, enter ALTER mode if (count($pragma) > 0) { echo "Table {$table} exists.\r\n"; foreach ($schema as $k => $v) { if (in_array($v['name'], $pragma_fields)) { echo 'Column ' . $v['name'] . " exists\r\n"; } else { echo $v['name'] . " does not exist\r\n"; if ($v['notnul'] == 1) { $notnull = 'NOT NULL'; } else { $notnull = 'NULL'; } if ($v['default'] != '') { $default = 'DEFAULT ' . $v['default']; } $sql = "ALTER TABLE {$table} ADD COLUMN " . $v['name'] . " " . $v['type'] . " {$notnull} " . $v['default']; $sqlite->exec($sql); echo $v['name'] . " column added\r\n"; } } // pragma returns zero, enter CREATE TABLE mode } else { $sql = "create table {$table} ("; foreach ($schema as $k => $v) { if ($v['notnul'] == 1) { $notnull = 'NOT NULL'; } else { $notnull = 'NULL'; } if ($v['default'] != '') { $default = 'DEFAULT ' . $v['default']; } if ($v['isprimarykey'] == 0) { $sql .= $v['name'] . " " . $v['type'] . " {$notnull} {$default},"; } else { $sql .= $v['name'] . " " . $v['type'] . " PRIMARY KEY,"; } } // Trim trailing comma and close statement $sql = rtrim($sql, ","); $sql .= ")"; echo "{$sql} \r\n"; $sqlite->exec($sql); echo "Table {$table} created.\r\n"; } // SQL create table syntax cheatsheet // Primary key: FIELDNAME INTEGER PRIMARY KEY // Fields: FIELDNAME TYPE(LENGTH) NULL DEFAULT '' // Timestamp: timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL }