initial commit

This commit is contained in:
Chris Sewell
2012-11-28 03:55:08 -05:00
parent 7adb399b2e
commit cf140a2e97
3247 changed files with 492437 additions and 0 deletions

View File

@ -0,0 +1,130 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004-2006 Sean Kerr.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfAutoloadConfigHandler.class.php 3256 2007-01-13 08:39:10Z fabien $
*/
class sfAutoloadConfigHandler extends sfYamlConfigHandler
{
/**
* 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)
{
// set our required categories list and initialize our handler
$categories = array('required_categories' => array('autoload'));
$this->initialize($categories);
// parse the yaml
$myConfig = $this->parseYamls($configFiles);
// init our data array
$data = array();
// let's do our fancy work
foreach ($myConfig['autoload'] as $name => $entry)
{
if (isset($entry['name']))
{
$data[] = sprintf("\n// %s", $entry['name']);
}
// file mapping or directory mapping?
if (isset($entry['files']))
{
// file mapping
foreach ($entry['files'] as $class => $path)
{
$path = $this->replaceConstants($path);
$data[] = sprintf("'%s' => '%s',", $class, $path);
}
}
else
{
// directory mapping
$ext = isset($entry['ext']) ? $entry['ext'] : '.php';
$path = $entry['path'];
$path = $this->replaceConstants($path);
$path = $this->replacePath($path);
// we automatically add our php classes
require_once(sfConfig::get('sf_symfony_lib_dir').'/util/sfFinder.class.php');
$finder = sfFinder::type('file')->ignore_version_control()->name('*'.$ext);
// recursive mapping?
$recursive = ((isset($entry['recursive'])) ? $entry['recursive'] : false);
if (!$recursive)
{
$finder->maxdepth(1);
}
// exclude files or directories?
if (isset($entry['exclude']) && is_array($entry['exclude']))
{
$finder->prune($entry['exclude'])->discard($entry['exclude']);
}
if ($matches = glob($path))
{
$files = $finder->in($matches);
}
else
{
$files = array();
}
$regex = '~^\s*(?:abstract\s+|final\s+)?(?:class|interface)\s+(\w+)~mi';
foreach ($files as $file)
{
preg_match_all($regex, file_get_contents($file), $classes);
foreach ($classes[1] as $class)
{
$prefix = '';
if (isset($entry['prefix']))
{
// FIXME: does not work for plugins installed with a symlink
preg_match('~^'.str_replace('\*', '(.+?)', preg_quote(str_replace('/', DIRECTORY_SEPARATOR, $path), '~')).'~', $file, $match);
if (isset($match[$entry['prefix']]))
{
$prefix = $match[$entry['prefix']].'/';
}
}
$data[] = sprintf("'%s%s' => '%s',", $prefix, $class, $file);
}
}
}
}
// compile data
$retval = sprintf("<?php\n".
"// auto-generated by sfAutoloadConfigHandler\n".
"// date: %s\nreturn array(\n%s\n);\n",
date('Y/m/d H:i:s'), implode("\n", $data));
return $retval;
}
}

View File

@ -0,0 +1,119 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfCacheConfigHandler allows you to configure cache.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfCacheConfigHandler.class.php 3203 2007-01-09 18:32:54Z fabien $
*/
class sfCacheConfigHandler extends sfYamlConfigHandler
{
protected
$cacheConfig = array();
/**
* 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;
}
/**
* Returns a single addCache statement.
*
* @param string The action name
*
* @return string PHP code for the addCache statement
*/
protected function addCache($actionName = '')
{
$data = array();
// enabled?
$enabled = $this->getConfigValue('enabled', $actionName);
// cache with or without loayout
$withLayout = $this->getConfigValue('with_layout', $actionName) ? 'true' : 'false';
// lifetime
$lifeTime = !$enabled ? '0' : $this->getConfigValue('lifetime', $actionName, '0');
// client_lifetime
$clientLifetime = !$enabled ? '0' : $this->getConfigValue('client_lifetime', $actionName, $lifeTime, '0');
// contextual
$contextual = $this->getConfigValue('contextual', $actionName) ? 'true' : 'false';
// vary
$vary = $this->getConfigValue('vary', $actionName, array());
if (!is_array($vary))
{
$vary = array($vary);
}
// add cache information to cache manager
$data[] = sprintf("\$this->addCache(\$moduleName, '%s', array('withLayout' => %s, 'lifeTime' => %s, 'clientLifeTime' => %s, 'contextual' => %s, 'vary' => %s));\n",
$actionName, $withLayout, $lifeTime, $clientLifetime, $contextual, str_replace("\n", '', var_export($vary, true)));
return implode("\n", $data);
}
}

View File

@ -0,0 +1,113 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004-2006 Sean Kerr.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfCompileConfigHandler gathers multiple files and puts them into a single file.
* Upon creation of the new file, all comments and blank lines are removed.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfCompileConfigHandler.class.php 5061 2007-09-13 06:49:52Z fabien $
*/
class sfCompileConfigHandler extends sfYamlConfigHandler
{
/**
* 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 = array();
foreach ($configFiles as $configFile)
{
$config = array_merge($config, $this->parseYaml($configFile));
}
// init our data
$data = '';
// let's do our fancy work
foreach ($config as $file)
{
$file = $this->replaceConstants($file);
$file = $this->replacePath($file);
if (!is_readable($file))
{
// file doesn't exist
$error = sprintf('Configuration file "%s" specifies nonexistent or unreadable file "%s"', $configFiles[0], $file);
throw new sfParseException($error);
}
$contents = file_get_contents($file);
// strip comments (not in debug mode)
if (!sfConfig::get('sf_debug'))
{
$contents = sfToolkit::stripComments($contents);
}
// insert configuration files
$contents = preg_replace_callback(array('#(require|include)(_once)?\((sfConfigCache::getInstance\(\)|\$configCache)->checkConfig\([^_]+sf_app_config_dir_name[^\.]*\.\'/([^\']+)\'\)\);#m',
'#()()(sfConfigCache::getInstance\(\)|\$configCache)->import\(.sf_app_config_dir_name\.\'/([^\']+)\'(, false)?\);#m'),
array($this, 'insertConfigFileCallback'), $contents);
// strip php tags
$contents = sfToolkit::pregtr($contents, array('/^\s*<\?(php)?/m' => '',
'/^\s*\?>/m' => ''));
// replace windows and mac format with unix format
$contents = str_replace("\r", "\n", $contents);
// replace multiple new lines with a single newline
$contents = preg_replace(array('/\s+$/Sm', '/\n+/S'), "\n", $contents);
// append file data
$data .= "\n".$contents;
}
// compile data
$retval = sprintf("<?php\n".
"// auto-generated by sfCompileConfigHandler\n".
"// date: %s\n%s\n",
date('Y/m/d H:i:s'), $data);
// save current symfony release
file_put_contents(sfConfig::get('sf_config_cache_dir').'/VERSION', file_get_contents(sfConfig::get('sf_symfony_lib_dir').'/VERSION'));
return $retval;
}
/**
* Callback for configuration file insertion in the cache.
*
*/
protected function insertConfigFileCallback($matches)
{
$configFile = sfConfig::get('sf_app_config_dir_name').'/'.$matches[4];
sfConfigCache::getInstance()->checkConfig($configFile);
$config = "// '$configFile' config file\n".
file_get_contents(sfConfigCache::getInstance()->getCacheName($configFile));
return $config;
}
}

View File

@ -0,0 +1,93 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfConfig stores all configuration information for a symfony application.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfConfig.class.php 3203 2007-01-09 18:32:54Z fabien $
*/
class sfConfig
{
protected static
$config = array();
/**
* Retrieves a config parameter.
*
* @param string A config parameter name
* @param mixed A default config parameter value
*
* @return mixed A config parameter value, if the config parameter exists, otherwise null
*/
public static function get($name, $default = null)
{
return isset(self::$config[$name]) ? self::$config[$name] : $default;
}
/**
* Indicates whether or not a config parameter exists.
*
* @param string A config parameter name
*
* @return bool true, if the config parameter exists, otherwise false
*/
public static function has($name)
{
return array_key_exists($name, self::$config);
}
/**
* Sets a config parameter.
*
* If a config parameter with the name already exists the value will be overridden.
*
* @param string A config parameter name
* @param mixed A config parameter value
*/
public static function set($name, $value)
{
self::$config[$name] = $value;
}
/**
* Sets an array of config parameters.
*
* If an existing config parameter name matches any of the keys in the supplied
* array, the associated value will be overridden.
*
* @param array An associative array of config parameters and their associated values
*/
public static function add($parameters = array())
{
self::$config = array_merge(self::$config, $parameters);
}
/**
* Retrieves all configuration parameters.
*
* @return array An associative array of configuration parameters.
*/
public static function getAll()
{
return self::$config;
}
/**
* Clears all current config parameters.
*/
public static function clear()
{
self::$config = null;
self::$config = array();
}
}

View File

@ -0,0 +1,342 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004-2006 Sean Kerr.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfConfigCache allows you to customize the format of a configuration file to
* make it easy-to-use, yet still provide a PHP formatted result for direct
* inclusion into your modules.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfConfigCache.class.php 3503 2007-02-18 19:08:26Z fabien $
*/
class sfConfigCache
{
protected
$handlers = array();
protected static
$instance = null;
/**
* Retrieves the singleton instance of this class.
*
* @return sfConfigCache A sfConfigCache instance
*/
public static function getInstance()
{
if (!self::$instance)
{
self::$instance = new sfConfigCache();
}
return self::$instance;
}
/**
* Loads a configuration handler.
*
* @param string The handler to use when parsing a configuration file
* @param array An array of absolute filesystem paths to configuration files
* @param string An absolute filesystem path to the cache file that will be written
*
* @throws <b>sfConfigurationException</b> If a requested configuration file does not have an associated configuration handler
*/
protected function callHandler($handler, $configs, $cache)
{
if (count($this->handlers) == 0)
{
// we need to load the handlers first
$this->loadConfigHandlers();
}
// handler to call for this configuration file
$handlerToCall = null;
$handler = str_replace(DIRECTORY_SEPARATOR, '/', $handler);
// grab the base name of the handler
$basename = basename($handler);
if (isset($this->handlers[$handler]))
{
// we have a handler associated with the full configuration path
$handlerToCall = $this->handlers[$handler];
}
else if (isset($this->handlers[$basename]))
{
// we have a handler associated with the configuration base name
$handlerToCall = $this->handlers[$basename];
}
else
{
// let's see if we have any wildcard handlers registered that match
// this basename
foreach ($this->handlers as $key => $handlerInstance)
{
// replace wildcard chars in the configuration
$pattern = strtr($key, array('.' => '\.', '*' => '.*?'));
// create pattern from config
if (preg_match('#'.$pattern.'#', $handler))
{
// we found a match!
$handlerToCall = $this->handlers[$key];
break;
}
}
}
if ($handlerToCall)
{
// call the handler and retrieve the cache data
$data = $handlerToCall->execute($configs);
$this->writeCacheFile($handler, $cache, $data);
}
else
{
// we do not have a registered handler for this file
$error = sprintf('Configuration file "%s" does not have a registered handler', implode(', ', $configs));
throw new sfConfigurationException($error);
}
}
/**
* Checks to see if a configuration file has been modified and if so
* recompile the cache file associated with it.
*
* The recompilation only occurs in a non debug environment.
*
* If the configuration file path is relative, symfony will look in directories
* defined in the sfLoader::getConfigPaths() method.
*
* @param string A filesystem path to a configuration file
*
* @return string An absolute filesystem path to the cache filename associated with this specified configuration file
*
* @throws <b>sfConfigurationException</b> If a requested configuration file does not exist
*
* @see sfLoader::getConfigPaths()
*/
public function checkConfig($configPath, $optional = false)
{
static $process_cache_cleared = false;
if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled'))
{
$timer = sfTimerManager::getTimer('Configuration');
}
// the cache filename we'll be using
$cache = $this->getCacheName($configPath);
if (sfConfig::get('sf_in_bootstrap') && is_readable($cache))
{
if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled'))
{
$timer->addTime();
}
return $cache;
}
if (!sfToolkit::isPathAbsolute($configPath))
{
$files = sfLoader::getConfigPaths($configPath);
}
else
{
$files = is_readable($configPath) ? array($configPath) : array();
}
if (!isset($files[0]))
{
if ($optional)
{
return null;
}
// configuration does not exist
$error = sprintf('Configuration "%s" does not exist or is unreadable', $configPath);
throw new sfConfigurationException($error);
}
// find the more recent configuration file last modification time
$mtime = 0;
foreach ($files as $file)
{
if (filemtime($file) > $mtime)
{
$mtime = filemtime($file);
}
}
if (!is_readable($cache) || $mtime > filemtime($cache))
{
// configuration has changed so we need to reparse it
$this->callHandler($configPath, $files, $cache);
// clear process cache
if ('config/config_handlers.yml' != $configPath && sfConfig::has('sf_use_process_cache') && !$process_cache_cleared)
{
sfProcessCache::clear();
$process_cache_cleared = true;
}
}
if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled'))
{
$timer->addTime();
}
return $cache;
}
/**
* Clears all configuration cache files.
*/
public function clear()
{
sfToolkit::clearDirectory(sfConfig::get('sf_config_cache_dir'));
}
/**
* Converts a normal filename into a cache filename.
*
* @param string A normal filename
*
* @return string An absolute filesystem path to a cache filename
*/
public function getCacheName($config)
{
if (strlen($config) > 3 && ctype_alpha($config[0]) && $config[1] == ':' && ($config[2] == '\\' || $config[2] == '/'))
{
// file is a windows absolute path, strip off the drive letter
$config = substr($config, 3);
}
// replace unfriendly filename characters with an underscore
$config = str_replace(array('\\', '/', ' '), '_', $config);
$config .= '.php';
return sfConfig::get('sf_config_cache_dir').'/'.$config;
}
/**
* Imports a configuration file.
*
* @param string A filesystem path to a configuration file
* @param bool Only allow this configuration file to be included once per request?
*
* @see checkConfig()
*/
public function import($config, $once = true, $optional = false)
{
$cache = $this->checkConfig($config, $optional);
if ($optional && !$cache)
{
return;
}
// include cache file
if ($once)
{
include_once($cache);
}
else
{
include($cache);
}
}
/**
* Loads all configuration application and module level handlers.
*
* @throws <b>sfConfigurationException</b> If a configuration related error occurs.
*/
protected function loadConfigHandlers()
{
// manually create our config_handlers.yml handler
$this->handlers['config_handlers.yml'] = new sfRootConfigHandler();
$this->handlers['config_handlers.yml']->initialize();
// application configuration handlers
require_once($this->checkConfig(sfConfig::get('sf_app_config_dir_name').'/config_handlers.yml'));
// module level configuration handlers
// make sure our modules directory exists
if (is_readable($sf_app_module_dir = sfConfig::get('sf_app_module_dir')))
{
// ignore names
$ignore = array('.', '..', 'CVS', '.svn');
// create a file pointer to the module dir
$fp = opendir($sf_app_module_dir);
// loop through the directory and grab the modules
while (($directory = readdir($fp)) !== false)
{
if (!in_array($directory, $ignore))
{
$configPath = $sf_app_module_dir.'/'.$directory.'/'.sfConfig::get('sf_app_module_config_dir_name').'/config_handlers.yml';
if (is_readable($configPath))
{
// initialize the root configuration handler with this module name
$params = array('module_level' => true, 'module_name' => $directory);
$this->handlers['config_handlers.yml']->initialize($params);
// replace module dir path with a special keyword that
// checkConfig knows how to use
$configPath = sfConfig::get('sf_app_module_dir_name').'/'.$directory.'/'.sfConfig::get('sf_app_module_config_dir_name').'/config_handlers.yml';
require_once($this->checkConfig($configPath));
}
}
}
// close file pointer
fclose($fp);
}
else
{
// module directory doesn't exist or isn't readable
$error = sprintf('Module directory "%s" does not exist or is not readable',
sfConfig::get('sf_app_module_dir'));
throw new sfConfigurationException($error);
}
}
/**
* Writes a cache file.
*
* @param string An absolute filesystem path to a configuration file
* @param string An absolute filesystem path to the cache file that will be written
* @param string Data to be written to the cache file
*
* @throws sfCacheException If the cache file cannot be written
*/
protected function writeCacheFile($config, $cache, &$data)
{
$fileCache = new sfFileCache(dirname($cache));
$fileCache->setSuffix('');
$fileCache->set(basename($cache), '', $data);
}
}

View File

@ -0,0 +1,105 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004-2006 Sean Kerr.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfConfigHandler allows a developer to create a custom formatted configuration
* file pertaining to any information they like and still have it auto-generate
* PHP code.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfConfigHandler.class.php 3203 2007-01-09 18:32:54Z fabien $
*/
abstract class sfConfigHandler
{
protected
$parameterHolder = null;
/**
* Executes this configuration handler
*
* @param array An array of 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
*/
abstract public function execute($configFiles);
/**
* Initializes this configuration handler.
*
* @param array An associative array of initialization parameters
*
* @return bool true, if initialization completes successfully, otherwise false
*
* @throws <b>sfInitializationException</b> If an error occurs while initializing this ConfigHandler
*/
public function initialize($parameters = null)
{
$this->parameterHolder = new sfParameterHolder();
$this->parameterHolder->add($parameters);
}
/**
* Replaces constant identifiers in a value.
*
* If the value is an array replacements are made recursively.
*
* @param mixed The value on which to run the replacement procedure
*
* @return string The new value
*/
public static function replaceConstants($value)
{
if (is_array($value))
{
array_walk_recursive($value, create_function('&$value', '$value = sfToolkit::replaceConstants($value);'));
}
else
{
$value = sfToolkit::replaceConstants($value);
}
return $value;
}
/**
* Replaces a relative filesystem path with an absolute one.
*
* @param string A relative filesystem path
*
* @return string The new path
*/
public static function replacePath($path)
{
if (!sfToolkit::isPathAbsolute($path))
{
// not an absolute path so we'll prepend to it
$path = sfConfig::get('sf_app_dir').'/'.$path;
}
return $path;
}
/**
* Gets the parameter holder for this configuration handler.
*
* @return sfParameterHolder A sfParameterHolder instance
*/
public function getParameterHolder()
{
return $this->parameterHolder;
}
}

View File

@ -0,0 +1,120 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004-2006 Sean Kerr.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfDatabaseConfigHandler allows you to setup database connections in a
* configuration file that will be created for you automatically upon first
* request.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfDatabaseConfigHandler.class.php 3254 2007-01-13 07:52:26Z fabien $
*/
class sfDatabaseConfigHandler extends sfYamlConfigHandler
{
/**
* 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;
}
}

View File

@ -0,0 +1,159 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfDefineEnvironmentConfigHandler.class.php 3254 2007-01-13 07:52:26Z fabien $
*/
class sfDefineEnvironmentConfigHandler extends sfYamlConfigHandler
{
/**
* Executes this configuration handler.
*
* @param string An 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)
{
// get our prefix
$prefix = strtolower($this->getParameterHolder()->get('prefix', ''));
// add dynamic prefix if needed
if ($this->getParameterHolder()->get('module', false))
{
$prefix .= "'.strtolower(\$moduleName).'_";
}
// parse the yaml
$myConfig = $this->mergeEnvironment($this->parseYamls($configFiles));
$values = array();
foreach ($myConfig as $category => $keys)
{
$values = array_merge($values, $this->getValues($prefix, $category, $keys));
}
$data = '';
foreach ($values as $key => $value)
{
$data .= sprintf(" '%s' => %s,\n", $key, var_export($value, true));
}
// compile data
$retval = '';
if ($values)
{
$retval = "<?php\n".
"// auto-generated by sfDefineEnvironmentConfigHandler\n".
"// date: %s\nsfConfig::add(array(\n%s));\n";
$retval = sprintf($retval, date('Y/m/d H:i:s'), $data);
}
return $retval;
}
/**
* Gets values from the configuration array.
*
* @param string The prefix name
* @param string The category name
* @param mixed The key/value array
*
* @param array The new key/value array
*/
protected function getValues($prefix, $category, $keys)
{
if (!is_array($keys))
{
list($key, $value) = $this->fixCategoryValue($prefix.strtolower($category), '', $keys);
return array($key => $value);
}
$values = array();
$category = $this->fixCategoryName($category, $prefix);
// loop through all key/value pairs
foreach ($keys as $key => $value)
{
list($key, $value) = $this->fixCategoryValue($category, $key, $value);
$values[$key] = $value;
}
return $values;
}
/**
* Fixes the category name and replaces constants in the value.
*
* @param string The category name
* @param string The key name
* @param string The value
*
* @param string Return the new key and value
*/
protected function fixCategoryValue($category, $key, $value)
{
// prefix the key
$key = $category.$key;
// replace constant values
$value = $this->replaceConstants($value);
return array($key, $value);
}
/**
* Fixes the category name.
*
* @param string The category name
* @param string The prefix
*
* @return string The fixed category name
*/
protected function fixCategoryName($category, $prefix)
{
// categories starting without a period will be prepended to the key
if ($category[0] != '.')
{
$category = $prefix.$category.'_';
}
else
{
$category = $prefix;
}
return $category;
}
/**
* Merges default, all and current environment configurations.
*
* @param array The main configuratino array
*
* @param array The merged configuration
*/
protected function mergeEnvironment($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()
);
}
}

View File

@ -0,0 +1,162 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004-2006 Sean Kerr.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfFactoryConfigHandler allows you to specify which factory implementation the
* system will use.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfFactoryConfigHandler.class.php 3203 2007-01-09 18:32:54Z fabien $
*/
class sfFactoryConfigHandler extends sfYamlConfigHandler
{
/**
* 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
*/
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
$includes = array();
$inits = array();
$instances = array();
// available list of factories
$factories = array('controller', 'request', 'response', 'storage', 'user', 'view_cache');
// let's do our fancy work
foreach ($factories as $factory)
{
// see if the factory exists for this controller
$keys = $myConfig[$factory];
if (!isset($keys['class']))
{
// missing class key
$error = sprintf('Configuration file "%s" specifies category "%s" with missing class key', $configFiles[0], $factory);
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))
{
// factory 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');", $file);
}
// parse parameters
if (isset($keys['param']))
{
$parameters = array();
foreach ($keys['param'] as $key => $value)
{
$parameters[$key] = $this->replaceConstants($value);
}
}
else
{
$parameters = null;
}
$parameters = var_export($parameters, true);
// append new data
switch ($factory)
{
case 'controller':
// append instance creation
$instances[] = sprintf(" \$this->controller = sfController::newInstance(sfConfig::get('sf_factory_controller', '%s'));", $class);
// append instance initialization
$inits[] = " \$this->controller->initialize(\$this);";
break;
case 'request':
// append instance creation
$instances[] = sprintf(" \$this->request = sfRequest::newInstance(sfConfig::get('sf_factory_request', '%s'));", $class);
// append instance initialization
$inits[] = sprintf(" \$this->request->initialize(\$this, sfConfig::get('sf_factory_request_parameters', %s), sfConfig::get('sf_factory_request_attributes', array()));", $parameters);
break;
case 'response':
// append instance creation
$instances[] = sprintf(" \$this->response = sfResponse::newInstance(sfConfig::get('sf_factory_response', '%s'));", $class);
// append instance initialization
$inits[] = sprintf(" \$this->response->initialize(\$this, sfConfig::get('sf_factory_response_parameters', %s));", $parameters);
break;
case 'storage':
// append instance creation
$instances[] = sprintf(" \$this->storage = sfStorage::newInstance(sfConfig::get('sf_factory_storage', '%s'));", $class);
// append instance initialization
$inits[] = sprintf(" \$this->storage->initialize(\$this, sfConfig::get('sf_factory_storage_parameters', %s));", $parameters);
break;
case 'user':
// append instance creation
$instances[] = sprintf(" \$this->user = sfUser::newInstance(sfConfig::get('sf_factory_user', '%s'));", $class);
// append instance initialization
$inits[] = sprintf(" \$this->user->initialize(\$this, sfConfig::get('sf_factory_user_parameters', %s));", $parameters);
break;
case 'view_cache':
// append view cache class name
$inits[] = sprintf("\n if (sfConfig::get('sf_cache'))\n {\n".
" \$this->viewCacheManager = new sfViewCacheManager();\n".
" \$this->viewCacheManager->initialize(\$this, sfConfig::get('sf_factory_view_cache', '%s'), sfConfig::get('sf_factory_view_cache_parameters', %s));\n".
" }\n",
$class, $parameters);
break;
}
}
// compile data
$retval = sprintf("<?php\n".
"// auto-generated by sfFactoryConfigHandler\n".
"// date: %s\n%s\n%s\n%s\n",
date('Y/m/d H:i:s'), implode("\n", $includes),
implode("\n", $instances), implode("\n", $inits));
return $retval;
}
}

