function __construct($alias, $architecture)
 {
     $this->alias = $alias;
     $this->architecture = $architecture;
     $archiConfig = $architecture->getConfig();
     $this->config = sfToolkit::arrayDeepMerge($archiConfig['hosts']['all'], $archiConfig['hosts'][$alias]);
 }
 public function executeTableManager()
 {
   $class = $this->getRequestParameter('class');
   $generator_configuration = array(
     'model_class' =>  $class,
     'theme'       => 'sfControlPanel',
     'moduleName'  => $class.'ControlPanel',
     'list' => array(
         'title' => $class.' list',
     ),
     'edit' => array(
         'title' => 'edit '.$class,
     ),
   );
   if(file_exists(SF_ROOT_DIR.'/config/sfControlPanel_generator.yml'))
   {
     $custom_configuration = sfYaml::load(SF_ROOT_DIR.'/config/sfControlPanel_generator.yml');
     if(isset($custom_configuration[$class]))
     {
       $generator_configuration = sfToolkit::arrayDeepMerge($generator_configuration, $custom_configuration[$class]);
     }
   }
   $generatorManager = new sfGeneratorManager();
   $generatorManager->initialize(); 
   $data = $generatorManager->generate('sfControlPanelGenerator', $generator_configuration);
   $this->redirect('auto'.$class.'ControlPanel/list');
 }
 protected function initialize(array $options)
 {
     $this->options = sfToolkit::arrayDeepMerge($this->options, $options);
     if (!$this->page instanceof DmPage) {
         throw new dmException(sprintf('%s require a source instance of DmPage, %s given', get_class($this), get_class($this->page)));
     }
 }
 /**
  * Executes this configuration handler.
  *
  * @param array An array of absolute filesystem path to a configuration file
  *
  * @return string Data to be written to a cache file
  *
  * @throws <b>sfConfigurationException</b> If a requested configuration file does not exist or is not readable
  * @throws <b>sfParseException</b> If a requested configuration file is improperly formatted
  * @throws <b>sfInitializationException</b> If a cache.yml key check fails
  */
 public function execute($configFiles)
 {
     // set our required categories list and initialize our handler
     $categories = array('required_categories' => array());
     $this->initialize($categories);
     // parse the yaml
     $myConfig = $this->parseYamls($configFiles);
     $myConfig['all'] = sfToolkit::arrayDeepMerge(isset($myConfig['default']) && is_array($myConfig['default']) ? $myConfig['default'] : array(), isset($myConfig['all']) && is_array($myConfig['all']) ? $myConfig['all'] : array());
     unset($myConfig['default']);
     $this->yamlConfig = $myConfig;
     // iterate through all action names
     $data = array();
     $first = true;
     foreach ($this->yamlConfig as $actionName => $values) {
         if ($actionName == 'all') {
             continue;
         }
         $data[] = $this->addCache($actionName);
         $first = false;
     }
     // general cache configuration
     $data[] = $this->addCache('DEFAULT');
     // compile data
     $retval = sprintf("<?php\n" . "// auto-generated by sfCacheConfigHandler\n" . "// date: %s\n%s\n", date('Y/m/d H:i:s'), implode('', $data));
     return $retval;
 }
 /**
  * Parses an array of YAMLs files and merges them in one configuration array.
  *
  * @param array An array of configuration file paths
  *
  * @param array A merged configuration array
  */
 protected function parseYamls($configFiles)
 {
     $config = array();
     foreach ($configFiles as $configFile) {
         $config = sfToolkit::arrayDeepMerge($config, $this->parseYaml($configFile));
     }
     return $config;
 }
