-
Notifications
You must be signed in to change notification settings - Fork 25
/
FileTextExtractable.php
124 lines (109 loc) · 2.87 KB
/
FileTextExtractable.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
119
120
121
122
123
124
<?php
namespace SilverStripe\TextExtraction\Extension;
use SilverStripe\Assets\File;
use SilverStripe\ORM\DataExtension;
use SilverStripe\TextExtraction\Cache\FileTextCache;
use SilverStripe\TextExtraction\Extractor\FileTextExtractor;
/**
* Decorate File or a File derivative to enable text extraction from the file content. Uses a set of subclasses of
* FileTextExtractor to do the extraction based on the content type of the file.
*
* Adds an additional property which is the cached contents, which is populated on demand.
*
* @author mstephens
*
* @extends DataExtension<File>
*/
class FileTextExtractable extends DataExtension
{
/**
* @var array
* @config
*/
private static $db = [
'FileContentCache' => 'Text'
];
/**
* @var array
* @config
*/
private static $casting = [
'FileContent' => 'Text'
];
/**
* @var array
* @config
*/
private static $dependencies = [
'TextCache' => '%$' . FileTextCache::class,
];
/**
* @var FileTextCache
*/
protected $fileTextCache = null;
/**
* @param FileTextCache $cache
* @return $this
*/
public function setTextCache(FileTextCache $cache)
{
$this->fileTextCache = $cache;
return $this;
}
/**
* @return FileTextCache
*/
public function getTextCache()
{
return $this->fileTextCache;
}
/**
* Helper function for template
*
* @return string
*/
public function getFileContent()
{
return $this->extractFileAsText();
}
/**
* Tries to parse the file contents if a FileTextExtractor class exists to handle the file type, and
* returns the text. The value is also cached into the File record itself.
*
* @param boolean $disableCache If false, the file content is only parsed on demand.
* If true, the content parsing is forced, bypassing
* the cached version
* @return string|null
*/
public function extractFileAsText($disableCache = false)
{
$file = $this->owner;
if (!$disableCache) {
$text = $this->getTextCache()->load($file);
if ($text) {
return $text;
}
}
// Determine which extractor can process this file.
$extractor = FileTextExtractor::for_file($file);
if (!$extractor) {
return null;
}
$text = $extractor->getContent($file);
if (!$text) {
return null;
}
if (!$disableCache) {
$this->getTextCache()->save($file, $text);
}
return $text;
}
/**
* @return void
*/
public function onBeforeWrite()
{
// Clear cache before changing file
$this->getTextCache()->invalidate($this->owner);
}
}