View File

@ -0,0 +1,206 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004-2006 Sean Kerr.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfFilterConfigHandler allows you to register filters with the system.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfFilterConfigHandler.class.php 3258 2007-01-13 12:12:22Z fabien $
*/
class sfFilterConfigHandler extends sfYamlConfigHandler
{
/**
* 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;
}
/**
* Adds a filter statement to the data.
*
* @param string The category name
* @param string The filter class name
* @param array Filter default parameters
*
* @return string The PHP statement
*/
protected function addFilter($category, $class, $parameters)
{
return sprintf("\nlist(\$class, \$parameters) = (array) sfConfig::get('sf_%s_filter', array('%s', %s));\n".
"\$filter = new \$class();\n".
"\$filter->initialize(\$this->context, \$parameters);\n".
"\$filterChain->register(\$filter);",
$category, $class, $parameters);
}
/**
* Adds a security filter statement to the data.
*
* @param string The category name
* @param string The filter class name
* @param array Filter default parameters
*
* @return string The PHP statement
*/
protected function addSecurityFilter($category, $class, $parameters)
{
return <<<EOF
// does this action require security?
if (\$actionInstance->isSecure())
{
if (!in_array('sfSecurityUser', class_implements(\$this->context->getUser())))
{
\$error = 'Security is enabled, but your sfUser implementation does not implement sfSecurityUser interface';
throw new sfSecurityException(\$error);
}
{$this->addFilter($category, $class, $parameters)}
}
EOF;
}
}

