forked from FriendsOfSymfony1/symfony1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsfConfigCache.class.php
354 lines (299 loc) · 12 KB
/
sfConfigCache.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004-2006 Sean Kerr <sean@code-box.org>
*
* 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.
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <sean@code-box.org>
*
* @version SVN: $Id$
*/
class sfConfigCache
{
protected $configuration;
protected $handlers = array();
protected $userHandlers = array();
/**
* Constructor.
*
* @param sfApplicationConfiguration $configuration A sfApplicationConfiguration instance
*/
public function __construct(sfApplicationConfiguration $configuration)
{
$this->configuration = $configuration;
}
/**
* 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 sfConfiguration::getConfigPaths() method.
*
* @param string $configPath A filesystem path to a configuration file
* @param bool $optional If true, config path does not need to exist
*
* @return string An absolute filesystem path to the cache filename associated with this specified configuration file
*
* @throws sfConfigurationException If a requested configuration file does not exist
*
* @see sfConfiguration::getConfigPaths()
*/
public function checkConfig($configPath, $optional = 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_debug') && !sfConfig::get('sf_test') && is_readable($cache)) {
return $cache;
}
if (!sfToolkit::isPathAbsolute($configPath)) {
$files = $this->configuration->getConfigPaths($configPath);
} else {
$files = is_readable($configPath) ? array($configPath) : array();
}
if (!isset($files[0])) {
if ($optional) {
return null;
}
// configuration does not exist
throw new sfConfigurationException(sprintf('Configuration "%s" does not exist or is unreadable.', $configPath));
}
// 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);
}
if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
// @var $timer sfTimer
$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 $config 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 $config A filesystem path to a configuration file
* @param bool $once Only allow this configuration file to be included once per request?
* @param bool $optional Only include if true
*
* @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;
}
}
/**
* Registers a configuration handler.
*
* @param string $handler The handler to use when parsing a configuration file
* @param class $class A configuration handler class
* @param string $params An array of options for the handler class initialization
*/
public function registerConfigHandler($handler, $class, $params = array())
{
$this->userHandlers[$handler] = new $class($params);
}
/**
* Loads a configuration handler.
*
* @param string $handler The handler to use when parsing a configuration file
* @param array $configs An array of absolute filesystem paths to configuration files
* @param string $cache An absolute filesystem path to the cache file that will be written
*
* @throws sfConfigurationException If a requested configuration file does not have an associated configuration handler
*/
protected function callHandler($handler, $configs, $cache)
{
if (0 == count($this->handlers)) {
// we need to load the handlers first
$this->loadConfigHandlers();
}
if (0 != count($this->userHandlers)) {
// we load user defined handlers
$this->mergeUserConfigHandlers();
}
// handler instance to call for this configuration file
$handlerInstance = 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
$handlerInstance = $this->getHandler($handler);
} elseif (isset($this->handlers[$basename])) {
// we have a handler associated with the configuration base name
$handlerInstance = $this->getHandler($basename);
} else {
// let's see if we have any wildcard handlers registered that match this basename
foreach (array_keys($this->handlers) as $key) {
// replace wildcard chars in the configuration
$pattern = strtr($key, array('.' => '\.', '*' => '(.*?)'));
$matches = array();
// create pattern from config
if (preg_match('#'.$pattern.'$#', $handler, $matches)) {
$handlerInstance = $this->getHandler($key);
array_shift($matches);
$handlerInstance->getParameterHolder()->set('wildcardValues', $matches);
break;
}
}
}
if (!$handlerInstance) {
// we do not have a registered handler for this file
throw new sfConfigurationException(sprintf('Configuration file "%s" does not have a registered handler.', implode(', ', $configs)));
}
// call the handler and retrieve the cache data
$data = $handlerInstance->execute($configs);
$this->writeCacheFile($handler, $cache, $data);
}
/**
* Returns the config handler configured for the given name.
*
* @param string $name The config handler name
*
* @return sfConfigHandler A sfConfigHandler instance
*/
protected function getHandler($name)
{
if (is_array($this->handlers[$name])) {
$class = $this->handlers[$name][0];
$this->handlers[$name] = new $class($this->handlers[$name][1]);
}
return $this->handlers[$name];
}
/**
* Loads all configuration application and module level handlers.
*
* @throws sfConfigurationException If a configuration related error occurs
*/
protected function loadConfigHandlers()
{
// manually create our config_handlers.yml handler
$this->handlers['config_handlers.yml'] = new sfRootConfigHandler();
// application configuration handlers
require $this->checkConfig('config/config_handlers.yml');
// module level configuration handlers
// checks modules directory exists
if (!is_readable($sf_app_module_dir = sfConfig::get('sf_app_module_dir'))) {
return;
}
// 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)) {
continue;
}
$configPath = $sf_app_module_dir.'/'.$directory.'/config/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 = 'modules/'.$directory.'/config/config_handlers.yml';
require $this->checkConfig($configPath);
}
}
// close file pointer
closedir($fp);
}
/**
* Writes a cache file.
*
* @param string $config An absolute filesystem path to a configuration file
* @param string $cache An absolute filesystem path to the cache file that will be written
* @param string $data Data to be written to the cache file
*
* @throws sfCacheException If the cache file cannot be written
*/
protected function writeCacheFile($config, $cache, $data)
{
$current_umask = umask(0000);
$cacheDir = dirname($cache);
if (!is_dir($cacheDir) && !@mkdir($cacheDir, 0777, true) && !is_dir($cacheDir)) {
throw new \sfCacheException(sprintf('Failed to make cache directory "%s" while generating cache for configuration file "%s".', $cacheDir, $config));
}
$tmpFile = tempnam($cacheDir, basename($cache));
if (!$fp = @fopen($tmpFile, 'wb')) {
throw new sfCacheException(sprintf('Failed to write cache file "%s" generated from configuration file "%s".', $tmpFile, $config));
}
@fwrite($fp, $data);
@fclose($fp);
// Hack from Agavi (http://trac.agavi.org/changeset/3979)
// With php < 5.2.6 on win32, renaming to an already existing file doesn't work, but copy does,
// so we simply assume that when rename() fails that we are on win32 and try to use copy()
if (!@rename($tmpFile, $cache)) {
if (copy($tmpFile, $cache)) {
unlink($tmpFile);
}
}
chmod($cache, 0666);
umask($current_umask);
}
/**
* Merges configuration handlers from the config_handlers.yml
* and the ones defined with registerConfigHandler().
*/
protected function mergeUserConfigHandlers()
{
// user defined configuration handlers
$this->handlers = array_merge($this->handlers, $this->userHandlers);
$this->userHandlers = array();
}
}