## Apache Zeta Components Manual :: File Source for file.php

## Source for file file.php

Documentation is available at file.php

1. <?php
2. /**
3. * File containing the ezcCacheStorageFile class.
4. *
5. * Licensed to the Apache Software Foundation (ASF) under one
6. * or more contributor license agreements. See the NOTICE file
7. * distributed with this work for additional information
8. * regarding copyright ownership. The ASF licenses this file
9. * to you under the Apache License, Version 2.0 (the
10. * "License"); you may not use this file except in compliance
11. * with the License. You may obtain a copy of the License at
12. *
13. * http://www.apache.org/licenses/LICENSE-2.0
14. *
15. * Unless required by applicable law or agreed to in writing,
16. * software distributed under the License is distributed on an
17. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
18. * KIND, either express or implied. See the License for the
19. * specific language governing permissions and limitations
20. * under the License.
21. *
22. * @package Cache
23. * @version //autogentag//
24. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
25. * @filesource
26. */
28. /**
29. * This class implements most of the methods which have been declared abstract
30. * in {@link ezcCacheStorage}, but also declares 2 new methods abstract, which
31. * have to be implemented by storage driver itself.
32. *
33. * This class is a common base class for all file system based storage classes.
34. * To implement a file system based cache storage, you simply have to derive
35. * from this class and implement the {@link ezcCacheStorageFile::fetchData()}
36. * and {@link ezcCacheStorageFile::prepareData()} methods. Everything else is
37. * done for you by the ezcCacheStorageFile base class.
38. *
39. * For example code of using a cache storage, see {@link ezcCacheManager}.
40. *
41. * The Cache package already contains several implementations of
42. * {@link ezcCacheStorageFile}. As there are:
43. *
44. * - ezcCacheStorageFileArray
45. * - ezcCacheStorageFileEvalArray
46. * - ezcCacheStorageFilePlain
47. *
48. * @package Cache
49. * @version //autogentag//
50. */
51. abstract class ezcCacheStorageFile extends ezcCacheStorage implements ezcCacheStackableStorage , ezcCacheStackMetaDataStorage
52. {
53. /**
54. * Resource used for the lock file.
55. *
56. * @var resource(file)
57. */
58. protected $lockResource = false;
60. /**
61. * Creates a new cache storage in the given location.
62. * Creates a new cache storage for a given location. The location in case
63. * of this storage class is a valid file system directory.
64. *
65. * Options can contain the 'ttl' ( Time-To-Life ). This is per default set
66. * to 1 day. The option 'permissions' can be used to define the file
67. * permissions of created cache items. Specific ezcCacheStorageFile
68. * implementations can have additional options.
69. *
70. * For details about the options see {@link ezcCacheStorageFileOptions}.
71. *
72. * @param string $location Path to the cache location
73. * @param array(string=>string) $options Options for the cache.
74. *
75. * @throws ezcBaseFileNotFoundException
76. * If the storage location does not exist. This should usually not
77. * happen, since {@link ezcCacheManager::createCache()} already
78. * performs sanity checks for the cache location. In case this
79. * exception is thrown, your cache location has been corrupted
80. * after the cache was configured.
81. * @throws ezcBaseFileNotFoundException
82. * If the storage location is not a directory. This should usually
83. * not happen, since {@link ezcCacheManager::createCache()} already
84. * performs sanity checks for the cache location. In case this
85. * exception is thrown, your cache location has been corrupted
86. * after the cache was configured.
87. * @throws ezcBaseFilePermissionException
88. * If the storage location is not writeable. This should usually not
89. * happen, since {@link ezcCacheManager::createCache()} already
90. * performs sanity checks for the cache location. In case this
91. * exception is thrown, your cache location has been corrupted
92. * after the cache was configured.
93. * @throws ezcBasePropertyNotFoundException
94. * If you tried to set a non-existent option value. The accepted
95. * options depend on the ezcCacheStorage implementation and may
96. * vary.
97. */
98. public function __construct ( $location, $options = array() )
99. {
100. // Sanity check location
101. if ( ! file_exists ( $location ) || ! is_dir ( $location ) )
102. {
103. throw new ezcBaseFileNotFoundException (
104. $location,
105. 'cache location',
106. 'Does not exist or is no directory.'
107. );
108. }
109. if ( ! is_readable ( $location ) )
110. {
111. throw new ezcBaseFilePermissionException (
112. $location,
113. ezcBaseFileException ::READ,
114. 'Cache location is not readable.'
115. );
116. }
117. if ( ! is_writeable ( $location ) )
118. {
119. throw new ezcBaseFilePermissionException (
120. $location,
121. ezcBaseFileException ::WRITE,
122. 'Cache location is not writeable.'
123. );
124. }
126. parent:: __construct ( $location );
127. // Overwrite parent set options with new ezcCacheFileStorageOptions
128. $this-> properties ['options'] = new ezcCacheStorageFileOptions ( $options );
129. }
130. /**
131. * Fetch data from the cache.
132. * This method does the fetching of the data itself. In this case, the
133. * method simply includes the file and returns the value returned by the
134. * include ( or false on failure ).
135. *
136. * @param string $filename The file to fetch data from.
137. * @return mixed The fetched data or false on failure.
138. */
139. abstract protected function fetchData ( $filename );
141. /**
142. * Serialize the data for storing.
143. * Serializes a PHP variable ( except type resource and object ) to a
144. * executable PHP code representation string.
145. *
146. * @param mixed $data Simple type or array
147. * @return string The serialized data
148. *
149. * @throws ezcCacheInvalidDataException
150. * If the data submitted can not be handled by the implementation
151. * of {@link ezcCacheStorageFile}. Most implementations can not
152. * handle objects and resources.
153. */
154. abstract protected function prepareData ( $data );
156. /**
157. * Store data to the cache storage.
158. * This method stores the given cache data into the cache, assigning the
159. * ID given to it.
160. *
161. * The type of cache data which is expected by a ezcCacheStorage depends on
162. * its implementation. In most cases strings and arrays will be accepted,
163. * in some rare cases only strings might be accepted.
164. *
165. * Using attributes you can describe your cache data further. This allows
166. * you to deal with multiple cache data at once later. Some ezcCacheStorage
167. * implementations also use the attributes for storage purposes. Attributes
168. * form some kind of "extended ID".
169. *
170. * @param string $id Unique identifier for the data.
171. * @param mixed $data The data to store.
172. * @param array(string=>string) $attributes Attributes describing the
173. * cached data.
174. *
175. * @return string The ID string of the newly cached data.
176. *
177. * @throws ezcBaseFilePermissionException
178. * If an already existsing cache file could not be unlinked to
179. * store the new data (may occur, when a cache item's TTL
180. * has expired and the file should be stored with more actual
181. * data). This exception means most likely that your cache directory
182. * has been corrupted by external influences (file permission
183. * change).
184. * @throws ezcBaseFilePermissionException
185. * If the directory to store the cache file could not be created.
186. * This exception means most likely that your cache directory
187. * has been corrupted by external influences (file permission
188. * change).
189. * @throws ezcBaseFileIoException
190. * If an error occured while writing the data to the cache. If this
191. * exception occurs, a serious error occured and your storage might
192. * be corruped (e.g. broken network connection, file system broken,
193. * ...).
194. * @throws ezcCacheInvalidDataException
195. * If the data submitted can not be handled by the implementation
196. * of {@link ezcCacheStorageFile}. Most implementations can not
197. * handle objects and resources.
198. */
199. public function store ( $id, $data, $attributes = array() )
200. {
201. $filename = $this-> properties ['location']
202. . $this-> generateIdentifier ( $id, $attributes );
203. if ( file_exists ( $filename ) )
204. {
205. if ( unlink ( $filename ) === false )
206. {
207. throw new ezcBaseFilePermissionException (
208. $filename,
209. ezcBaseFileException ::WRITE,
210. 'Could not delete existsing cache file.'
211. );
212. }
213. }
214. $dataStr = $this-> prepareData ( $data );
215. $dirname = dirname ( $filename );
216. if ( ! is_dir ( $dirname ) && ! mkdir ( $dirname, 0777, true ) )
217. {
218. throw new ezcBaseFilePermissionException (
219. $dirname,
220. ezcBaseFileException ::WRITE,
221. 'Could not create directory to stor cache file.'
222. );
223. }
225. $this-> storeRawData ( $filename, $dataStr );
227. if ( ezcBaseFeatures :: os () !== "Windows" )
228. {
229. chmod ( $filename, $this->options->permissions );
230. }
231. return $id;
232. }
234. /**
235. * Actually stores the given data.
236. *
237. * @param string $filename
238. * @param string $data
239. * @return void
240. *
241. * @throws ezcBaseFileIoException
242. * if the store fails.
243. */
244. protected function storeRawData ( $filename, $data )
245. {
246. if ( file_put_contents ( $filename, $data ) !== strlen ( $data ) )
247. {
248. throw new ezcBaseFileIoException (
249. $filename,
250. ezcBaseFileException ::WRITE,
251. 'Could not write data to cache file.'
252. );
253. }
254. }
256. /**
257. * Restore data from the cache.
258. * Restores the data associated with the given cache and
259. * returns it. Please see {@link ezcCacheStorage::store()}
260. * for more detailed information of cachable datatypes.
261. *
262. * During access to cached data the caches are automatically
263. * expired. This means, that the ezcCacheStorage object checks
264. * before returning the data if it's still actual. If the cache
265. * has expired, data will be deleted and false is returned.
266. *
267. * You should always provide the attributes you assigned, although
268. * the cache storages must be able to find a cache ID even without
269. * them. BEWARE: Finding cache data only by ID can be much
270. * slower than finding it by ID and attributes.
271. *
272. * Note that with the {@link ezcCacheStorageFilePlain} all restored data
273. * will be of type string. If you expect a different data type you need to
274. * perform a cast after restoring.
275. *
276. * @param string $id The item ID to restore.
277. * @param array(string=>string) $attributes Attributes describing the
278. * data to restore.
279. * @param bool $search Whether to search for items
280. * if not found directly.
281. *
282. * @return mixed|boolThe cached data on success, otherwise false.
283. *
284. * @throws ezcBaseFilePermissionException
285. * If an already existsing cache file could not be unlinked.
286. * This exception means most likely that your cache directory
287. * has been corrupted by external influences (file permission
288. * change).
289. */
290. public function restore ( $id, $attributes = array(), $search = false )
291. {
292. $filename = $this-> properties ['location']
293. . $this-> generateIdentifier ( $id, $attributes );
294. if ( file_exists ( $filename ) === false )
295. {
296. if ( $search === true
297. && count ( $files = $this-> search ( $id, $attributes ) ) === 1 )
298. {
299. $filename = $files[0];
300. }
301. else
302. {
303. return false;
304. }
305. }
306. // No cached data
307. if ( file_exists ( $filename ) === false )
308. {
309. return false;
310. }
311. // Cached data outdated, purge it.
312. if ( $this-> calcLifetime ( $filename ) == 0
313. && $this-> properties ['options']['ttl'] !== false )
314. {
315. $this-> delete ( $id, $attributes );
316. return false;
317. }
318. return ( $this-> fetchData ( $filename ) );
319. }
321. /**
322. * Delete data from the cache.
323. * Purges the cached data for a given ID and or attributes. Using an ID
324. * purges only the cache data for just this ID.
325. *
326. * Additional attributes provided will matched additionally. This can give
327. * you an immense speed improvement against just searching for ID ( see
328. * {@link ezcCacheStorage::restore()} ).
329. *
330. * If you only provide attributes for deletion of cache data, all cache
331. * data matching these attributes will be purged.
332. *
333. * @param string $id The item ID to purge.
334. * @param array(string=>string) $attributes Attributes describing the
335. * data to restore.
336. * @param bool $search Whether to search for items
337. * if not found directly.
338. * @return void
339. *
340. * @throws ezcBaseFilePermissionException
341. * If an already existsing cache file could not be unlinked.
342. * This exception means most likely that your cache directory
343. * has been corrupted by external influences (file permission
344. * change).
345. */
346. public function delete ( $id = null, $attributes = array(), $search = false )
347. {
348. $filename = $this-> properties ['location']
349. . $this-> generateIdentifier ( $id, $attributes );
351. $filesToDelete = array();
352. if ( file_exists ( $filename ) )
353. {
354. $filesToDelete[] = $filename;
355. }
356. else if ( $search === true )
357. {
358. $filesToDelete = $this-> search ( $id, $attributes );
359. }
361. $deletedIds = array();
362. foreach ( $filesToDelete as $filename )
363. {
364. if ( unlink ( $filename ) === false )
365. {
366. throw new ezcBaseFilePermissionException (
367. $filename,
368. ezcBaseFileException ::WRITE,
369. 'Could not unlink cache file.'
370. );
371. }
372. $deleted = $this->extractIdentifier( $filename );
373. $deletedIds[] = $deleted['id'];
374. }
375. return $deletedIds;
376. }
378. /**
379. * Return the number of items in the cache matching a certain criteria.
380. * This method determines if cache data described by the given ID and/or
381. * attributes exists. It returns the number of cache data items found.
382. *
383. * @param string $id The item ID.
384. * @param array(string=>string) $attributes Attributes describing the
385. * data to restore.
386. * @return int Number of data items matching the criteria.
387. */
388. public function countDataItems ( $id = null, $attributes = array() )
389. {
390. return count ( $this-> search ( $id, $attributes ) );
391. }
393. /**
394. * Returns the time ( in seconds ) which remains for a cache object,
395. * before it gets outdated. In case the cache object is already
396. * outdated or does not exist, this method returns 0.
397. *
398. * @param string $id The item ID.
399. * @param array(string=>string) $attributes Attributes describing the
400. * data to restore.
401. * @access public
402. * @return int The remaining lifetime (0 if nonexists or oudated).
403. */
404. public function getRemainingLifetime ( $id, $attributes = array() )
405. {
406. if ( count ( $objects = $this-> search ( $id, $attributes ) ) > 0 )
407. {
408. return $this-> calcLifetime ( $objects[0] );
409. }
410. return 0;
411. }
413. /**
414. * Purges the given number of cache items.
415. *
416. * This method minimally purges the $limit number of outdated cache items
417. * from the storage. If limit is left out, all outdated items are purged.
418. * The purged item IDs are returned.
419. *
420. * @param int $limit
421. * @return array(string)
422. */
423. public function purge ( $limit = null )
424. {
425. $purgeCount = 0;
426. return $this->purgeRecursive( $this-> properties ['location'], $limit, $purgeCount );
427. }
429. /**
430. * Recursively purge cache items.
431. *
432. * Recursively purges $dir until $limit is reached. $purgeCount is the
433. * number of already purged items.
434. *
435. * @param string $dir
436. * @param int $limit
437. * @param int $purgeCount
438. */
439. private function purgeRecursive( $dir, $limit, &$purgeCount )
440. {
441. $purgedIds = array();
443. // Deal with files in the directory
444. if ( ( $files = glob ( "{$dir}*{$this-> properties ['options']->extension}" ) ) === false )
445. {
446. throw new ezcBaseFileNotFoundException (
447. $dir,
448. 'cache location',
449. 'Produced an error while globbing for files.'
450. );
451. }
453. foreach ( $files as $file )
454. {
455. if ( $this-> calcLifetime ( $file ) == 0 )
456. {
457. if ( @ unlink ( $file ) === false )
458. {
459. throw new ezcBaseFilePermissionException (
460. $file,
461. ezcBaseFileException ::WRITE,
462. 'Could not unlink cache file.'
463. );
464. }
465. $fileInfo = $this->extractIdentifier( $file );
466. $purgedIds[] = $fileInfo['id'];
467. ++$purgeCount;
468. }
469. // Stop purging if limit is reached
470. if ( $limit !== null && $purgeCount >= $limit )
471. {
472. return $purgedIds;
473. }
474. }
476. // Deal with sub dirs, this function expects them to be marked with a
477. // slash because of the property $location
478. if ( ( $dirs = glob ( "$dir*", GLOB_ONLYDIR | GLOB_MARK ) ) === false )
479. {
480. throw new ezcBaseFileNotFoundException (
481. $dir,
482. 'cache location',
483. 'Produced an error while globbing for directories.'
484. );
485. }
486. foreach ( $dirs as $dir )
487. {
488. $purgedIds = array_merge (
489. $purgedIds,
490. $this->purgeRecursive( $dir, $limit, $purgeCount )
491. );
492. // Stop purging if limit is reached
493. if ( $limit !== null && $purgeCount >= $limit )
494. {
495. return $purgedIds;
496. }
497. }
499. // Finished purging, return IDs.
500. return $purgedIds;
501. }
503. /**
504. * Resets the whole storage.
505. *
506. * Deletes all data in the storage including {@link ezcCacheStackMetaData}
507. * that was stored using {@link storeMetaData()}.
508. */
509. public function reset ()
510. {
511. $files = glob ( "{$this-> properties ['location']}*

" );
- foreach ( $files as $file )
- {
- if ( is_dir ( $file ) )
- {
- ezcBaseFile :: removeRecursive ( $file );
- }
- else
- {
- if ( @ unlink ( $file ) === false )
- {
- throw new ezcBaseFilePermissionException (
- $file,
- ezcBaseFileException ::REMOVE,
- 'Could not unlink cache file.'
- );
- }
- }
- }
- }
- /**
- * Search the storage for data.
- *
- * @param string $id An item ID.
- * @param array(string=>string) $attributes Attributes describing the
- * data to restore.
- * @return array(int=>string) Found cache items.
- */
- protected function search ( $id = null, $attributes = array() )
- {
- $globArr = explode ( "-", $this-> generateIdentifier ( $id, $attributes ), 2 );
- if ( sizeof ( $globArr ) > 1 )
- {
- $glob = $globArr[0] . "-" . strtr ( $globArr[1], array( '-' => '*', '.' => '*' ) );
- }
- else
- {
- $glob = strtr ( $globArr[0], array( '-' => '*', '.' => '*' ) );
- }
- $glob = ( $id === null ? '*' : '' ) . $glob;
- return $this-> searchRecursive ( $glob, $this-> properties ['location'] );
- }
- /**
- * Search the storage for data recursively.
- *
- * @param string $pattern Pattern used with {@link glob()}.
- * @param mixed $directory Directory to search in.
- * @return array(int=>string) Found cache items.
- */
- protected function searchRecursive ( $pattern, $directory )
- {
- $itemArr = glob ( $directory . $pattern );
- $dirArr = glob ( $directory . "*", GLOB_ONLYDIR );
- foreach ( $dirArr as $dirEntry )
- {
- $result = $this-> searchRecursive ( $pattern, "$dirEntry/" );
- $itemArr = array_merge ( $itemArr, $result );
- }
- return $itemArr;
- }
- /**
- * Checks the path in the location property exists, and is read-/writable. It
- * throws an exception if not.
- *
- * @throws ezcBaseFileNotFoundException
- * If the storage location does not exist. This should usually not
- * happen, since {@link ezcCacheManager::createCache()} already
- * performs sanity checks for the cache location. In case this
- * exception is thrown, your cache location has been corrupted
- * after the cache was configured.
- * @throws ezcBaseFileNotFoundException
- * If the storage location is not a directory. This should usually
- * not happen, since {@link ezcCacheManager::createCache()} already
- * performs sanity checks for the cache location. In case this
- * exception is thrown, your cache location has been corrupted
- * after the cache was configured.
- * @throws ezcBaseFilePermissionException
- * If the storage location is not writeable. This should usually not
- * happen, since {@link ezcCacheManager::createCache()} already
- * performs sanity checks for the cache location. In case this
- * exception is thrown, your cache location has been corrupted
- * after the cache was configured.
- */
- protected function validateLocation ()
- {
- if ( file_exists ( $this-> properties ['location'] ) === false )
- {
- throw new ezcBaseFileNotFoundException (
- $this-> properties ['location'],
- 'cache location'
- );
- }
- if ( is_dir ( $this-> properties ['location'] ) === false )
- {
- throw new ezcBaseFileNotFoundException (
- $this-> properties ['location'],
- 'cache location',
- 'Cache location not a directory.'
- );
- }
- if ( is_writeable ( $this-> properties ['location'] ) === false )
- {
- throw new ezcBaseFilePermissionException (
- $this-> properties ['location'],
- ezcBaseFileException ::WRITE,
- 'Cache location is not a directory.'
- );
- }
- }
- /**
- * Generate the storage internal identifier from ID and attributes.
- *
- * Generates the storage internal identifier out of the provided ID and the
- * attributes. This is the default implementation and can be overloaded if
- * necessary.
- *
- * @param string $id The ID.
- * @param array(string=>string) $attributes Attributes describing the
- * data to restore.
- * @return string The generated identifier
- */
- public function generateIdentifier ( $id, $attributes = null )
- {
- $filename = (string) $id;
- $illegalFileNameChars = array(
- ' ' => '_',
- '/' => DIRECTORY_SEPARATOR,
- '\\' => DIRECTORY_SEPARATOR,
- );
- $filename = strtr ( $filename, $illegalFileNameChars );
- // Chars used for filename concatination
- $illegalChars = array(
- '-' => '#',
- ' ' => '%',
- '=' => '+',
- '.' => '+',
- );
- if ( is_array ( $attributes ) && count ( $attributes ) > 0 )
- {
- ksort ( $attributes );
- foreach ( $attributes as $key => $val )
- {
- $attrStr = '-' . strtr ( $key, $illegalChars )
- . '=' . strtr ( $val, $illegalChars );
- if ( strlen ( $filename . $attrStr ) > 250 )
- {
- // Max filename length
- break;
- }
- $filename .= $attrStr;
- }
- }
- else
- {
- $filename .= '-';
- }
- return $filename . $this-> properties ['options']['extension'];
- }
- /**
- * Restores and returns the meta data struct.
- *
- * This method fetches the meta data stored in the storage and returns the
- * according struct of type {@link ezcCacheStackMetaData}. The meta data
- * must be stored inside the storage, but should not be visible as normal
- * cache items to the user.
- *
- * @return ezcCacheStackMetaData|null
- */
- public function restoreMetaData ()
- {
- // Silence require warnings. It's ok that meta data does not exist.
- $dataArr = @$this-> fetchData (
- $this-> properties ['location'] . $this-> properties ['options']->metaDataFile
- );
- $result = null;
- if ( $dataArr !== false )
- {
- $result = new $dataArr['class']();
- $result->setState( $dataArr['data'] );
- }
- return $result;
- }
- /**
- * Stores the given meta data struct.
- *
- * This method stores the given $metaData inside the storage. The data must
- * be stored with the same mechanism that the storage itself uses. However,
- * it should not be stored as a normal cache item, if possible, to avoid
- * accedental user manipulation.
- *
- * @param ezcCacheStackMetaData $metaData
- * @return void
- */
- public function storeMetaData ( ezcCacheStackMetaData $metaData )
- {
- $dataArr = array(
- 'class' => get_class ( $metaData ),
- 'data' => $metaData->getState(),
- );
- $this-> storeRawData (
- $this-> properties ['location'] . $this-> properties ['options']->metaDataFile,
- $this-> prepareData ( $dataArr )
- );
- }
- /**
- * Acquire a lock on the storage.
- *
- * This method acquires a lock on the storage. If locked, the storage must
- * block all other method calls until the lock is freed again using {@link }
- * ezcCacheStackMetaDataStorage::unlock()}. Methods that are called within
- * the request that successfully acquired the lock must succeed as usual.
- *
- * @return void
- */
- public function lock ()
- {
- $lockFile = $this-> properties ['location'] . $this-> properties ['options']->lockFile;
- while ( $this-> lockResource === false )
- {
- clearstatcache ();
- $this-> lockResource = @ fopen ( $lockFile, 'x' );
- // Wait for lock to get freed
- if ( $this-> lockResource === false )
- {
- usleep ( $this-> properties ['options']->lockWaitTime );
- }
- // Check if lock is to be considered dead. Might result in a
- // nonrelevant race condition if the lock file disappears between
- // fs calls. To avoid warnings in this case, the calls are
- // silenced.
- if ( file_exists ( $lockFile ) && ( time () - @ filemtime ( $lockFile ) ) > $this-> properties ['options']->maxLockTime )
- {
- @ unlink ( $lockFile );
- }
- }
- }
- /**
- * Release a lock on the storage.
- *
- * This method releases the lock of the storage, that has been acquired via
- * {@link ezcCacheStackMetaDataStorage::lock()}. After this method has been
- * called, blocked method calls (including calls to lock()) can suceed
- * again.
- *
- * @return void
- */
- public function unlock ()
- {
- // If the resource is already removed, nothing to do
- if ( $this-> lockResource !== false )
- {
- fclose ( $this-> lockResource );
- @ unlink (
- $this-> properties ['location'] . $this-> properties ['options']->lockFile
- );
- $this-> lockResource = false;
- }
- }
- /**
- * Set new options.
- * This method allows you to change the options of a cache file storage. Change
- * of options take effect directly after this method has been called. The
- * available options depend on the ezcCacheStorageFile implementation. All
- * implementations have to offer the following options:
- *
- * - ttl The time-to-life. After this time span, a cache item becomes
- * invalid and will be purged. The
- * {@link ezcCacheStorage::restore()} method will then return
- * false.
- * - extension The "extension" for your cache items. This is usually the
- * file name extension, when you deal with file system based
- * caches or e.g. a database ID extension.
- * - permissions The file permissions to set for new files.
- *
- * The usage of ezcCacheStorageOptions and arrays for setting options is
- * deprecated, but still supported. You should migrate to
- * ezcCacheStorageFileOptions.
- *
- * @param ezcCacheStorageFileOptions $options The options to set (accepts
- * ezcCacheStorageOptions or
- * array for compatibility
- * reasons, too).
- *
- * @throws ezcBasePropertyNotFoundException
- * If you tried to set a non-existent option value. The accepted
- * options depend on the ezcCacheStorage implementation and may
- * vary.
- * @throws ezcBaseValueException
- * If the value is not valid for the desired option.
- * @throws ezcBaseValueException
- * If you submit neither an instance of ezcCacheStorageFileOptions,
- * nor an instance of ezcCacheStorageOptions nor an array.
- */
- public function setOptions ( $options )
- {
- if ( is_array ( $options ) )
- {
- $this-> properties ['options']->merge( $options );
- }
- else if ( $options instanceof ezcCacheStorageFileOptions )
- {
- $this-> properties ['options'] = $options;
- }
- else if ( $options instanceof ezcCacheStorageOptions )
- {
- $this-> properties ['options']->mergeStorageOptions( $options );
- }
- else
- {
- throw new ezcBaseValueException (
- 'options',
- $options,
- 'instance of ezcCacheStorageFileOptions or (deprecated) ezcCacheStorageOptions'
- );
- }
- }
- /**
- * Property write access.
- *
- * @param string $propertyName Name of the property.
- * @param mixed $val The value for the property.
- *
- * @throws ezcBaseValueException
- * If the value for the property options is not an instance of
- * ezcCacheStorageOptions.
- * @ignore
- */
- public function __set( $propertyName, $val )
- {
- switch ( $propertyName )
- {
- case 'options':
- if ( $val instanceof ezcCacheStorageFileOptions )
- {
- $this-> properties ['options'] = $val;
- return;
- }
- if ( $val instanceof ezcCacheStorageOptions )
- {
- $this-> properties ['options']->mergeStorageOptions( $val );
- return;
- }
- throw new ezcBaseValueException (
- $propertyName,
- $val,
- 'instance of ezcCacheStorageFileOptions'
- );
- }
- throw new ezcBasePropertyNotFoundException ( $propertyName );
- }
- /**
- * Calculates the lifetime remaining for a cache object.
- *
- * This calculates the time a cached object stays valid and returns it. In
- * case the TTL is set to false, this method always returns a value of 1.
- *
- * @param string $file The file to calculate the remaining lifetime for.
- * @return int The remaining lifetime in seconds (0 if no time remaining).
- */
- protected function calcLifetime ( $file )
- {
- $ttl = $this->options->ttl;
- if ( file_exists ( $file ) && ( $modTime = filemtime ( $file ) ) !== false )
- {
- if ( $ttl === false )
- {
- return 1;
- }
- return (
- ( $lifeTime = time () - $modTime ) < $ttl
- ? $ttl - $lifeTime
- : 0
- );
- }
- return 0;
- }
- /**
- * Extracts ID, attributes and the file extension from a filename.
- *
- * @param string $filename
- * @return array('id'=>string,'attributes'=>string,'ext'=>string)
- */
- private function extractIdentifier( $filename )
- {
- // Regex to split up the file name into id, attributes and extension
- $regex = '(
- (?:' . preg_quote ( $this-> properties ['location'] ) . ')
- (?P<id>.*)
- (?P<attr>(?:-[^-=]+=[^-]+)*)
- -? # This is added if no attributes are supplied. For whatever reason...
- (?P<ext>' . preg_quote ( $this->options->extension ) . ')
- )Ux';
- if ( preg_match ( $regex, $filename, $matches ) !== 1 )
- {
- // @TODO: Should this be an exception?
- return array(
- 'id' => '',
- 'attributes' => '',
- 'extension' => $this->options->extension,
- );
- }
- else
- {
- // Successfully split
- return array(
- 'id' => $matches['id'],
- 'attributes' => $matches['attr'],
- 'extension' => $matches['ext'],
- );
- }
- }
- }
- ?>
Documentation generated by phpDocumentor 1.4.3