View File

@ -0,0 +1,82 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfGeneratorConfigHandler.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfGeneratorConfigHandler.class.php 3203 2007-01-09 18:32:54Z fabien $
*/
class sfGeneratorConfigHandler extends sfYamlConfigHandler
{
/**
* 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
* @throws sfInitializationException If a generator.yml key check fails
*/
public function execute($configFiles)
{
// parse the yaml
$config = $this->parseYamls($configFiles);
if (!$config)
{
return '';
}
if (!isset($config['generator']))
{
throw new sfParseException(sprintf('Configuration file "%s" must specify a generator section', $configFiles[1] ? $configFiles[1] : $configFiles[0]));
}
$config = $config['generator'];
if (!isset($config['class']))
{
throw new sfParseException(sprintf('Configuration file "%s" must specify a generator class section under the generator section', $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', $configFiles[1] ? $configFiles[1] : $configFiles[0], $section));
}
}
// generate class and add a reference to it
$generatorManager = new sfGeneratorManager();
$generatorManager->initialize();
// generator parameters
$generatorParam = (isset($config['param']) ? $config['param'] : array());
// hack to find the module name
preg_match('#'.sfConfig::get('sf_app_module_dir_name').'/([^/]+)/#', $configFiles[1], $match);
$generatorParam['moduleName'] = $match[1];
$data = $generatorManager->generate($config['class'], $generatorParam);
// compile data
$retval = "<?php\n".
"// auto-generated by sfGeneratorConfigHandler\n".
"// date: %s\n%s\n";
$retval = sprintf($retval, date('Y/m/d H:i:s'), $data);
return $retval;
}
}

View File

@ -0,0 +1,373 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfLoader is a class which contains the logic to look for files/classes in symfony.
*
* @package symfony
* @subpackage util
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfLoader.class.php 4277 2007-06-20 10:12:35Z fabien $
*/
class sfLoader
{
/**
* Gets directories where model classes are stored.
*
* @return array An array of directories
*/
static public function getModelDirs()
{
$dirs = array(sfConfig::get('sf_lib_dir').'/model' ? sfConfig::get('sf_lib_dir').'/model' : 'lib/model'); // project
if ($pluginDirs = glob(sfConfig::get('sf_plugins_dir').'/*/lib/model'))
{
$dirs = array_merge($dirs, $pluginDirs); // plugins
}
return $dirs;
}
/**
* Gets directories where controller classes are stored for a given module.
*
* @param string The module name
*
* @return array An array of directories
*/
static public function getControllerDirs($moduleName)
{
$suffix = $moduleName.'/'.sfConfig::get('sf_app_module_action_dir_name');
$dirs = array();
foreach (sfConfig::get('sf_module_dirs', array()) as $key => $value)
{
$dirs[$key.'/'.$suffix] = $value;
}
$dirs[sfConfig::get('sf_app_module_dir').'/'.$suffix] = false; // application
if ($pluginDirs = glob(sfConfig::get('sf_plugins_dir').'/*/modules/'.$suffix))
{
$dirs = array_merge($dirs, array_combine($pluginDirs, array_fill(0, count($pluginDirs), true))); // plugins
}
$dirs[sfConfig::get('sf_symfony_data_dir').'/modules/'.$suffix] = true; // core modules
return $dirs;
}
/**
* Gets directories where template files are stored for a given module.
*
* @param string The module name
*
* @return array An array of directories
*/
static public function getTemplateDirs($moduleName)
{
$suffix = $moduleName.'/'.sfConfig::get('sf_app_module_template_dir_name');
$dirs = array();
foreach (sfConfig::get('sf_module_dirs', array()) as $key => $value)
{
$dirs[] = $key.'/'.$suffix;
}
$dirs[] = sfConfig::get('sf_app_module_dir').'/'.$suffix; // application
if ($pluginDirs = glob(sfConfig::get('sf_plugins_dir').'/*/modules/'.$suffix))
{
$dirs = array_merge($dirs, $pluginDirs); // plugins
}
$dirs[] = sfConfig::get('sf_symfony_data_dir').'/modules/'.$suffix; // core modules
$dirs[] = sfConfig::get('sf_module_cache_dir').'/auto'.ucfirst($suffix); // generated templates in cache
return $dirs;
}
/**
* Gets the template directory to use for a given module and template file.
*
* @param string The module name
* @param string The template file
*
* @return string A template directory
*/
static public function getTemplateDir($moduleName, $templateFile)
{
$dirs = self::getTemplateDirs($moduleName);
foreach ($dirs as $dir)
{
if (is_readable($dir.'/'.$templateFile))
{
return $dir;
}
}
return null;
}
/**
* Gets the template to use for a given module and template file.
*
* @param string The module name
* @param string The template file
*
* @return string A template path
*/
static public function getTemplatePath($moduleName, $templateFile)
{
$dir = self::getTemplateDir($moduleName, $templateFile);
return $dir ? $dir.'/'.$templateFile : null;
}
/**
* Gets the i18n directory to use for a given module.
*
* @param string The module name
*
* @return string An i18n directory
*/
static public function getI18NDir($moduleName)
{
$suffix = $moduleName.'/'.sfConfig::get('sf_app_module_i18n_dir_name');
// application
$dir = sfConfig::get('sf_app_module_dir').'/'.$suffix;
if (is_dir($dir))
{
return $dir;
}
// plugins
$dirs = glob(sfConfig::get('sf_plugins_dir').'/*/modules/'.$suffix);
if (isset($dirs[0]))
{
return $dirs[0];
}
}
/**
* Gets directories where template files are stored for a generator class and a specific theme.
*
* @param string The generator class name
* @param string The theme name
*
* @return array An array of directories
*/
static public function getGeneratorTemplateDirs($class, $theme)
{
$dirs = array(sfConfig::get('sf_data_dir').'/generator/'.$class.'/'.$theme.'/template'); // project
if ($pluginDirs = glob(sfConfig::get('sf_plugins_dir').'/*/data/generator/'.$class.'/'.$theme.'/template'))
{
$dirs = array_merge($dirs, $pluginDirs); // plugin
}
$dirs[] = sfConfig::get('sf_symfony_data_dir').'/generator/'.$class.'/default/template'; // default theme
return $dirs;
}
/**
* Gets directories where the skeleton is stored for a generator class and a specific theme.
*
* @param string The generator class name
* @param string The theme name
*
* @return array An array of directories
*/
static public function getGeneratorSkeletonDirs($class, $theme)
{
$dirs = array(sfConfig::get('sf_data_dir').'/generator/'.$class.'/'.$theme.'/skeleton'); // project
if ($pluginDirs = glob(sfConfig::get('sf_plugins_dir').'/*/data/generator/'.$class.'/'.$theme.'/skeleton'))
{
$dirs = array_merge($dirs, $pluginDirs); // plugin
}
$dirs[] = sfConfig::get('sf_symfony_data_dir').'/generator/'.$class.'/default/skeleton'; // default theme
return $dirs;
}
/**
* Gets the template to use for a generator class.
*
* @param string The generator class name
* @param string The theme name
* @param string The template path
*
* @return string A template path
*
* @throws sfException
*/
static public function getGeneratorTemplate($class, $theme, $path)
{
$dirs = self::getGeneratorTemplateDirs($class, $theme);
foreach ($dirs as $dir)
{
if (is_readable($dir.'/'.$path))
{
return $dir.'/'.$path;
}
}
throw new sfException(sprintf('Unable to load "%s" generator template in: %s', $path, implode(', ', $dirs)));
}
/**
* Gets the configuration file paths for a given relative configuration path.
*
* @param string The configuration path
*
* @return array An array of paths
*/
static public function getConfigPaths($configPath)
{
$globalConfigPath = basename(dirname($configPath)).'/'.basename($configPath);
$files = array(
sfConfig::get('sf_symfony_data_dir').'/'.$globalConfigPath, // symfony
sfConfig::get('sf_symfony_data_dir').'/'.$configPath, // core modules
);
if ($pluginDirs = glob(sfConfig::get('sf_plugins_dir').'/*/'.$globalConfigPath))
{
$files = array_merge($files, $pluginDirs); // plugins
}
$files = array_merge($files, array(
sfConfig::get('sf_root_dir').'/'.$globalConfigPath, // project
sfConfig::get('sf_root_dir').'/'.$configPath, // project
sfConfig::get('sf_app_dir').'/'.$globalConfigPath, // application
sfConfig::get('sf_cache_dir').'/'.$configPath, // generated modules
));
if ($pluginDirs = glob(sfConfig::get('sf_plugins_dir').'/*/'.$configPath))
{
$files = array_merge($files, $pluginDirs); // plugins
}
$files[] = sfConfig::get('sf_app_dir').'/'.$configPath; // module
$configs = array();
foreach (array_unique($files) as $file)
{
if (is_readable($file))
{
$configs[] = $file;
}
}
return $configs;
}
/**
* Gets the helper directories for a given module name.
*
* @param string The module name
*
* @return array An array of directories
*/
static public function getHelperDirs($moduleName = '')
{
$dirs = array();
if ($moduleName)
{
$dirs[] = sfConfig::get('sf_app_module_dir').'/'.$moduleName.'/'.sfConfig::get('sf_app_module_lib_dir_name').'/helper'; // module
if ($pluginDirs = glob(sfConfig::get('sf_plugins_dir').'/*/modules/'.$moduleName.'/lib/helper'))
{
$dirs = array_merge($dirs, $pluginDirs); // module plugins
}
}
$dirs[] = sfConfig::get('sf_app_lib_dir').'/helper'; // application
$dirs[] = sfConfig::get('sf_lib_dir').'/helper'; // project
if ($pluginDirs = glob(sfConfig::get('sf_plugins_dir').'/*/lib/helper'))
{
$dirs = array_merge($dirs, $pluginDirs); // plugins
}
$dirs[] = sfConfig::get('sf_symfony_lib_dir').'/helper'; // global
return $dirs;
}
/**
* Loads helpers.
*
* @param array An array of helpers to load
* @param string A module name (optional)
*
* @throws sfViewException
*/
static public function loadHelpers($helpers, $moduleName = '')
{
static $loaded = array();
$dirs = self::getHelperDirs($moduleName);
foreach ((array) $helpers as $helperName)
{
if (isset($loaded[$helperName]))
{
continue;
}
$fileName = $helperName.'Helper.php';
foreach ($dirs as $dir)
{
$included = false;
if (is_readable($dir.'/'.$fileName))
{
include($dir.'/'.$fileName);
$included = true;
break;
}
}
if (!$included)
{
// search in the include path
if ((@include('helper/'.$fileName)) != 1)
{
$dirs = array_merge($dirs, explode(PATH_SEPARATOR, get_include_path()));
// remove sf_root_dir from dirs
foreach ($dirs as &$dir)
{
$dir = str_replace('%SF_ROOT_DIR%', sfConfig::get('sf_root_dir'), $dir);
}
throw new sfViewException(sprintf('Unable to load "%sHelper.php" helper in: %s', $helperName, implode(', ', $dirs)));
}
}
$loaded[$helperName] = true;
}
}
static public function loadPluginConfig()
{
if ($pluginConfigs = glob(sfConfig::get('sf_plugins_dir').'/*/config/config.php'))
{
foreach ($pluginConfigs as $config)
{
include($config);
}
}
}
}

View File

@ -0,0 +1,93 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfLoggingConfigHandler allows you to configure logging and register loggers with the system.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfLoggingConfigHandler.class.php 3258 2007-01-13 12:12:22Z fabien $
*/
class sfLoggingConfigHandler extends sfDefineEnvironmentConfigHandler
{
protected
$enabled = true,
$loggers = array();
/**
* 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
*/
public function execute($configFiles)
{
$data = parent::execute($configFiles);
if ($this->enabled)
{
$data .= "\n\$logger = sfLogger::getInstance();\n";
// log level
$data .= "\$logger->setLogLevel(constant('SF_LOG_'.strtoupper(sfConfig::get('sf_logging_level'))));\n";
// register loggers defined in the logging.yml configuration file
foreach ($this->loggers as $name => $keys)
{
if (isset($keys['enabled']) && !$keys['enabled'])
{
continue;
}
if (!isset($keys['class']))
{
// missing class key
throw new sfParseException(sprintf('Configuration file "%s" specifies filter "%s" with missing class key', $configFiles[0], $name));
}
$condition = true;
if (isset($keys['param']['condition']))
{
$condition = $this->replaceConstants($keys['param']['condition']);
unset($keys['param']['condition']);
}
if ($condition)
{
// parse parameters
$parameters = isset($keys['param']) ? var_export($keys['param'], true) : '';
// create logger instance
$data .= sprintf("\n\$log = new %s();\n\$log->initialize(%s);\n\$logger->registerLogger(\$log);\n", $keys['class'], $parameters);
}
}
}
return $data;
}
protected function getValues($prefix, $category, $keys)
{
if ('enabled' == $category)
{
$this->enabled = $this->replaceConstants($keys);
}
else if ('loggers' == $category)
{
$this->loggers = $this->replaceConstants($keys);
return array();
}
return parent::getValues($prefix, $category, $keys);
}
}

View File

@ -0,0 +1,154 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfPhpConfigHandler allows you to override php.ini configuration at runtime.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfPhpConfigHandler.class.php 3203 2007-01-09 18:32:54Z fabien $
*/
class sfPhpConfigHandler extends sfYamlConfigHandler
{
/**
* 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 php.yml key check fails
*/
public function execute($configFiles)
{
$this->initialize();
// parse the yaml
$config = $this->parseYamls($configFiles);
// init our data array
$data = array();
// get all php.ini configuration
$configs = ini_get_all();
// set some php.ini keys
if (isset($config['set']))
{
foreach ($config['set'] as $key => $value)
{
$key = strtolower($key);
// key exists?
if (!array_key_exists($key, $configs))
{
$error = sprintf('Configuration file "%s" specifies key "%s" which is not a php.ini directive', $configFiles[0], $key);
throw new sfParseException($error);
}
// key is overridable?
if ($configs[$key]['access'] != 7)
{
$error = sprintf('Configuration file "%s" specifies key "%s" which cannot be overrided', $configFiles[0], $key);
throw new sfParseException($error);
}
// escape value
$value = str_replace("'", "\\'", $value);
$data[] = sprintf("ini_set('%s', '%s');", $key, $value);
}
}
// check some php.ini settings
if (isset($config['check']))
{
foreach ($config['check'] as $key => $value)
{
$key = strtolower($key);
// key exists?
if (!array_key_exists($key, $configs))
{
$error = sprintf('Configuration file "%s" specifies key "%s" which is not a php.ini directive [err0002]', $configFiles[0], $key);
throw new sfParseException($error);
}
if (ini_get($key) != $value)
{
$error = sprintf('Configuration file "%s" specifies that php.ini "%s" key must be set to "%s". The current value is "%s" (%s). [err0001]', $configFiles[0], $key, var_export($value, true), var_export(ini_get($key), true), $this->get_ini_path());
throw new sfInitializationException($error);
}
}
}
// warn about some php.ini settings
if (isset($config['warn']))
{
foreach ($config['warn'] as $key => $value)
{
$key = strtolower($key);
// key exists?
if (!array_key_exists($key, $configs))
{
$error = sprintf('Configuration file "%s" specifies key "%s" which is not a php.ini directive [err0002]', $configFiles[0], $key);
throw new sfParseException($error);
}
$warning = sprintf('{sfPhpConfigHandler} php.ini "%s" key is better set to "%s" (current value is "%s" - %s)', $key, var_export($value, true), var_export(ini_get($key), true), $this->get_ini_path());
$data[] = sprintf("if (ini_get('%s') != %s)\n{\n sfLogger::getInstance()->warning('%s');\n}\n", $key, var_export($value, true), str_replace("'", "\\'", $warning));
}
}
// check for some extensions
if (isset($config['extensions']))
{
foreach ($config['extensions'] as $extension_name)
{
if (!extension_loaded($extension_name))
{
$error = sprintf('Configuration file "%s" specifies that the PHP extension "%s" should be loaded. (%s)', $configFiles[0], $extension_name, $this->get_ini_path());
throw new sfInitializationException($error);
}
}
}
// compile data
$retval = sprintf("<?php\n".
"// auto-generated by sfPhpConfigHandler\n".
"// date: %s\n%s\n", date('Y/m/d H:i:s'), implode("\n", $data));
return $retval;
}
/**
* Gets the php.ini path used by PHP.
*
* @return string the php.ini path
*/
protected function get_ini_path()
{
$cfg_path = get_cfg_var('cfg_file_path');
if ($cfg_path == '')
{
$ini_path = 'WARNING: system is not using a php.ini file';
}
else
{
$ini_path = sprintf('php.ini location: "%s"', $cfg_path);
}
return $ini_path;
}
}

View File

@ -0,0 +1,104 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfRootConfigHandler allows you to specify configuration handlers for the
* application or on a module level.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfRootConfigHandler.class.php 3203 2007-01-09 18:32:54Z fabien $
*/
class sfRootConfigHandler extends sfYamlConfigHandler
{
/**
* 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->parseYamls($configFiles);
// determine if we're loading the system config_handlers.yml or a module config_handlers.yml
$moduleLevel = ($this->getParameterHolder()->get('module_level') === true) ? true : false;
if ($moduleLevel)
{
// get the current module name
$moduleName = $this->getParameterHolder()->get('module_name');
}
// init our data and includes arrays
$data = array();
$includes = array();
// let's do our fancy work
foreach ($config as $category => $keys)
{
if ($moduleLevel)
{
// module-level registration, so we must prepend the module
// root to the category
$category = 'modules/'.$moduleName.'/'.$category;
}
if (!isset($keys['class']))
{
// missing class key
$error = sprintf('Configuration file "%s" specifies category "%s" with missing class key', $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))
{
// handler 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');", $file);
}
// parse parameters
$parameters = (isset($keys['param']) ? var_export($keys['param'], true) : null);
// append new data
$data[] = sprintf("\$this->handlers['%s'] = new %s();", $category, $class);
// initialize the handler with parameters
$data[] = sprintf("\$this->handlers['%s']->initialize(%s);", $category, $parameters);
}
// compile data
$retval = sprintf("<?php\n" .
"// auto-generated by sfRootConfigHandler\n".
"// date: %s\n%s\n%s\n",
date('Y/m/d H:i:s'), implode("\n", $includes), implode("\n", $data));
return $retval;
}
}

View File

@ -0,0 +1,54 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfRoutingConfigHandler.class.php 3203 2007-01-09 18:32:54Z fabien $
*/
class sfRoutingConfigHandler extends sfYamlConfigHandler
{
/**
* 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->parseYamls($configFiles);
// connect routes
$routes = sfRouting::getInstance();
foreach ($config as $name => $params)
{
$routes->connect(
$name,
($params['url'] ? $params['url'] : '/'),
(isset($params['param']) ? $params['param'] : array()),
(isset($params['requirements']) ? $params['requirements'] : array())
);
}
// compile data
$retval = sprintf("<?php\n".
"// auto-generated by sfRoutingConfigHandler\n".
"// date: %s\n\$routes = sfRouting::getInstance();\n\$routes->setRoutes(\n%s\n);\n",
date('Y/m/d H:i:s'), var_export($routes->getRoutes(), 1));
return $retval;
}
}

View File

@ -0,0 +1,55 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfSecurityConfigHandler allows you to configure action security.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfSecurityConfigHandler.class.php 3624 2007-03-17 10:57:03Z fabien $
*/
class sfSecurityConfigHandler extends sfYamlConfigHandler
{
/**
* 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;
}
}

View File

@ -0,0 +1,40 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfSimpleYamlConfigHandler allows you to load simple configuration files formatted as YAML.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfSimpleYamlConfigHandler.class.php 3203 2007-01-09 18:32:54Z fabien $
*/
class sfSimpleYamlConfigHandler extends sfYamlConfigHandler
{
/**
* 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
*/
public function execute($configFiles)
{
$config = $this->parseYamls($configFiles);
// compile data
$retval = "<?php\n".
"// auto-generated by %s\n".
"// date: %s\nreturn %s;\n";
$retval = sprintf($retval, __CLASS__, date('Y/m/d H:i:s'), var_export($config, true));
return $retval;
}
}

View File

@ -0,0 +1,555 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004-2006 Sean Kerr.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfValidatorConfigHandler allows you to register validators with the system.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfValidatorConfigHandler.class.php 3410 2007-02-06 08:11:38Z fabien $
*/
class sfValidatorConfigHandler extends sfYamlConfigHandler
{
/**
* 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->parseYamls($configFiles);
// alternate format?
if (isset($config['fields']))
{
$this->convertAlternate2Standard($config);
}
foreach (array('methods', 'names') as $category)
{
if (!isset($config[$category]))
{
throw new sfParseException(sprintf('Configuration file "%s" is missing "%s" category', $configFiles[0], $category));
}
}
// init our data, includes, methods, names and validators arrays
$data = array();
$includes = array();
$methods = array();
$names = array();
$validators = array();
// get a list of methods and their registered files/parameters
foreach ($config['methods'] as $method => $list)
{
$method = strtoupper($method);
if (!isset($methods[$method]))
{
// make sure that this method is GET or POST
if ($method != 'GET' && $method != 'POST')
{
// unsupported request method
$error = sprintf('Configuration file "%s" specifies unsupported request method "%s"', $configFiles[0], $method);
throw new sfParseException($error);
}
// create our method
$methods[$method] = array();
}
if (!count($list))
{
// we have an empty list of names
continue;
}
// load name list
$this->loadNames($configFiles, $method, $methods, $names, $config, $list);
}
// load attribute list
$this->loadAttributes($configFiles, $methods, $names, $validators, $config, $list);
// fill-in filter configuration
$fillin = var_export(isset($config['fillin']) ? $config['fillin'] : array(), true);
// generate GET file/parameter data
$data[] = "if (\$_SERVER['REQUEST_METHOD'] == 'GET')";
$data[] = "{";
$ret = $this->generateRegistration('GET', $data, $methods, $names, $validators);
if ($ret)
{
$data[] = sprintf(" \$context->getRequest()->setAttribute('fillin', %s, 'symfony/filter');", $fillin);
}
// generate POST file/parameter data
$data[] = "}";
$data[] = "else if (\$_SERVER['REQUEST_METHOD'] == 'POST')";
$data[] = "{";
$ret = $this->generateRegistration('POST', $data, $methods, $names, $validators);
if ($ret)
{
$data[] = sprintf(" \$context->getRequest()->setAttribute('fillin', %s, 'symfony/filter');", $fillin);
}
$data[] = "}";
// compile data
$retval = sprintf("<?php\n".
"// auto-generated by sfValidatorConfigHandler\n".
"// date: %s\n%s\n%s\n", date('Y/m/d H:i:s'),
implode("\n", $includes), implode("\n", $data));
return $retval;
}
/**
* Generates raw cache data.
*
* @param string A request method
* @param array The data array where our cache code will be appended
* @param array An associative array of request method data
* @param array An associative array of file/parameter data
* @param array A validators array
*
* @return boolean Returns true if there is some validators for this file/parameter
*/
protected function generateRegistration($method, &$data, &$methods, &$names, &$validators)
{
// setup validator array
$data[] = " \$validators = array();";
if (!isset($methods[$method]))
{
$methods[$method] = array();
}
// determine which validators we need to create for this request method
foreach ($methods[$method] as $name)
{
if (preg_match('/^([a-z0-9_-]+)\{([a-z0-9\s_-]+)\}$/i', $name, $match))
{
// this file/parameter has a parent
$subname = $match[2];
$parent = $match[1];
$valList = $names[$parent][$subname]['validators'];
}
else
{
// no parent
$valList = $names[$name]['validators'];
}
if ($valList == null)
{
// no validator list for this file/parameter
continue;
}
foreach ($valList as $valName)
{
if (isset($validators[$valName]) && !isset($validators[$valName][$method]))
{
// retrieve this validator's info
$validator =& $validators[$valName];
$data[] = sprintf(" \$validators['%s'] = new %s();\n".
" \$validators['%s']->initialize(%s, %s);",
$valName, $validator['class'], $valName, '$context', $validator['parameters']);
// mark this validator as created for this request method
$validators[$valName][$method] = true;
}
}
}
foreach ($methods[$method] as $name)
{
if (preg_match('/^([a-z0-9_-]+)\{([a-z0-9\s_-]+)\}$/i', $name, $match))
{
// this file/parameter has a parent
$subname = $match[2];
$parent = $match[1];
$name = $match[2];
$attributes = $names[$parent][$subname];
}
else
{
// no parent
$attributes = $names[$name];
}
// register file/parameter
$data[] = sprintf(" \$validatorManager->registerName('%s', %s, %s, %s, %s, %s);",
$name, $attributes['required'] ? 1 : 0,
isset($attributes['required_msg']) ? $attributes['required_msg'] : "''",
$attributes['parent'], $attributes['group'],
$attributes['file']);
// register validators for this file/parameter
foreach ($attributes['validators'] as &$validator)
{
$data[] = sprintf(" \$validatorManager->registerValidator('%s', %s, %s);", $name,
"\$validators['$validator']",
$attributes['parent']);
}
}
return count($methods[$method]) ? true : false;
}
/**
* Loads the linear list of attributes from the [names] category.
*
* @param string The configuration file name (for exception usage)
* @param array An associative array of request method data
* @param array An associative array of file/parameter names in which to store loaded information
* @param array An associative array of validator data
* @param array The loaded ini configuration that we'll use for verification purposes
* @param string A comma delimited list of file/parameter names
*/
protected function loadAttributes(&$configFiles, &$methods, &$names, &$validators, &$config, &$list)
{
foreach ($config['names'] as $name => $attributes)
{
// get a reference to the name entry
if (preg_match('/^([a-z0-9_-]+)\{([a-z0-9\s_-]+)\}$/i', $name, $match))
{
// this name entry has a parent
$subname = $match[2];
$parent = $match[1];
if (!isset($names[$parent][$subname]))
{
// unknown parent or subname
$error = sprintf('Configuration file "%s" specifies unregistered parent "%s" or subname "%s"', $configFiles[0], $parent, $subname);
throw new sfParseException($error);
}
$entry =& $names[$parent][$subname];
}
else
{
// no parent
if (!isset($names[$name]))
{
// unknown name
$error = sprintf('Configuration file "%s" specifies unregistered name "%s"', $configFiles[0], $name);
throw new sfParseException($error);
}
$entry =& $names[$name];
}
foreach ($attributes as $attribute => $value)
{
if ($attribute == 'validators')
{
// load validators for this file/parameter name
$this->loadValidators($configFiles, $validators, $config, $value, $entry);
}
else if ($attribute == 'type')
{
// name type
$lvalue = strtolower($value);
$entry['file'] = ($lvalue == 'file' ? 'true' : 'false');
}
else
{
// just a normal attribute
$entry[$attribute] = sfToolkit::literalize($value, true);
}
}
}
}
/**
* Loads all request methods and the file/parameter names that will be
* validated from the [methods] category.
*
* @param string The configuration file name (for exception usage)
* @param string A request method
* @param array An associative array of request method data
* @param array An associative array of file/parameter names in which to store loaded information
* @param array The loaded ini configuration that we'll use for verification purposes
* @param string A comma delimited list of file/parameter names
*/
protected function loadNames(&$configFiles, &$method, &$methods, &$names, &$config, &$list)
{
// explode the list of names
$array = $list;
// loop through the names
foreach ($array as $name)
{
// make sure we have the required status of this file or parameter
if (!isset($config['names'][$name]['required']))
{
// missing 'required' attribute
$error = sprintf('Configuration file "%s" specifies file or parameter "%s", but it is missing the "required" attribute', $configFiles[0], $name);
throw new sfParseException($error);
}
// determine parent status
if (preg_match('/^([a-z0-9_-]+)\{([a-z0-9\s_-]+)\}$/i', $name, $match))
{
// this name has a parent
$subname = $match[2];
$parent = $match[1];
if (!isset($names[$parent]) || !isset($names[$parent][$name]))
{
if (!isset($names[$parent]))
{
// create our parent
$names[$parent] = array('_is_parent' => true);
}
// create our new name entry
$entry = array();
$entry['file'] = 'false';
$entry['group'] = 'null';
$entry['parent'] = "'$parent'";
$entry['required'] = 'true';
$entry['required_msg'] = "'Required'";
$entry['validators'] = array();
// add our name entry
$names[$parent][$subname] = $entry;
}
}
else if (strpos($name, '{') !== false || strpos($name, '}') !== false)
{
// name contains an invalid character
// this is most likely a typo where the user forgot to add a brace
$error = sprintf('Configuration file "%s" specifies method "%s" with invalid file/parameter name "%s"', $configFiles[0], $method, $name);
throw new sfParseException($error);
}
else
{
// no parent
if (!isset($names[$name]))
{
// create our new name entry
$entry = array();
$entry['file'] = 'false';
$entry['group'] = 'null';
$entry['parent'] = 'null';
$entry['required'] = 'true';
$entry['required_msg'] = "'Required'";
$entry['type'] = 'parameter';
$entry['validators'] = array();
// add our name entry
$names[$name] = $entry;
}
}
// add this name to the current request method
$methods[$method][] = $name;
}
}
/**
* Loads a list of validators.
*
* @param string The configuration file name (for exception usage)
* @param array An associative array of validator data
* @param array The loaded ini configuration that we'll use for verification purposes
* @param string A comma delimited list of validator names
* @param array A file/parameter name entry
*/
protected function loadValidators(&$configFiles, &$validators, &$config, &$list, &$entry)
{
// create our empty entry validator array
$entry['validators'] = array();
if (!$list || (!is_array($list) && trim($list) == ''))
{
// skip the empty list
return;
}
// get our validator array
$array = is_array($list) ? $list : explode(',', $list);
foreach ($array as $validator)
{
$validator = trim($validator);
// add this validator name to our entry
$entry['validators'][] = $validator;
// make sure the specified validator exists
if (!isset($config[$validator]))
{
// validator hasn't been registered
$error = sprintf('Configuration file "%s" specifies unregistered validator "%s"', $configFiles[0], $validator);
throw new sfParseException($error);
}
// has it already been registered?
if (isset($validators[$validator]))
{
continue;
}
if (!isset($config[$validator]['class']))
{
// missing class key
$error = sprintf('Configuration file "%s" specifies category "%s" with missing class key', $configFiles[0], $validator);
throw new sfParseException($error);
}
// create our validator
$validators[$validator] = array();
$validators[$validator]['class'] = $config[$validator]['class'];
$validators[$validator]['file'] = null;
$validators[$validator]['parameters'] = null;
if (isset($config[$validator]['file']))
{
// we have a file for this validator
$file = $config[$validator]['file'];
// keyword replacement
$file = $this->replaceConstants($file);
$file = $this->replacePath($file);
if (!is_readable($file))
{
// file doesn't exist
$error = sprintf('Configuration file "%s" specifies category "%s" with nonexistent or unreadable file "%s"', $configFiles[0], $validator, $file);
throw new sfParseException($error);
}
$validators[$validator]['file'] = $file;
}
// parse parameters
$parameters = (isset($config[$validator]['param']) ? var_export($config[$validator]['param'], true) : 'null');
$validators[$validator]['parameters'] = $parameters;
}
}
/**
* Converts alternate format to standard format.
*
* @param array Configuration data
*/
protected function convertAlternate2Standard(&$config)
{
$defaultMethods = isset($config['methods']) ? $config['methods'] : array('post');
$config['methods'] = array();
// validators
if (isset($config['validators']))
{
foreach ((array) $config['validators'] as $validator => $params)
{
$config[$validator] = $params;
}
unset($config['validators']);
}
// names
$config['names'] = $config['fields'];
unset($config['fields']);
foreach ($config['names'] as $name => $values)
{
// validators
$validators = array();
foreach ($values as $validator => $params)
{
if (in_array($validator, array('required', 'group', 'group_msg', 'parent', 'file', 'methods')))
{
continue;
}
// class or validator
if (!isset($config[$validator]))
{
$config[$validator] = array('class' => $validator);
}
$validatorName = $validator;
if ($params)
{
// create a new validator
$validatorName = $validator.'_'.$name;
$config[$validatorName] = $config[$validator];
$config[$validatorName]['param'] = array_merge(isset($config[$validator]['param']) ? (array) $config[$validator]['param'] : array(), $params);
}
$validators[] = $validatorName;
unset($values[$validator]);
}
$values['validators'] = $validators;
// group
if (isset($values['group']) && isset($values['group_msg']))
{
$values['required_msg'] = $values['group_msg'];
}
// required
if (isset($values['required']))
{
$values['required_msg'] = $values['required']['msg'];
$values['required'] = true;
}
else
{
$values['required'] = false;
}
// methods
if (isset($values['methods']))
{
$methods = (array) $values['methods'];
unset($values['methods']);
}
else
{
$methods = $defaultMethods;
}
foreach ($methods as $method)
{
$config['methods'][$method][] = $name;
}
$config['names'][$name] = $values;
}
}
}

View File

@ -0,0 +1,343 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfViewConfigHandler allows you to configure views.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfViewConfigHandler.class.php 3289 2007-01-15 21:28:51Z fabien $
*/
class sfViewConfigHandler extends sfYamlConfigHandler
{
/**
* 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)
{
// set our required categories list and initialize our handler
$categories = array('required_categories' => array());
$this->initialize($categories);
// parse the yaml
$this->mergeConfig($this->parseYamls($configFiles));
// init our data array
$data = array();
$data[] = "\$context = \$this->getContext();\n";
$data[] = "\$response = \$context->getResponse();\n\n";
// first pass: iterate through all view names to determine the real view name
$first = true;
foreach ($this->yamlConfig as $viewName => $values)
{
if ($viewName == 'all')
{
continue;
}
$data[] = ($first ? '' : 'else ')."if (\$this->actionName.\$this->viewName == '$viewName')\n".
"{\n";
$data[] = $this->addTemplate($viewName);
$data[] = "}\n";
$first = false;
}
// general view configuration
$data[] = ($first ? '' : "else\n{")."\n";
$data[] = $this->addTemplate($viewName);
$data[] = ($first ? '' : "}")."\n\n";
// second pass: iterate through all real view names
$first = true;
foreach ($this->yamlConfig as $viewName => $values)
{
if ($viewName == 'all')
{
continue;
}
$data[] = ($first ? '' : 'else ')."if (\$templateName.\$this->viewName == '$viewName')\n".
"{\n";
$data[] = $this->addLayout($viewName);
$data[] = $this->addComponentSlots($viewName);
$data[] = $this->addHtmlHead($viewName);
$data[] = $this->addEscaping($viewName);
$data[] = $this->addHtmlAsset($viewName);
$data[] = "}\n";
$first = false;
}
// general view configuration
$data[] = ($first ? '' : "else\n{")."\n";
$data[] = $this->addLayout();
$data[] = $this->addComponentSlots();
$data[] = $this->addHtmlHead();
$data[] = $this->addEscaping();
$data[] = $this->addHtmlAsset();
$data[] = ($first ? '' : "}")."\n";
// compile data
$retval = sprintf("<?php\n".
"// auto-generated by sfViewConfigHandler\n".
"// date: %s\n%s\n",
date('Y/m/d H:i:s'), implode('', $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 a component slot statement to the data.
*
* @param string The view name
*
* @return string The PHP statement
*/
protected function addComponentSlots($viewName = '')
{
$data = '';
$components = $this->mergeConfigValue('components', $viewName);
foreach ($components as $name => $component)
{
if (!is_array($component) || count($component) < 1)
{
$component = array(null, null);
}
$data .= " \$this->setComponentSlot('$name', '{$component[0]}', '{$component[1]}');\n";
$data .= " if (sfConfig::get('sf_logging_enabled')) \$context->getLogger()->info('{sfViewConfig} set component \"$name\" ({$component[0]}/{$component[1]})');\n";
}
return $data;
}
/**
* Adds a template setting statement to the data.
*
* @param string The view name
*
* @return string The PHP statement
*/
protected function addTemplate($viewName = '')
{
$data = '';
$templateName = $this->getConfigValue('template', $viewName);
$defaultTemplateName = $templateName ? "'$templateName'" : '$this->actionName';
$data .= " \$templateName = \$response->getParameter(\$this->moduleName.'_'.\$this->actionName.'_template', $defaultTemplateName, 'symfony/action/view');\n";
$data .= " \$this->setTemplate(\$templateName.\$this->viewName.\$this->getExtension());\n";
return $data;
}
/**
* Adds a layour statement statement to the data.
*
* @param string The view name
*
* @return string The PHP statement
*/
protected function addLayout($viewName = '')
{
$data = '';
if ($this->getConfigValue('has_layout', $viewName) && false !== $layout = $this->getConfigValue('layout', $viewName))
{
$data = " \$this->setDecoratorTemplate('$layout'.\$this->getExtension());\n";
}
// For XMLHttpRequest, we want no layout by default
// So, we check if the user requested has_layout: true or if he gave a layout: name for this particular action
$localLayout = isset($this->yamlConfig[$viewName]['layout']) || isset($this->yamlConfig[$viewName]['has_layout']);
if (!$localLayout && $data)
{
$data = " if (!\$context->getRequest()->isXmlHttpRequest())\n {\n $data }\n";
}
return $data;
}
/**
* Adds http metas and metas statements to the data.
*
* @param string The view name
*
* @return string The PHP statement
*/
protected function addHtmlHead($viewName = '')
{
$data = array();
foreach ($this->mergeConfigValue('http_metas', $viewName) as $httpequiv => $content)
{
$data[] = sprintf(" \$response->addHttpMeta('%s', '%s', false);", $httpequiv, str_replace('\'', '\\\'', $content));
}
foreach ($this->mergeConfigValue('metas', $viewName) as $name => $content)
{
$data[] = sprintf(" \$response->addMeta('%s', '%s', false, false);", $name, str_replace('\'', '\\\'', preg_replace('/&amp;(?=\w+;)/', '&', htmlentities($content, ENT_QUOTES, sfConfig::get('sf_charset')))));
}
return implode("\n", $data)."\n";
}
/**
* Adds stylesheets and javascripts statements to the data.
*
* @param string The view name
*
* @return string The PHP statement
*/
protected function addHtmlAsset($viewName = '')
{
$data = array();
$omit = array();
$delete = array();
$delete_all = false;
// Merge the current view's stylesheets with the app's default stylesheets
$stylesheets = $this->mergeConfigValue('stylesheets', $viewName);
$tmp = array();
foreach ((array) $stylesheets as $css)
{
$position = '';
if (is_array($css))
{
$key = key($css);
$options = $css[$key];
if (isset($options['position']))
{
$position = $options['position'];
unset($options['position']);
}
}
else
{
$key = $css;
$options = array();
}
$key = $this->replaceConstants($key);
if ('-*' == $key)
{
$tmp = array();
}
else if ('-' == $key[0])
{
unset($tmp[substr($key, 1)]);
}
else
{
$tmp[$key] = sprintf(" \$response->addStylesheet('%s', '%s', %s);", $key, $position, str_replace("\n", '', var_export($options, true)));
}
}
$data = array_merge($data, array_values($tmp));
$omit = array();
$delete_all = false;
// Populate $javascripts with the values from ONLY the current view
$javascripts = $this->mergeConfigValue('javascripts', $viewName);
$tmp = array();
foreach ((array) $javascripts as $js)
{
$js = $this->replaceConstants($js);
if ('-*' == $js)
{
$tmp = array();
}
else if ('-' == $js[0])
{
unset($tmp[substr($js, 1)]);
}
else
{
$tmp[$js] = sprintf(" \$response->addJavascript('%s');", $js);
}
}
$data = array_merge($data, array_values($tmp));
return implode("\n", $data)."\n";
}
/**
* Adds an escaping statement to the data.
*
* @param string The view name
*
* @return string The PHP statement
*/
protected function addEscaping($viewName = '')
{
$data = array();
$escaping = $this->getConfigValue('escaping', $viewName);
if (isset($escaping['strategy']))
{
$data[] = sprintf(" \$this->setEscaping(%s);", var_export($escaping['strategy'], true));
}
if (isset($escaping['method']))
{
$data[] = sprintf(" \$this->setEscapingMethod(%s);", var_export($escaping['method'], true));
}
return implode("\n", $data)."\n";
}
}

View File

@ -0,0 +1,134 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfYamlConfigHandler is a base class for YAML (.yml) configuration handlers. This class
* provides a central location for parsing YAML files and detecting required categories.
*
* @package symfony
* @subpackage config
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfYamlConfigHandler.class.php 3203 2007-01-09 18:32:54Z fabien $
*/
abstract class sfYamlConfigHandler extends sfConfigHandler
{
protected
$yamlConfig = null;
/**
* 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;
}
/**
* Parses a YAML (.yml) configuration file.
*
* @param string An absolute filesystem path to a configuration file
*
* @return string A parsed .yml configuration
*
* @throws sfConfigurationException If a requested configuration file does not exist or is not readable
* @throws sfParseException If a requested configuration file is improperly formatted
*/
protected function parseYaml($configFile)
{
if (!is_readable($configFile))
{
// can't read the configuration
$error = sprintf('Configuration file "%s" does not exist or is not readable', $configFile);
throw new sfConfigurationException($error);
}
// parse our config
$config = sfYaml::load($configFile);
if ($config === false || $config === null)
{
// configuration couldn't be parsed
$error = sprintf('Configuration file "%s" could not be parsed', $configFile);
throw new sfParseException($error);
}
// get a list of the required categories
$categories = $this->getParameterHolder()->get('required_categories', array());
foreach ($categories as $category)
{
if (!isset($config[$category]))
{
$error = sprintf('Configuration file "%s" is missing "%s" category', $configFile, $category);
throw new sfParseException($error);
}
}
return $config;
}
/**
* Merges configuration values for a given key and category.
*
* @param string The key name
* @param string The category name
*
* @return string The value associated with this key name and category
*/
protected function mergeConfigValue($keyName, $category)
{
$values = array();
if (isset($this->yamlConfig['all'][$keyName]) && is_array($this->yamlConfig['all'][$keyName]))
{
$values = $this->yamlConfig['all'][$keyName];
}
if ($category && isset($this->yamlConfig[$category][$keyName]) && is_array($this->yamlConfig[$category][$keyName]))
{
$values = array_merge($values, $this->yamlConfig[$category][$keyName]);
}
return $values;
}
/**
* Gets a configuration value for a given key and category.
*
* @param string The key name
* @param string The category name
* @param string The default value
*
* @return string The value associated with this key name and category
*/
protected function getConfigValue($keyName, $category, $defaultValue = null)
{
if (isset($this->yamlConfig[$category][$keyName]))
{
return $this->yamlConfig[$category][$keyName];
}
else if (isset($this->yamlConfig['all'][$keyName]))
{
return $this->yamlConfig['all'][$keyName];
}
return $defaultValue;
}
}