-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWeedStorage.php
85 lines (78 loc) · 2.6 KB
/
WeedStorage.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
namespace Micjohnson\WeedPhpBundle;
use InvalidArgumentException;
class WeedStorage
{
protected $weedPhp;
public function __construct($weedPhp)
{
$this->weedPhp = $weedPhp;
}
/**
* return a random server
* @param unknown $volumeId
*
* TODO Throw proper exception
*/
public function randomLookup($volumeId)
{
$lookup = $this->weedPhp->lookup($volumeId);
$lookup = json_decode($lookup, true);
if($lookup === false || array_key_exists("error", $lookup)) {
return false;
}
$locs = $lookup['locations'];
$count = count($locs);
$rand = rand(0, $count-1);
return $locs[$rand]['publicUrl'];
}
public function store($entity)
{
$dataArray = $entity->getData();
if(!is_array($dataArray)) {
$dataArray = array( $dataArray );
}
$count = count($dataArray);
$files = array();
foreach($dataArray as $data) {
$files[] = $data;
}
$replication = $entity->getReplicationScheme();
$assignResponse = $this->weedPhp->assign($count, $replication);
$assignResponse = json_decode($assignResponse, true);
$volumeAddress = $assignResponse['publicUrl'];
$fid = $assignResponse['fid'];
$entity->setFileId($fid);
$response = $this->weedPhp->storeMultiple($volumeAddress, $fid, $files);
return $response;
}
public function retrieve($entity, $version)
{
$fileId = $entity->getFileId();
if($version !== 0) {
if(!$entity->hasVersion($version)) {
throw new InvalidArgumentException('That version does not exist');
}
$fileId .= '_' . $entity->getVersionOffset($version);
}
$volumeId = explode(',', $entity->getFileId());
$volumeId = $volumeId[0];
$serverAddress = $this->randomLookup($volumeId);
return $this->weedPhp->retrieve($serverAddress, $fileId);
}
public function delete($entity)
{
$fileId = $entity->getFileId();
$volumeId = explode(',', $entity->getFileId());
$volumeId = $volumeId[0];
if($serverAddress = $this->randomLookup($volumeId)) {
if(!$entity->getVersions()) {
throw new \Exception("No information about this files versions are stored");
}
foreach($entity->getVersions() as $offset=>$name) {
$this->weedPhp->delete($serverAddress, $fileId);
$fileId = $entity->getFileId() . '_' . ($offset+1);
}
}
}
}