Example #6
0
 public function __construct($source, $ruleName = 'default')
 {
     $this->setSource(tsUploadSource::create($source));
     $defaultRule = array('params' => array('image_resize' => true), 'sizes' => array());
     $uploadConfig = sfYaml::load(sfConfig::get('sf_app_config_dir') . '/upload.yml');
     $config = sfToolkit::arrayDeepMerge($uploadConfig['all'], (array) @$uploadConfig[sfConfig::get('sf_environment')]);
     $this->_ruleConfig = sfToolkit::arrayDeepMerge((array) @$config['rules']['default'], $config['rules'][$ruleName]);
     $this->_ruleConfig = sfToolkit::arrayDeepMerge($defaultRule, $this->_ruleConfig);
 }
 public function __construct(sfConfigCache $configCache, $architecture)
 {
     $this->configCache = $configCache;
     if (!file_exists($path = sfConfig::get('sf_config_dir') . '/knp_architecture.yml')) {
         throw new Exception($path . ' does not exist');
     }
     $this->configCache->registerConfigHandler('config/knp_architecture.yml', 'sfSimpleYamlConfigHandler');
     $this->config = (include $this->configCache->checkConfig('config/knp_architecture.yml'));
     $this->architecture = $architecture;
     $this->config = sfToolkit::arrayDeepMerge($this->config['all'], $this->config[$architecture]);
 }
 /**
  * Executes this configuration handler.
  *
  * @param array An array of absolute filesystem path to a configuration file
  *
  * @return string Data to be written to a cache file
  *
  * @throws <b>sfConfigurationException</b> If a requested configuration file does not exist or is not readable
  * @throws <b>sfParseException</b> If a requested configuration file is improperly formatted
  * @throws <b>sfInitializationException</b> If a view.yml key check fails
  */
 public function execute($configFiles)
 {
     // parse the yaml
     $myConfig = $this->parseYamls($configFiles);
     $myConfig['all'] = sfToolkit::arrayDeepMerge(isset($myConfig['default']) && is_array($myConfig['default']) ? $myConfig['default'] : array(), isset($myConfig['all']) && is_array($myConfig['all']) ? $myConfig['all'] : array());
     unset($myConfig['default']);
     // change all of the keys to lowercase
     $myConfig = array_change_key_case($myConfig);
     // compile data
     $retval = sprintf("<?php\n" . "// auto-generated by sfSecurityConfigHandler\n" . "// date: %s\n\$this->security = %s;\n", date('Y/m/d H:i:s'), var_export($myConfig, true));
     return $retval;
 }
 /**
  * Executes this configuration handler.
  *
  * @param array An array of absolute filesystem path to a configuration file
  *
  * @return string Data to be written to a cache file
  *
  * @throws sfConfigurationException If a requested configuration file does not exist or is not readable
  * @throws sfParseException If a requested configuration file is improperly formatted
  */
 public function execute($configFiles)
 {
     // parse the yaml
     $myConfig = $this->parseYamls($configFiles);
     $myConfig = sfToolkit::arrayDeepMerge(isset($myConfig['default']) && is_array($myConfig['default']) ? $myConfig['default'] : array(), isset($myConfig['all']) && is_array($myConfig['all']) ? $myConfig['all'] : array(), isset($myConfig[sfConfig::get('sf_environment')]) && is_array($myConfig[sfConfig::get('sf_environment')]) ? $myConfig[sfConfig::get('sf_environment')] : array());
     // init our data and includes arrays
     $data = array();
     $databases = array();
     $includes = array();
     // get a list of database connections
     foreach ($myConfig as $key => $dbConfig) {
         // is this category already registered?
         if (in_array($key, $databases)) {
             // this category is already registered
             $error = sprintf('Configuration file "%s" specifies previously registered category "%s"', $configFiles[0], $key);
             throw new sfParseException($error);
         }
         // add this database
         $databases[] = $key;
         // let's do our fancy work
         if (!isset($dbConfig['class'])) {
             // missing class key
             $error = sprintf('Configuration file "%s" specifies category "%s" with missing class key', $configFiles[0], $key);
             throw new sfParseException($error);
         }
         if (isset($dbConfig['file'])) {
             // we have a file to include
             $file = $this->replaceConstants($dbConfig['file']);
             $file = $this->replacePath($file);
             if (!is_readable($file)) {
                 // database file doesn't exist
                 $error = sprintf('Configuration file "%s" specifies class "%s" with nonexistent or unreadable file "%s"', $configFiles[0], $dbConfig['class'], $file);
                 throw new sfParseException($error);
             }
             // append our data
             $includes[] = sprintf("require_once('%s');", $file);
         }
         // parse parameters
         if (isset($dbConfig['param'])) {
             foreach ($dbConfig['param'] as &$value) {
                 $value = $this->replaceConstants($value);
             }
             $parameters = var_export($dbConfig['param'], true);
         } else {
             $parameters = 'null';
         }
         // append new data
         $data[] = sprintf("\n\$database = new %s();\n" . "\$database->initialize(%s, '%s');\n" . "\$this->databases['%s'] = \$database;", $dbConfig['class'], $parameters, $key, $key);
     }
     // compile data
     $retval = sprintf("<?php\n" . "// auto-generated by sfDatabaseConfigHandler\n" . "// date: %s%s\n%s\n", date('Y/m/d H:i:s'), implode("\n", $includes), implode("\n", $data));
     return $retval;
 }
 protected function getConfigForPath($path)
 {
     if (strncmp($path, sfConfig::get('sf_root_dir'), $len = strlen(sfConfig::get('sf_root_dir'))) == 0) {
         $path = substr($path, $len);
     }
     $config = array();
     foreach ($this->patternConfigs as $pattern => $patternConfig) {
         if (preg_match('/^' . str_replace('/', '\\/', $pattern) . '$/', $path) > 0) {
             $config = sfToolkit::arrayDeepMerge($config, $patternConfig);
         }
     }
     return $config;
 }
 public static function applyInheritance($config)
 {
     $classes = array_keys($config);
     $merged = array();
     foreach ($classes as $class) {
         if (class_exists($class)) {
             $merged[$class] = $config[$class];
             foreach (array_intersect(class_parents($class), $classes) as $parent) {
                 $merged[$class] = sfToolkit::arrayDeepMerge($config[$parent], $merged[$class]);
             }
         }
     }
     return $merged;
 }
 public function getAuthConfigSettings($name = '')
 {
     if (!sfConfig::has('op_auth_' . $this->getAuthModeName())) {
         // default
         $configPath = sfConfig::get('sf_lib_dir') . '/config/config/auth.yml';
         sfContext::getInstance()->getConfigCache()->registerConfigHandler($configPath, 'sfSimpleYamlConfigHandler', array());
         $default = (include sfContext::getInstance()->getConfigCache()->checkConfig($configPath));
         // plugins
         $configPath = sfConfig::get('sf_plugins_dir') . '/opAuth' . $this->getAuthModeName() . 'Plugin/config/auth.yml';
         sfContext::getInstance()->getConfigCache()->registerConfigHandler($configPath, 'sfSimpleYamlConfigHandler', array());
         $plugins = (include sfContext::getInstance()->getConfigCache()->checkConfig($configPath));
         sfConfig::set('op_auth_' . $this->getAuthModeName(), sfToolkit::arrayDeepMerge($default, $plugins));
     }
     $configs = sfConfig::get('op_auth_' . $this->getAuthModeName());
     if (!$name) {
         return $configs;
     } elseif (!empty($configs[$name])) {
         return $configs[$name];
     }
     return null;
 }
 public function execute($configFiles)
 {
     // Parse yaml config files
     $configs = $this->parseYamls($configFiles);
     // Default config: all.attributes
     $default_config = array();
     if (isset($configs['all']['attributes']) && is_array($configs['all']['attributes'])) {
         $default_config = $configs['all']['attributes'];
         unset($configs['all']['attributes']);
     }
     // Environment specific defaults: <env>.attributes
     $env = sfConfig::get('sf_environment');
     if (isset($configs[$env]['attributes']) && is_array($configs[$env]['attributes'])) {
         $default_config = sfToolKit::arrayDeepMerge($default_config, $configs[$env]['attributes']);
         unset($configs[$env]['attributes']);
     }
     // Connection specific configs
     $conn_configs = array();
     foreach ($configs as $env => $env_config) {
         foreach ($env_config as $conn => $conn_config) {
             $conn_configs[$conn] = sfToolkit::arrayDeepMerge($default_config, $conn_config);
         }
     }
     // Prepare default config data
     $data = array();
     foreach ($this->configToAttributes($default_config) as $key => $value) {
         $data[] = sprintf('$default_attributes["%s"] = %s;', $key, $this->attributeToPhp($value));
     }
     $data[] = '';
     // Prepare connection specific data
     foreach ($conn_configs as $conn_name => $conn_config) {
         foreach ($this->configToAttributes($conn_config) as $key => $value) {
             $data[] = sprintf('$attributes["%s"]["%s"] = %s;', $conn_name, $key, $this->attributeToPHP($value));
         }
         $data[] = '';
     }
     // compile data
     $retval = sprintf("<?php\n" . "// auto-generated by sfDoctrineConfigHandler\n" . "// date: %s\n%s\n", date('Y-m-d H:i:s'), implode("\n", $data));
     return $retval;
 }
 /**
  * Executes this configuration handler.
  *
  * @param array An array of absolute filesystem path to a configuration file
  *
  * @return string Data to be written to a cache file
  *
  * @throws <b>sfParseException</b> If a requested configuration file is improperly formatted
  */
 public function execute($configFiles)
 {
     // parse the yaml
     $myConfig = $this->parseYamls($configFiles);
     $myConfig = sfToolkit::arrayDeepMerge(isset($myConfig['default']) && is_array($myConfig['default']) ? $myConfig['default'] : array(), isset($myConfig['all']) && is_array($myConfig['all']) ? $myConfig['all'] : array(), isset($myConfig[sfConfig::get('sf_environment')]) && is_array($myConfig[sfConfig::get('sf_environment')]) ? $myConfig[sfConfig::get('sf_environment')] : array());
     // Set Up Servers
     $defaultServerConfig = array('host' => 'localhost', 'port' => 11211, 'persistent' => true, 'weight' => 1, 'timeout' => 1, 'retry_interval' => 15, 'status' => true);
     if (!isset($myConfig['servers']) || !is_array($myConfig['servers'])) {
         $myConfig['servers'] = array('default' => $defaultServerConfig);
     }
     $myConfig['servers']['default'] = array_merge($defaultServerConfig, isset($myConfig['servers']['default']) ? $myConfig['servers']['default'] : array());
     foreach ($myConfig['servers'] as $serverName => &$server) {
         $server = array_merge($myConfig['servers']['default'], $server);
     }
     // Set Up Buckets
     if (!isset($myConfig['buckets']) || !is_array($myConfig['buckets'])) {
         throw new sfParseException(sprintf('Configuration file "%s" does not specify any cache buckets.', $configFiles[0]));
     }
     $inits = array();
     $tmp = array();
     foreach ($myConfig['buckets'] as $bucketName => &$bucket) {
         if (!isset($bucket['servers'])) {
             $bucket['servers'] = 'default';
         }
         if (!is_array($bucket['servers'])) {
             $bucket['servers'] = array($bucket['servers']);
         }
         foreach ($bucket['servers'] as $serverName => &$server) {
             if (!isset($myConfig['servers'][$server])) {
                 throw new sfParseException(sprintf('Configuration file "%s" requires server configuration \'%s\' for bucket \'%s\', but server configuration does not exist.', $configFiles[0], $server, $bucketName));
             }
             $server = $myConfig['servers'][$server];
         }
         $tmp[$bucketName] = $bucket;
     }
     $inits[] = sprintf("sfConfig::set('%s', %s);", 'memcache_servers', var_export($tmp, true));
     // Compile Return Value
     return sprintf("<?php\n  %s", implode("\n", $inits));
 }
 protected function _buildArrayToWrite()
 {
     $old = $this->getDefaults();
     $new = $this->getValues();
     $array = array();
     $array['all']['sympal_config'] = array();
     // Add only the values that have changed from the old default values
     foreach ($new as $key => $value) {
         if ($value != $old[$key]) {
             $array['all']['sympal_config'][$key] = $value;
         }
     }
     // Merge in existing values from the current app.yml file
     $array = sfToolkit::arrayDeepMerge(sfYaml::load(sfConfig::get('sf_app_dir') . '/config/app.yml'), $array);
     // Remove values that don't exist anymore
     foreach ($array['all']['sympal_config'] as $key => $value) {
         if (!array_key_exists($key, $new)) {
             unset($array['all']['sympal_config'][$key]);
         }
     }
     return $array;
 }
 /**
  * Execute handler
  * 
  * @param   array   $configFiles    Configuration files
  * @return  string  Php code for configuration file
  */
 public function execute($configFiles)
 {
     if (!($config = self::parseYamls($configFiles))) {
         return '';
     }
     if (!isset($config['generator'])) {
         throw new sfParseException(sprintf('Configuration file "%s" must specify a generator section.', isset($configFiles[1]) ? $configFiles[1] : $configFiles[0]));
     }
     $config = sfToolkit::arrayDeepMerge($this->getBaseConfig(), $config);
     $config = $this->configureI18nFields($this->configureSort($config['generator']));
     if (!isset($config['class'])) {
         throw new sfParseException(sprintf('Configuration file "%s" must specify a generator class section under the generator section.', isset($configFiles[1]) ? $configFiles[1] : $configFiles[0]));
     }
     foreach (array('fields', 'list', 'edit') as $section) {
         if (isset($config[$section])) {
             throw new sfParseException(sprintf('Configuration file "%s" can specify a "%s" section but only under the param section.', isset($configFiles[1]) ? $configFiles[1] : $configFiles[0], $section));
         }
     }
     $generatorManager = new sfGeneratorManager(sfContext::getInstance()->getConfiguration());
     $generatorParam = isset($config['param']) ? $config['param'] : array();
     preg_match('#.*/modules/([^/]+)/#', str_replace('\\', '/', $configFiles[0]), $match);
     $generatorParam['moduleName'] = $match[1];
     return sprintf("<?php\n// auto-generated by dinGeneratorConfigHandler\n// date: %s\n%s\n", date('Y/m/d H:i:s'), $generatorManager->generate($config['class'], $generatorParam));
 }
 protected function prepareSchemaFile($yamlSchemaPath)
 {
     $models = array();
     $finder = sfFinder::type('file')->name('schema.yml')->sort_by_name()->follow_link();
     // plugin models
     foreach ($this->configuration->getPlugins() as $name) {
         $plugin = $this->configuration->getPluginConfiguration($name);
         foreach ($finder->in($plugin->getRootDir() . '/config/sfMagento') as $schema) {
             $pluginModels = (array) sfYaml::load($schema);
             foreach ($pluginModels as $model => $definition) {
                 // merge this model into the schema
                 $models[$model] = isset($models[$model]) ? sfToolkit::arrayDeepMerge($models[$model], $definition) : $definition;
                 // the first plugin to define this model gets the package
                 if (!isset($models[$model]['package'])) {
                     $models[$model]['package'] = $plugin->getName() . '.lib.model.sfMagento';
                 }
                 if (!isset($models[$model]['package_custom_path']) && 0 === strpos($models[$model]['package'], $plugin->getName())) {
                     $models[$model]['package_custom_path'] = $plugin->getRootDir() . '/lib/model/sfMagento';
                 }
             }
         }
     }
     // project models
     foreach ($finder->in($yamlSchemaPath) as $schema) {
         $projectModels = (array) sfYaml::load($schema);
         foreach ($projectModels as $model => $definition) {
             // merge this model into the schema
             $models[$model] = isset($models[$model]) ? sfToolkit::arrayDeepMerge($models[$model], $definition) : $definition;
         }
     }
     // create one consolidated schema file
     $file = realpath(sys_get_temp_dir()) . '/sfMagento_schema_' . rand(11111, 99999) . '.yml';
     $this->logSection('file+', $file);
     file_put_contents($file, sfYaml::dump($models, 4));
     return $file;
 }
 /**
  * Generates a valid URLs for parameters.
  *
  * @param  array  The parameter values
  * @param  string The divider between key/value pairs
  * @param  string The equal sign to use between key and value
  *
  * @return string The generated URL
  */
 public function generate($name, $params, $querydiv = '/', $divider = '/', $equals = '/')
 {
     $global_defaults = sfConfig::get('sf_routing_defaults', null);
     // named route?
     if ($name) {
         if (!isset($this->routes[$name])) {
             $error = 'The route "%s" does not exist.';
             $error = sprintf($error, $name);
             throw new sfConfigurationException($error);
         }
         list($url, $regexp, $names, $names_hash, $defaults, $requirements, $suffix) = $this->routes[$name];
         if ($global_defaults !== null) {
             $defaults = array_merge($defaults, $global_defaults);
         }
         // all params must be given
         foreach ($names as $tmp) {
             if (!isset($params[$tmp]) && !isset($defaults[$tmp])) {
                 throw new sfException(sprintf('Route named "%s" have a mandatory "%s" parameter', $name, $tmp));
             }
         }
     } else {
         // find a matching route
         $found = false;
         foreach ($this->routes as $name => $route) {
             list($url, $regexp, $names, $names_hash, $defaults, $requirements, $suffix) = $route;
             if ($global_defaults !== null) {
                 $defaults = array_merge($defaults, $global_defaults);
             }
             $tparams = array_merge($defaults, $params);
             // we must match all names (all $names keys must be in $params array)
             foreach ($names as $key) {
                 if (!isset($tparams[$key])) {
                     continue 2;
                 }
             }
             // we must match all defaults with value except if present in names
             foreach ($defaults as $key => $value) {
                 if (isset($names_hash[$key])) {
                     continue;
                 }
                 if (!isset($tparams[$key]) || $tparams[$key] != $value) {
                     continue 2;
                 }
             }
             // we must match all requirements for rule
             foreach ($requirements as $req_param => $req_regexp) {
                 if (!preg_match('/' . str_replace('/', '\\/', $req_regexp) . '/', $tparams[$req_param])) {
                     continue 2;
                 }
             }
             // we must have consumed all $params keys if there is no * in route
             if (!strpos($url, '*')) {
                 if (count(array_diff(array_keys($tparams), $names, array_keys($defaults)))) {
                     continue;
                 }
             }
             // match found
             $found = true;
             break;
         }
         if (!$found) {
             $error = 'Unable to find a matching routing rule to generate url for params "%s".';
             $error = sprintf($error, var_export($params, true));
             throw new sfConfigurationException($error);
         }
     }
     $params = sfToolkit::arrayDeepMerge($defaults, $params);
     if (version_compare(PHP_VERSION, '5.5.0') >= 0) {
         $real_url = preg_replace_callback('/\\:([^\\/]+)/', function ($matches) use($params) {
             return urlencode($params[$matches[1]]);
         }, $url);
     } else {
         $real_url = preg_replace('/\\:([^\\/]+)/e', 'urlencode($params["\\1"])', $url);
     }
     // we add all other params if *
     if (strpos($real_url, '*')) {
         $tmp = array();
         foreach ($params as $key => $value) {
             if (isset($names_hash[$key]) || isset($defaults[$key])) {
                 continue;
             }
             if (is_array($value)) {
                 foreach ($value as $v) {
                     $tmp[] = $key . $equals . urlencode($v);
                 }
             } else {
                 $tmp[] = urlencode($key) . $equals . urlencode($value);
             }
         }
         $tmp = implode($divider, $tmp);
         if (strlen($tmp) > 0) {
             $tmp = $querydiv . $tmp;
         }
         $real_url = preg_replace('/\\/\\*(\\/|$)/', "{$tmp}\$1", $real_url);
     }
     // strip off last divider character
     if (strlen($real_url) > 1) {
         $real_url = rtrim($real_url, $divider);
     }
     if ($real_url != '/') {
         $real_url .= $suffix;
     }
     return $real_url;
 }
