1
0
Fork 0
composer/src/Composer/Cache.php

105 lines
2.7 KiB
PHP
Raw Normal View History

2012-04-06 20:39:43 +00:00
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\IO\IOInterface;
2012-11-01 17:02:08 +00:00
use Composer\Util\Filesystem;
2012-04-06 20:39:43 +00:00
/**
* Reads/writes to a filesystem cache
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class Cache
{
private $io;
private $root;
private $enabled = true;
2012-11-01 17:02:08 +00:00
private $whitelist;
private $filesystem;
2012-04-06 20:39:43 +00:00
2012-11-01 17:02:08 +00:00
public function __construct(IOInterface $io, $cacheDir, $whitelist = 'a-z0-9.', Filesystem $filesystem = null)
2012-04-06 20:39:43 +00:00
{
$this->io = $io;
$this->root = rtrim($cacheDir, '/\\') . '/';
2012-11-01 17:02:08 +00:00
$this->whitelist = $whitelist;
$this->filesystem = $filesystem ?: new Filesystem();
2012-04-06 20:39:43 +00:00
if (!is_dir($this->root)) {
if (!@mkdir($this->root, 0777, true)) {
$this->enabled = false;
}
}
}
public function getRoot()
{
return $this->root;
}
public function read($file)
{
2012-11-01 17:02:08 +00:00
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
2012-04-06 20:39:43 +00:00
if ($this->enabled && file_exists($this->root . $file)) {
return file_get_contents($this->root . $file);
}
}
public function write($file, $contents)
{
if ($this->enabled) {
2012-11-01 17:02:08 +00:00
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
2012-04-06 20:39:43 +00:00
file_put_contents($this->root . $file, $contents);
}
}
2012-11-01 17:02:08 +00:00
public function copyFrom($file, $source)
{
if ($this->enabled) {
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
$this->filesystem->ensureDirectoryExists(dirname($this->root . $file));
copy($source, $this->root . $file);
}
}
public function copyTo($file, $target)
{
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
if ($this->enabled && file_exists($this->root . $file)) {
touch($this->root . $file);
return copy($this->root . $file, $target);
}
}
public function gc($expire)
{
// TODO
}
2012-04-06 20:39:43 +00:00
public function sha1($file)
{
2012-11-01 17:02:08 +00:00
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
2012-04-06 20:39:43 +00:00
if ($this->enabled && file_exists($this->root . $file)) {
return sha1_file($this->root . $file);
}
}
2012-10-14 14:33:53 +00:00
public function sha256($file)
{
2012-11-01 17:02:08 +00:00
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
2012-10-14 14:33:53 +00:00
if ($this->enabled && file_exists($this->root . $file)) {
return hash_file('sha256', $this->root . $file);
}
}
2012-04-06 20:39:43 +00:00
}