/
GeneratedAssets.php
118 lines (105 loc) · 3.01 KB
/
GeneratedAssets.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
namespace SilverStripe\Assets\Flysystem;
use Exception;
use SilverStripe\Assets\Flysystem\Filesystem;
use League\Flysystem\UnableToWriteFile;
use SilverStripe\Assets\Storage\GeneratedAssetHandler;
/**
* Simple Flysystem implementation of GeneratedAssetHandler for storing generated content
*/
class GeneratedAssets implements GeneratedAssetHandler
{
/**
* Flysystem store for files
*
* @var Filesystem
*/
protected $assetStore = null;
/**
* Assign the asset backend. This must be a filesystem
* with an adapter of type {@see PublicAdapter}.
*
* @param Filesystem $store
* @return $this
*/
public function setFilesystem(Filesystem $store)
{
$this->assetStore = $store;
return $this;
}
/**
* Get the asset backend
*
* @return Filesystem
* @throws Exception
*/
public function getFilesystem()
{
if (!$this->assetStore) {
throw new Exception("Filesystem misconfiguration error");
}
return $this->assetStore;
}
public function getContentURL($filename, $callback = null)
{
$result = $this->checkOrCreate($filename, $callback);
if (!$result) {
return null;
}
$filesystem = $this->getFilesystem();
if (! $filesystem instanceof Filesystem) {
return null;
}
$adapter = $filesystem->getAdapter();
if (!$adapter instanceof PublicAdapter) {
return null;
}
return $adapter->getPublicUrl($filename);
}
public function getContent($filename, $callback = null)
{
$result = $this->checkOrCreate($filename, $callback);
if (!$result) {
return null;
}
return $this
->getFilesystem()
->read($filename);
}
/**
* Check if the file exists or that the $callback provided was able to regenerate it.
*
* @param string $filename
* @param callable $callback
* @return bool Whether or not the file exists
* @throws UnableToWriteFile If an error has occurred during save
*/
protected function checkOrCreate($filename, $callback = null)
{
// Check if there is an existing asset
if ($this->getFilesystem()->has($filename)) {
return true;
}
if (!$callback) {
return false;
}
// Invoke regeneration and save
$content = call_user_func($callback);
$this->setContent($filename, $content);
return true;
}
public function setContent($filename, $content)
{
// Store content
$this->getFilesystem()->write($filename, $content);
}
public function removeContent($filename)
{
$filesystem = $this->getFilesystem();
if ($filesystem->directoryExists($filename)) {
$filesystem->deleteDirectory($filename);
} elseif ($filesystem->fileExists($filename)) {
$filesystem->delete($filename);
}
}
}