Example #19
0
 protected function schemaToXML($checkSchema = self::CHECK_SCHEMA, $prefix = '')
 {
     $finder = sfFinder::type('file')->name('*schema.yml')->prune('doctrine');
     $dirs = array_merge(array(sfConfig::get('sf_config_dir')), $this->configuration->getPluginSubPaths('/config'));
     $schemas = $finder->in($dirs);
     if (self::CHECK_SCHEMA === $checkSchema && !count($schemas)) {
         throw new sfCommandException('You must create a schema.yml file.');
     }
     $dbSchema = new sfPropelDatabaseSchema();
     foreach ($schemas as $schema) {
         $schemaArray = sfYaml::load($schema);
         if (!is_array($schemaArray)) {
             continue;
             // No defined schema here, skipping
         }
         if (!isset($schemaArray['classes'])) {
             // Old schema syntax: we convert it
             $schemaArray = $dbSchema->convertOldToNewYaml($schemaArray);
         }
         $customSchemaFilename = str_replace(array(str_replace(DIRECTORY_SEPARATOR, '/', sfConfig::get('sf_root_dir')) . '/', 'plugins/', 'config/', '/', 'schema.yml'), array('', '', '', '_', 'schema.custom.yml'), $schema);
         $customSchemas = sfFinder::type('file')->name($customSchemaFilename)->in($dirs);
         foreach ($customSchemas as $customSchema) {
             $this->logSection('schema', sprintf('found custom schema %s', $customSchema));
             $customSchemaArray = sfYaml::load($customSchema);
             if (!isset($customSchemaArray['classes'])) {
                 // Old schema syntax: we convert it
                 $customSchemaArray = $dbSchema->convertOldToNewYaml($customSchemaArray);
             }
             $schemaArray = sfToolkit::arrayDeepMerge($schemaArray, $customSchemaArray);
         }
         $dbSchema->loadArray($schemaArray);
         $this->logSection('schema', sprintf('converting "%s" to XML', $schema));
         $localprefix = $prefix;
         // change prefix for plugins
         if (preg_match('#plugins[/\\\\]([^/\\\\]+)[/\\\\]#', $schema, $match)) {
             $localprefix = $prefix . $match[1] . '-';
         }
         // save converted xml files in original directories
         $xml_file_name = str_replace('.yml', '.xml', basename($schema));
         $file = str_replace(basename($schema), $localprefix . $xml_file_name, $schema);
         $this->logSection('schema', sprintf('putting %s', $file));
         file_put_contents($file, $dbSchema->asXML());
     }
 }
 /**
  * @see sfConfigHandler
  */
 public static function getConfiguration(array $configFiles)
 {
     $config = self::parseYaml($configFiles[0]);
     foreach (array_slice($configFiles, 1) as $i => $configFile) {
         // we get the order of the new file and merge with the previous configurations
         $previous = $config;
         $config = array();
         foreach (self::parseYaml($configFile) as $key => $value) {
             $value = (array) $value;
             $config[$key] = isset($previous[$key]) ? sfToolkit::arrayDeepMerge($previous[$key], $value) : $value;
         }
         // check that every key in previous array is still present (to avoid problem when upgrading)
         foreach (array_keys($previous) as $key) {
             if (!isset($config[$key])) {
                 throw new sfConfigurationException(sprintf('The filter name "%s" is defined in "%s" but not present in "%s" file. To disable a filter, add a "enabled" key with a false value.', $key, $configFiles[$i], $configFile));
             }
         }
     }
     $config = self::replaceConstants($config);
     foreach ($config as $category => $keys) {
         if (isset($keys['file'])) {
             $config[$category]['file'] = self::replacePath($keys['file']);
         }
     }
     return $config;
 }
  /**
   * Looks for a link or a button in the response and submits the related request
   *
   * @param string The link/button value/href/alt
   * @param array request parameters (associative array)
   *
   * @return sfWebBrowser The current browser object
   */ 
  public function click($name, $arguments = array())
  {
    if (!$dom = $this->getResponseDom())
    {
      throw new Exception('Cannot click because there is no current page in the browser');
    }

    $xpath = new DomXpath($dom);

    // text link, the name being in an attribute
    if ($link = $xpath->query(sprintf('//a[@*="%s"]', $name))->item(0))
    {
      return $this->get($link->getAttribute('href'));
    }

    // text link, the name being the text value
    if ($links = $xpath->query('//a[@href]'))
    {
      foreach($links as $link)
      {
        if(preg_replace(array('/\s{2,}/', '/\\r\\n|\\n|\\r/'), array(' ', ''), $link->nodeValue) == $name)
        {
          return $this->get($link->getAttribute('href'));  
        }
      }
    }
    
    // image link, the name being the alt attribute value
    if ($link = $xpath->query(sprintf('//a/img[@alt="%s"]/ancestor::a', $name))->item(0))
    {
      return $this->get($link->getAttribute('href'));
    }

    // form, the name being the button or input value
    if (!$form = $xpath->query(sprintf('//input[((@type="submit" or @type="button") and @value="%s") or (@type="image" and @alt="%s")]/ancestor::form', $name, $name))->item(0))
    {
      throw new Exception(sprintf('Cannot find the "%s" link or button.', $name));
    }

    // form attributes
    $url = $form->getAttribute('action');
    $method = $form->getAttribute('method') ? strtolower($form->getAttribute('method')) : 'get';

    // merge form default values and arguments
    $defaults = array();
    foreach ($xpath->query('descendant::input | descendant::textarea | descendant::select', $form) as $element)
    {
      $elementName = $element->getAttribute('name');
      $nodeName    = $element->nodeName;
      $value       = null;
      if ($nodeName == 'input' && ($element->getAttribute('type') == 'checkbox' || $element->getAttribute('type') == 'radio'))
      {
        if ($element->getAttribute('checked'))
        {
          $value = $element->getAttribute('value');
        }
      }
      else if (
        $nodeName == 'input'
        &&
        (($element->getAttribute('type') != 'submit' && $element->getAttribute('type') != 'button') || $element->getAttribute('value') == $name)
        &&
        ($element->getAttribute('type') != 'image' || $element->getAttribute('alt') == $name)
      )
      {
        $value = $element->getAttribute('value');
      }
      else if ($nodeName == 'textarea')
      {
        $value = '';
        foreach ($element->childNodes as $el)
        {
          $value .= $dom->saveXML($el);
        }
      }
      else if ($nodeName == 'select')
      {
        if ($multiple = $element->hasAttribute('multiple'))
        {
          $elementName = str_replace('[]', '', $elementName);
          $value = array();
        }
        else
        {
          $value = null;
        }

        $found = false;
        foreach ($xpath->query('descendant::option', $element) as $option)
        {
          if ($option->getAttribute('selected'))
          {
            $found = true;
            if ($multiple)
            {
              $value[] = $option->getAttribute('value');
            }
            else
            {
              $value = $option->getAttribute('value');
            }
          }
        }

        // if no option is selected and if it is a simple select box, take the first option as the value
        if (!$found && !$multiple)
        {
          $value = $xpath->query('descendant::option', $element)->item(0)->getAttribute('value');
        }
      }

      if (null !== $value)
      {
        $this->parseArgumentAsArray($elementName, $value, $defaults);
      }
    }

    // create request parameters
    $arguments = sfToolkit::arrayDeepMerge($defaults, $this->fields, $arguments);
    if ('post' == $method)
    {
      return $this->post($url, $arguments);
    }
    else
    {
      return $this->get($url, $arguments);
    }
  }
 public static function arrayDeepMerge()
 {
     switch (func_num_args()) {
         case 0:
             return false;
         case 1:
             return func_get_arg(0);
         case 2:
             $args = func_get_args();
             $args[2] = array();
             if (is_array($args[0]) && is_array($args[1])) {
                 foreach (array_unique(array_merge(array_keys($args[0]), array_keys($args[1]))) as $key) {
                     $isKey0 = array_key_exists($key, $args[0]);
                     $isKey1 = array_key_exists($key, $args[1]);
                     if ($isKey0 && $isKey1 && is_array($args[0][$key]) && is_array($args[1][$key])) {
                         $args[2][$key] = self::arrayDeepMerge($args[0][$key], $args[1][$key]);
                     } else {
                         if ($isKey0 && $isKey1) {
                             $args[2][$key] = $args[1][$key];
                         } else {
                             if (!$isKey1) {
                                 $args[2][$key] = $args[0][$key];
                             } else {
                                 if (!$isKey0) {
                                     $args[2][$key] = $args[1][$key];
                                 }
                             }
                         }
                     }
                 }
                 return $args[2];
             } else {
                 return $args[1];
             }
         default:
             $args = func_get_args();
             $args[1] = sfToolkit::arrayDeepMerge($args[0], $args[1]);
             array_shift($args);
             return call_user_func_array(array('sfToolkit', 'arrayDeepMerge'), $args);
             break;
     }
 }
 /**
  * Simulates a click on the supplied DOM element.
  *
  * This method is called internally by the {@link click()} method.
  *
  * @param  DOMElement $item      The element being clicked
  * @param  array      $arguments The arguments to pass to the link
  * @param  array      $options   An array of options
  *
  * @return array An array composed of the URI, the method and the arguments to pass to the call() call
  *
  * @uses getResponseDomXpath()
  */
 public function doClickElement(DOMElement $item, $arguments = array(), $options = array())
 {
     $method = strtolower(isset($options['method']) ? $options['method'] : 'get');
     if ('a' == $item->nodeName) {
         if (in_array($method, array('post', 'put', 'delete'))) {
             if (isset($options['_with_csrf']) && $options['_with_csrf']) {
                 $arguments['_with_csrf'] = true;
             }
             return array($item->getAttribute('href'), $method, $arguments);
         } else {
             return array($item->getAttribute('href'), 'get', $arguments);
         }
     } else {
         if ('button' == $item->nodeName || 'input' == $item->nodeName && in_array($item->getAttribute('type'), array('submit', 'button', 'image'))) {
             // add the item's value to the arguments
             $this->parseArgumentAsArray($item->getAttribute('name'), $item->getAttribute('value'), $arguments);
             // use the ancestor form element
             do {
                 if (null === ($item = $item->parentNode)) {
                     throw new Exception('The clicked form element does not have a form ancestor.');
                 }
             } while ('form' != $item->nodeName);
         }
     }
     // form attributes
     $url = $item->getAttribute('action');
     if (!$url || '#' == $url) {
         $url = $this->stack[$this->stackPosition]['uri'];
     }
     $method = strtolower(isset($options['method']) ? $options['method'] : ($item->getAttribute('method') ? $item->getAttribute('method') : 'get'));
     // merge form default values and arguments
     $defaults = array();
     $arguments = sfToolkit::arrayDeepMerge($this->fields, $arguments);
     $xpath = $this->getResponseDomXpath();
     foreach ($xpath->query('descendant::input | descendant::textarea | descendant::select', $item) as $element) {
         if ($element->hasAttribute('disabled')) {
             continue;
         }
         $elementName = $element->getAttribute('name');
         $nodeName = $element->nodeName;
         $value = null;
         if ($nodeName == 'input' && ($element->getAttribute('type') == 'checkbox' || $element->getAttribute('type') == 'radio')) {
             if ($element->getAttribute('checked')) {
                 $value = $element->hasAttribute('value') ? $element->getAttribute('value') : '1';
             }
         } else {
             if ($nodeName == 'input' && $element->getAttribute('type') == 'file') {
                 $filename = array_key_exists($elementName, $arguments) ? $arguments[$elementName] : sfToolkit::getArrayValueForPath($arguments, $elementName, '');
                 if (is_readable($filename)) {
                     $fileError = UPLOAD_ERR_OK;
                     $fileSize = filesize($filename);
                 } else {
                     $fileError = UPLOAD_ERR_NO_FILE;
                     $fileSize = 0;
                 }
                 unset($arguments[$elementName]);
                 $this->parseArgumentAsArray($elementName, array('name' => basename($filename), 'type' => '', 'tmp_name' => $filename, 'error' => $fileError, 'size' => $fileSize), $this->files);
             } else {
                 if ('input' == $nodeName && !in_array($element->getAttribute('type'), array('submit', 'button', 'image'))) {
                     $value = $element->getAttribute('value');
                 } else {
                     if ($nodeName == 'textarea') {
                         $value = '';
                         foreach ($element->childNodes as $el) {
                             $value .= $this->getResponseDom()->saveXML($el);
                         }
                     } else {
                         if ($nodeName == 'select') {
                             if ($multiple = $element->hasAttribute('multiple')) {
                                 $elementName = str_replace('[]', '', $elementName);
                                 $value = array();
                             } else {
                                 $value = null;
                             }
                             $found = false;
                             foreach ($xpath->query('descendant::option', $element) as $option) {
                                 if ($option->getAttribute('selected')) {
                                     $found = true;
                                     if ($multiple) {
                                         $value[] = $option->getAttribute('value');
                                     } else {
                                         $value = $option->getAttribute('value');
                                     }
                                 }
                             }
                             // if no option is selected and if it is a simple select box, take the first option as the value
                             $option = $xpath->query('descendant::option', $element)->item(0);
                             if (!$found && !$multiple && $option instanceof DOMElement) {
                                 $value = $option->getAttribute('value');
                             }
                         }
                     }
                 }
             }
         }
         if (null !== $value) {
             $this->parseArgumentAsArray($elementName, $value, $defaults);
         }
     }
     // create request parameters
     $arguments = sfToolkit::arrayDeepMerge($defaults, $arguments);
     if (in_array($method, array('post', 'put', 'delete'))) {
         return array($url, $method, $arguments);
     } else {
         $queryString = http_build_query($arguments, null, '&');
         $sep = false === strpos($url, '?') ? '?' : '&';
         return array($url . ($queryString ? $sep . $queryString : ''), 'get', array());
     }
 }
