|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace DocumentStorage\Adapter\Storage; |
|
5
|
|
|
|
|
6
|
|
|
use DocumentStorage\Exception\DocumentNotFound; |
|
7
|
|
|
use DocumentStorage\Exception\DocumentNotStored; |
|
8
|
|
|
use DocumentStorage\Storage; |
|
9
|
|
|
|
|
10
|
|
|
class Filesystem implements Storage |
|
11
|
|
|
{ |
|
12
|
|
|
/** @var string */ |
|
13
|
|
|
private $storageDir; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* @throws \InvalidArgumentException If $storageDir is not a directory |
|
17
|
|
|
* @throws \InvalidArgumentException If $storageDir is not writable |
|
18
|
|
|
*/ |
|
19
|
|
|
public function __construct(string $storageDir) |
|
20
|
|
|
{ |
|
21
|
|
|
if (!is_dir($storageDir)) { |
|
22
|
|
|
throw new \InvalidArgumentException(sprintf('[%s] is not a directory', $storageDir)); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
if (!is_writable($storageDir)) { |
|
26
|
|
|
throw new \InvalidArgumentException(sprintf('[%s] is not writable', $storageDir)); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
$this->storageDir = $storageDir; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function store(string $pathOrBody, string $targetDocName, string $oldDocName = '') : string |
|
33
|
|
|
{ |
|
34
|
|
|
$docPath = $this->getDocPath($targetDocName); |
|
35
|
|
|
|
|
36
|
|
|
$stored = file_exists($pathOrBody) |
|
37
|
|
|
? copy($pathOrBody, $docPath) |
|
38
|
|
|
: file_put_contents($docPath, $pathOrBody); |
|
39
|
|
|
|
|
40
|
|
|
if (false === $stored) { |
|
41
|
|
|
throw new DocumentNotStored('There was an error storing the document [%s] to the filesystem.'); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
return $docPath; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function retrieve(string $docName) : string |
|
48
|
|
|
{ |
|
49
|
|
|
$docPath = $this->getDocPath($docName); |
|
50
|
|
|
|
|
51
|
|
|
if (false === file_exists($docPath) || false === $contents = file_get_contents($docPath)) { |
|
52
|
|
|
throw new DocumentNotFound(sprintf('Could not retrieve [%s]', $docPath)); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return $contents; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function getUrl(string $docName) : string |
|
59
|
|
|
{ |
|
60
|
|
|
return ''; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
private function getDocPath(string $docName) : string |
|
64
|
|
|
{ |
|
65
|
|
|
return $this->storageDir.DIRECTORY_SEPARATOR.$docName; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|