silverstripe-textextraction/code/extensions/FileTextExtractable.php
Damian Mooyman 2977f85cb5 API Implement Tika support
API Implement support for detection via mime-type as well as file extension
API Implement FileContent property for safe usage in templates
API instead of returning the list of extensions / mime types supported, support is determined on a per-file bases
Marking dev-master as version 2.0 as this contains breaking changes
2015-02-20 15:12:20 +13:00

55 lines
1.5 KiB
PHP

<?php
/**
* 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
*
*/
class FileTextExtractable extends DataExtension {
private static $db = array(
'FileContentCache' => 'Text'
);
private static $casting = array(
'FileContent' => 'Text'
);
/**
* 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
*/
public function extractFileAsText($disableCache = false) {
if (!$disableCache && $this->owner->FileContentCache) return $this->owner->FileContentCache;
// Determine which extractor can process this file.
$extractor = FileTextExtractor::for_file($this->owner->FullPath);
if (!$extractor) return null;
$text = $extractor->getContent($this->owner->FullPath);
if (!$text) return null;
$this->owner->FileContentCache = $text;
$this->owner->write();
return $text;
}
}