Example #24
0
  sfToolkit::arrayDeepMerge(array('d' => 'due', 't' => 'tre'), array('d' => 'bis', 'q' => 'quattro')),
  array('d' => 'bis', 't' => 'tre', 'q' => 'quattro'),
  '::arrayDeepMerge() merges linear arrays preserving literal keys'
);
$t->is(
  sfToolkit::arrayDeepMerge(array('d' => 'due', 't' => 'tre', 'c' => array('c' => 'cinco')), array('d' => array('due', 'bis'), 'q' => 'quattro', 'c' => array('c' => 'cinque', 'c2' => 'cinco'))),
  array('d' => array('due', 'bis'), 't' => 'tre', 'q' => 'quattro', 'c' => array('c' => 'cinque', 'c2' => 'cinco')),
  '::arrayDeepMerge() recursively merges arrays preserving literal keys'
);
$t->is(
  sfToolkit::arrayDeepMerge(array(2 => 'due', 3 => 'tre'), array(2 => 'bis', 4 => 'quattro')),
  array(2 => 'bis', 3 => 'tre', 4 => 'quattro'),
  '::arrayDeepMerge() merges linear arrays preserving numerical keys'
);
$t->is(
  sfToolkit::arrayDeepMerge(array(2 => array('due'), 3 => 'tre'), array(2 => array('bis', 'bes'), 4 => 'quattro')),
  array(2 => array('bis', 'bes'), 3 => 'tre', 4 => 'quattro'),
  '::arrayDeepMerge() recursively merges arrays preserving numerical keys'
);

