1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of Transfer. |
5
|
|
|
* |
6
|
|
|
* For the full copyright and license information, please view the LICENSE file located |
7
|
|
|
* in the root directory. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Transfer\Storage; |
11
|
|
|
|
12
|
|
|
use Transfer\Storage\Exception\ObjectNotFoundException; |
13
|
|
|
use Transfer\Storage\Hashing\HashingStrategyInterface; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* File storage. |
17
|
|
|
*/ |
18
|
|
|
class FileStorage extends AbstractStorage |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var string Storage directory |
22
|
|
|
*/ |
23
|
|
|
private $directory; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param string $directory Storage directory |
27
|
|
|
* @param HashingStrategyInterface $hashingStrategy Hashing strategy |
28
|
|
|
*/ |
29
|
|
|
public function __construct($directory = '/tmp', HashingStrategyInterface $hashingStrategy = null) |
30
|
|
|
{ |
31
|
|
|
parent::__construct($hashingStrategy); |
32
|
|
|
|
33
|
|
|
$this->directory = $directory; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* {@inheritdoc} |
38
|
|
|
*/ |
39
|
|
|
public function add($object, $id = null) |
40
|
|
|
{ |
41
|
|
|
if ($id === null) { |
42
|
|
|
$id = $this->hashingStrategy->hash($object); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
file_put_contents(sprintf('%s/%s', $this->directory, $id), serialize($object)); |
46
|
|
|
|
47
|
|
|
return true; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* {@inheritdoc} |
52
|
|
|
*/ |
53
|
|
|
public function contains($object) |
54
|
|
|
{ |
55
|
|
|
return $this->containsId($this->hashingStrategy->hash($object)); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* {@inheritdoc} |
60
|
|
|
*/ |
61
|
|
|
public function containsId($id) |
62
|
|
|
{ |
63
|
|
|
return file_exists(sprintf('%s/%s', $this->directory, $id)); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* {@inheritdoc} |
68
|
|
|
*/ |
69
|
|
|
public function findById($id) |
70
|
|
|
{ |
71
|
|
|
if (!$this->containsId($id)) { |
72
|
|
|
throw new ObjectNotFoundException($id); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return unserialize(file_get_contents(sprintf('%s/%s', $this->directory, $id))); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* {@inheritdoc} |
80
|
|
|
*/ |
81
|
|
|
public function remove($object) |
82
|
|
|
{ |
83
|
|
|
return $this->removeById($this->hashingStrategy->hash($object)); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* {@inheritdoc} |
88
|
|
|
*/ |
89
|
|
|
public function removeById($id) |
90
|
|
|
{ |
91
|
|
|
unlink(sprintf('%s/%s', $this->directory, $id)); |
92
|
|
|
|
93
|
|
|
return true; |
94
|
|
|
} |
95
|
|
|
|
96
|
|
|
/** |
97
|
|
|
* {@inheritdoc} |
98
|
|
|
*/ |
99
|
|
|
public function all() |
100
|
|
|
{ |
101
|
|
|
throw new \Exception('Unsupported method.'); |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|