silverstripe-textextraction/code/extensions/FileTextExtractable.php

99 lines
2.4 KiB
PHP
Raw Normal View History

2012-08-22 17:52:08 +02:00
<?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
*
*/
2015-11-18 05:07:31 +01:00
class FileTextExtractable extends DataExtension
{
private static $db = array(
'FileContentCache' => 'Text'
);
2012-08-22 17:52:08 +02:00
2015-11-18 05:07:31 +01:00
private static $casting = array(
'FileContent' => 'Text'
);
2015-11-18 05:07:31 +01:00
private static $dependencies = array(
'TextCache' => '%$FileTextCache'
);
2015-11-18 05:07:31 +01:00
/**
* @var FileTextCache
*/
protected $fileTextCache = null;
2015-11-18 05:07:31 +01:00
/**
*
* @param FileTextCache $cache
*/
public function setTextCache(FileTextCache $cache)
{
$this->fileTextCache = $cache;
}
2015-11-18 05:07:31 +01:00
/**
* @return FileTextCache
*/
public function getTextCache()
{
return $this->fileTextCache;
}
2015-11-18 05:07:31 +01:00
/**
* Helper function for template
*
* @return string
*/
public function getFileContent()
{
return $this->extractFileAsText();
}
2015-11-18 05:07:31 +01:00
/**
* 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) {
$text = $this->getTextCache()->load($this->owner);
if ($text) {
return $text;
}
}
2012-08-22 17:52:08 +02:00
2015-11-18 05:07:31 +01:00
// Determine which extractor can process this file.
$extractor = FileTextExtractor::for_file($this->owner->FullPath);
if (!$extractor) {
return null;
}
2012-08-22 17:52:08 +02:00
2015-11-18 05:07:31 +01:00
$text = $extractor->getContent($this->owner->FullPath);
if (!$text) {
return null;
}
2012-08-22 17:52:08 +02:00
if (!$disableCache) {
$this->getTextCache()->save($this->owner, $text);
}
2012-08-22 17:52:08 +02:00
2015-11-18 05:07:31 +01:00
return $text;
}
2015-11-18 05:07:31 +01:00
public function onBeforeWrite()
{
// Clear cache before changing file
$this->getTextCache()->invalidate($this->owner);
}
2012-08-22 17:52:08 +02:00
}