4 * This file is part of the Behat Gherkin.
5 * (c) Konstantin Kudryashov <ever.zet@gmail.com>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
11 namespace Behat\Gherkin\Cache;
13 use Behat\Gherkin\Exception\CacheException;
14 use Behat\Gherkin\Node\FeatureNode;
15 use Behat\Gherkin\Gherkin;
19 * Caches feature into a file.
21 * @author Konstantin Kudryashov <ever.zet@gmail.com>
23 class FileCache implements CacheInterface
28 * Initializes file cache.
30 * @param string $path Path to the folder where to store caches.
32 * @throws CacheException
34 public function __construct($path)
36 $this->path = rtrim($path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.'v'.Gherkin::VERSION;
38 if (!is_dir($this->path)) {
39 @mkdir($this->path, 0777, true);
42 if (!is_writeable($this->path)) {
43 throw new CacheException(sprintf('Cache path "%s" is not writeable. Check your filesystem permissions or disable Gherkin file cache.', $this->path));
48 * Checks that cache for feature exists and is fresh.
50 * @param string $path Feature path
51 * @param integer $timestamp The last time feature was updated
55 public function isFresh($path, $timestamp)
57 $cachePath = $this->getCachePathFor($path);
59 if (!file_exists($cachePath)) {
63 return filemtime($cachePath) > $timestamp;
67 * Reads feature cache from path.
69 * @param string $path Feature path
73 * @throws CacheException
75 public function read($path)
77 $cachePath = $this->getCachePathFor($path);
78 $feature = unserialize(file_get_contents($cachePath));
80 if (!$feature instanceof FeatureNode) {
81 throw new CacheException(sprintf('Can not load cache for a feature "%s" from "%s".', $path, $cachePath ));
88 * Caches feature node.
90 * @param string $path Feature path
91 * @param FeatureNode $feature Feature instance
93 public function write($path, FeatureNode $feature)
95 file_put_contents($this->getCachePathFor($path), serialize($feature));
99 * Returns feature cache file path from features path.
101 * @param string $path Feature path
105 protected function getCachePathFor($path)
107 return $this->path.'/'.md5($path).'.feature.cache';