$arr = array(
  'foobar' => 'foo',
  'foo' => array(
    'bar' => array(
      'baz' => 'foo bar',
    ),
  ),
  'bar' => array(
    'foo',
    'bar',
  ),
 /**
  * Executes this configuration handler
  *
  * @param array An array of absolute filesystem path to a configuration file
  *
  * @return string Data to be written to a cache file
  *
  * @throws sfConfigurationException If a requested configuration file does not exist or is not readable
  * @throws sfParseException If a requested configuration file is improperly formatted
  */
 public function execute($configFiles)
 {
     // parse the yaml
     $config = $this->parseYaml($configFiles[0]);
     foreach (array_slice($configFiles, 1) as $i => $configFile) {
         // we get the order of the new file and merge with the previous configurations
         $previous = $config;
         $config = array();
         foreach ($this->parseYaml($configFile) as $key => $value) {
             $value = (array) $value;
             $config[$key] = isset($previous[$key]) ? sfToolkit::arrayDeepMerge($previous[$key], $value) : $value;
         }
         // check that every key in previous array is still present (to avoid problem when upgrading)
         foreach (array_keys($previous) as $key) {
             if (!isset($config[$key])) {
                 throw new sfConfigurationException(sprintf('The filter name "%s" is defined in "%s" but not present in "%s" file. To disable a filter, add a "enabled" key with a false value', $key, $configFiles[$i], $configFile));
             }
         }
     }
     // init our data and includes arrays
     $data = array();
     $includes = array();
     $execution = false;
     $rendering = false;
     // let's do our fancy work
     foreach ($config as $category => $keys) {
         if (isset($keys['enabled']) && !$keys['enabled']) {
             continue;
         }
         if (!isset($keys['class'])) {
             // missing class key
             $error = 'Configuration file "%s" specifies category "%s" with missing class key';
             $error = sprintf($error, $configFiles[0], $category);
             throw new sfParseException($error);
         }
         $class = $keys['class'];
         if (isset($keys['file'])) {
             // we have a file to include
             $file = $this->replaceConstants($keys['file']);
             $file = $this->replacePath($file);
             if (!is_readable($file)) {
                 // filter file doesn't exist
                 $error = sprintf('Configuration file "%s" specifies class "%s" with nonexistent or unreadable file "%s"', $configFiles[0], $class, $file);
                 throw new sfParseException($error);
             }
             // append our data
             $includes[] = sprintf("require_once('%s');\n", $file);
         }
         $condition = true;
         if (isset($keys['param']['condition'])) {
             $condition = $this->replaceConstants($keys['param']['condition']);
             unset($keys['param']['condition']);
         }
         $type = isset($keys['param']['type']) ? $keys['param']['type'] : null;
         unset($keys['param']['type']);
         if ($condition) {
             // parse parameters
             $parameters = isset($keys['param']) ? var_export($keys['param'], true) : 'null';
             // append new data
             if ('security' == $type) {
                 $data[] = $this->addSecurityFilter($category, $class, $parameters);
             } else {
                 $data[] = $this->addFilter($category, $class, $parameters);
             }
             if ('rendering' == $type) {
                 $rendering = true;
             }
             if ('execution' == $type) {
                 $execution = true;
             }
         }
     }
     if (!$rendering) {
         $error = sprintf('Configuration file "%s" must register a filter of type "rendering"', $configFiles[0]);
         throw new sfParseException($error);
     }
     if (!$execution) {
         $error = sprintf('Configuration file "%s" must register a filter of type "execution"', $configFiles[0]);
         throw new sfParseException($error);
     }
     // compile data
     $retval = sprintf("<?php\n" . "// auto-generated by sfFilterConfigHandler\n" . "// date: %s%s\n%s\n\n", date('Y/m/d H:i:s'), implode("\n", $includes), implode("\n", $data));
     return $retval;
 }
 /**
  * Merges assets and environement configuration.
  *
  * @param array A configuration array
  */
 protected function mergeConfig($myConfig)
 {
     // merge javascripts and stylesheets
     $myConfig['all']['stylesheets'] = array_merge(isset($myConfig['default']['stylesheets']) && is_array($myConfig['default']['stylesheets']) ? $myConfig['default']['stylesheets'] : array(), isset($myConfig['all']['stylesheets']) && is_array($myConfig['all']['stylesheets']) ? $myConfig['all']['stylesheets'] : array());
     unset($myConfig['default']['stylesheets']);
     $myConfig['all']['javascripts'] = array_merge(isset($myConfig['default']['javascripts']) && is_array($myConfig['default']['javascripts']) ? $myConfig['default']['javascripts'] : array(), isset($myConfig['all']['javascripts']) && is_array($myConfig['all']['javascripts']) ? $myConfig['all']['javascripts'] : array());
     unset($myConfig['default']['javascripts']);
     // merge default and all
     $myConfig['all'] = sfToolkit::arrayDeepMerge(isset($myConfig['default']) && is_array($myConfig['default']) ? $myConfig['default'] : array(), isset($myConfig['all']) && is_array($myConfig['all']) ? $myConfig['all'] : array());
     unset($myConfig['default']);
     $this->yamlConfig = $myConfig;
 }
 /**
  * Adds configuration for current datasource.
  */
 public function addConfig()
 {
     if ($dsn = $this->getParameter('dsn')) {
         $params = $this->parseDsn($dsn);
         $options = array('dsn', 'phptype', 'hostspec', 'database', 'username', 'password', 'port', 'protocol', 'encoding', 'persistent', 'socket', 'compat_assoc_lower', 'compat_rtrim_string');
         foreach ($options as $option) {
             if (!$this->getParameter($option) && isset($params[$option])) {
                 $this->setParameter($option, $params[$option]);
             }
         }
     }
     if ($this->hasParameter('persistent')) {
         // for BC
         $this->setParameter('options', array_merge($this->getParameter('options', array()), array('ATTR_PERSISTENT' => $this->getParameter('persistent'))));
     }
     $propelConfiguration = Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT);
     if ($this->hasParameter('debug')) {
         $propelConfiguration->setParameter('debugpdo.logging', sfToolkit::arrayDeepMerge($propelConfiguration->getParameter('debugpdo.logging', array()), $this->getParameter('debug')));
     }
     $event = new sfEvent($propelConfiguration, 'propel.filter_connection_config', array('name' => $this->getParameter('datasource'), 'database' => $this));
     $event = sfProjectConfiguration::getActive()->getEventDispatcher()->filter($event, array('adapter' => $this->getParameter('phptype'), 'connection' => array('dsn' => $this->getParameter('dsn'), 'user' => $this->getParameter('username'), 'password' => $this->getParameter('password'), 'classname' => $this->getParameter('classname', 'PropelPDO'), 'options' => $this->getParameter('options', array()), 'settings' => array('charset' => array('value' => $this->getParameter('encoding', sfConfig::get('sf_charset'))), 'queries' => $this->getParameter('queries', array())))));
     $propelConfiguration->setParameter('datasources.' . $this->getParameter('datasource'), $event->getReturnValue());
 }
 protected static function mergeConfig($config)
 {
     // merge javascripts and stylesheets
     $config['all']['stylesheets'] = array_merge(isset($config['default']['stylesheets']) && is_array($config['default']['stylesheets']) ? $config['default']['stylesheets'] : array(), isset($config['all']['stylesheets']) && is_array($config['all']['stylesheets']) ? $config['all']['stylesheets'] : array());
     unset($config['default']['stylesheets']);
     $config['all']['javascripts'] = array_merge(isset($config['default']['javascripts']) && is_array($config['default']['javascripts']) ? $config['default']['javascripts'] : array(), isset($config['all']['javascripts']) && is_array($config['all']['javascripts']) ? $config['all']['javascripts'] : array());
     unset($config['default']['javascripts']);
     // merge default and all
     $config['all'] = sfToolkit::arrayDeepMerge(isset($config['default']) && is_array($config['default']) ? $config['default'] : array(), isset($config['all']) && is_array($config['all']) ? $config['all'] : array());
     unset($config['default']);
     return static::replaceConstants($config);
 }
 /**
  * @see sfConfigHandler
  *
  * Additionally this method merges modules
  */
 public static function getConfiguration(array $configFiles)
 {
     $config = array();
     foreach ($configFiles as $configFile) {
         $values = self::parseYaml($configFile);
         // BC 5.0_BETA6 "Content" was named "Project"
         if (isset($values['Project']) && !isset($values['Content'])) {
             $values['Content'] = $values['Project'];
             unset($values['Project']);
         }
         $pluginName = self::isProjectConfigFile($configFile) ? false : basename(str_replace('/config/dm/modules.yml', '', $configFile));
         foreach ($values as $valuesTypeName => $valuesType) {
             foreach ($valuesType as $valuesSpaceName => $valuesSpace) {
                 foreach (array_keys($valuesSpace) as $moduleKey) {
                     // add plugin name
                     $values[$valuesTypeName][$valuesSpaceName][$moduleKey]['plugin'] = $pluginName;
                     // fix non modulized module keys
                     if ($moduleKey !== dmString::modulize($moduleKey)) {
                         $values[$valuesTypeName][$valuesSpaceName][dmString::modulize($moduleKey)] = $values[$valuesTypeName][$valuesSpaceName][$moduleKey];
                         unset($values[$valuesTypeName][$valuesSpaceName][$moduleKey]);
                     }
                 }
                 // merge overridden modules
                 foreach ($config as $configTypeName => $configType) {
                     foreach ($configType as $configSpaceName => $configSpace) {
                         foreach (array_intersect_key($values[$valuesTypeName][$valuesSpaceName], $configSpace) as $moduleKey => $module) {
                             // merge the new module with the old one
                             $values[$valuesTypeName][$valuesSpaceName][$moduleKey] = sfToolkit::arrayDeepMerge($configSpace[$moduleKey], $values[$valuesTypeName][$valuesSpaceName][$moduleKey]);
                             $values[$valuesTypeName][$valuesSpaceName][$moduleKey]['overridden'] = true;
                             $values[$valuesTypeName][$valuesSpaceName][$moduleKey]['plugin'] = $configSpace[$moduleKey]['plugin'];
                             // remove the old module
                             unset($config[$configTypeName][$configSpaceName][$moduleKey]);
                         }
                     }
                 }
             }
         }
         $config = sfToolkit::arrayDeepMerge($config, $values);
     }
     return $config;
 }
 /**
  * Merges default, all and current environment configurations.
  *
  * @param array $config The main configuratino array
  *
  * @return array The merged configuration
  */
 public static function flattenConfigurationWithEnvironment($config)
 {
     return sfToolkit::arrayDeepMerge(isset($config['default']) && is_array($config['default']) ? $config['default'] : array(), isset($config['all']) && is_array($config['all']) ? $config['all'] : array(), isset($config[sfConfig::get('sf_environment')]) && is_array($config[sfConfig::get('sf_environment')]) ? $config[sfConfig::get('sf_environment')] : array());
 }