Merge pull request #21 from helpfulrobot/convert-to-psr-2

Converted to PSR-2
This commit is contained in:
Daniel Hensby 2015-11-18 23:30:07 +00:00
commit ebfa07dc5f
14 changed files with 892 additions and 809 deletions

View File

@ -1,7 +1,7 @@
<?php
interface FileTextCache {
interface FileTextCache
{
/**
* Save extracted content for a given File entity
*
@ -30,32 +30,34 @@ interface FileTextCache {
* Caches the extracted content on the record for the file.
* Limits the stored file content by default to avoid hitting query size limits.
*/
class FileTextCache_Database implements FileTextCache {
public function load(File $file) {
class FileTextCache_Database implements FileTextCache
{
public function load(File $file)
{
return $file->FileContentCache;
}
public function save(File $file, $content) {
public function save(File $file, $content)
{
$maxLength = Config::inst()->get('FileTextCache_Database', 'max_content_length');
$file->FileContentCache = ($maxLength) ? substr($content, 0, $maxLength) : $content;
$file->write();
}
public function invalidate(File $file) {
public function invalidate(File $file)
{
// To prevent writing to the cache from invalidating it
if (!$file->isChanged('FileContentCache')) {
$file->FileContentCache = '';
}
}
}
/**
* Uses SS_Cache with a lifetime to cache extracted content
*/
class FileTextCache_SSCache implements FileTextCache, Flushable {
class FileTextCache_SSCache implements FileTextCache, Flushable
{
/**
* Lifetime of cache in seconds
* Null is indefinite
@ -68,38 +70,43 @@ class FileTextCache_SSCache implements FileTextCache, Flushable {
/**
* @return SS_Cache
*/
protected static function get_cache() {
protected static function get_cache()
{
$lifetime = Config::inst()->get(__CLASS__, 'lifetime');
$cache = SS_Cache::factory(__CLASS__);
$cache->setLifetime($lifetime);
return $cache;
}
protected function getKey(File $file) {
protected function getKey(File $file)
{
return md5($file->getFullPath());
}
public function load(File $file) {
public function load(File $file)
{
$key = $this->getKey($file);
$cache = self::get_cache();
return $cache->load($key);
}
public function save(File $file, $content) {
public function save(File $file, $content)
{
$key = $this->getKey($file);
$cache = self::get_cache();
return $cache->save($content, $key);
}
public static function flush() {
public static function flush()
{
$cache = self::get_cache();
$cache->clean();
}
public function invalidate(File $file) {
public function invalidate(File $file)
{
$key = $this->getKey($file);
$cache = self::get_cache();
return $cache->remove($key);
}
}

View File

@ -9,8 +9,8 @@
* @author mstephens
*
*/
class FileTextExtractable extends DataExtension {
class FileTextExtractable extends DataExtension
{
private static $db = array(
'FileContentCache' => 'Text'
);
@ -32,14 +32,16 @@ class FileTextExtractable extends DataExtension {
*
* @param FileTextCache $cache
*/
public function setTextCache(FileTextCache $cache) {
public function setTextCache(FileTextCache $cache)
{
$this->fileTextCache = $cache;
}
/**
* @return FileTextCache
*/
public function getTextCache() {
public function getTextCache()
{
return $this->fileTextCache;
}
@ -48,7 +50,8 @@ class FileTextExtractable extends DataExtension {
*
* @return string
*/
public function getFileContent() {
public function getFileContent()
{
return $this->extractFileAsText();
}
@ -60,7 +63,8 @@ class FileTextExtractable extends DataExtension {
* If true, the content parsing is forced, bypassing the cached version
* @return string
*/
public function extractFileAsText($disableCache = false) {
public function extractFileAsText($disableCache = false)
{
if (!$disableCache) {
$text = $this->getTextCache()->load($this->owner);
if ($text) {
@ -84,7 +88,8 @@ class FileTextExtractable extends DataExtension {
return $text;
}
public function onBeforeWrite() {
public function onBeforeWrite()
{
// Clear cache before changing file
$this->getTextCache()->invalidate($this->owner);
}

View File

@ -5,8 +5,8 @@
* @author mstephens
*
*/
abstract class FileTextExtractor extends Object {
abstract class FileTextExtractor extends Object
{
/**
* Set priority from 0-100.
* The highest priority extractor for a given content type will be selected.
@ -28,9 +28,12 @@ abstract class FileTextExtractor extends Object {
*
* @return array
*/
protected static function get_extractor_classes() {
protected static function get_extractor_classes()
{
// Check cache
if (self::$sorted_extractor_classes) return self::$sorted_extractor_classes;
if (self::$sorted_extractor_classes) {
return self::$sorted_extractor_classes;
}
// Generate the sorted list of extractors on demand.
$classes = ClassInfo::subclassesFor("FileTextExtractor");
@ -52,7 +55,8 @@ abstract class FileTextExtractor extends Object {
* @param string $class
* @return FileTextExtractor
*/
protected static function get_extractor($class) {
protected static function get_extractor($class)
{
return Injector::inst()->get($class);
}
@ -62,7 +66,8 @@ abstract class FileTextExtractor extends Object {
* @param string $path
* @return string Mime type if found
*/
protected static function get_mime($path) {
protected static function get_mime($path)
{
$file = new Symfony\Component\HttpFoundation\File\File($path);
return $file->getMimeType();
@ -72,7 +77,8 @@ abstract class FileTextExtractor extends Object {
* @param string $path
* @return FileTextExtractor|null
*/
static function for_file($path) {
public static function for_file($path)
{
if (!file_exists($path) || is_dir($path)) {
return;
}
@ -83,7 +89,9 @@ abstract class FileTextExtractor extends Object {
$extractor = self::get_extractor($className);
// Skip unavailable extractors
if(!$extractor->isAvailable()) continue;
if (!$extractor->isAvailable()) {
continue;
}
// Check extension
if ($extension && $extractor->supportsExtension($extension)) {
@ -132,4 +140,6 @@ abstract class FileTextExtractor extends Object {
abstract public function getContent($path);
}
class FileTextExtractor_Exception extends Exception {}
class FileTextExtractor_Exception extends Exception
{
}

View File

@ -5,20 +5,23 @@
* @author mstephens
*
*/
class HTMLTextExtractor extends FileTextExtractor {
public function isAvailable() {
class HTMLTextExtractor extends FileTextExtractor
{
public function isAvailable()
{
return true;
}
public function supportsExtension($extension) {
public function supportsExtension($extension)
{
return in_array(
strtolower($extension),
array("html", "htm", "xhtml")
);
}
public function supportsMime($mime) {
public function supportsMime($mime)
{
return strtolower($mime) === 'text/html';
}
@ -38,7 +41,8 @@ class HTMLTextExtractor extends FileTextExtractor {
* @param string $path
* @return string
*/
public function getContent($path) {
public function getContent($path)
{
$content = file_get_contents($path);
// Yes, yes, regex'ing HTML is evil.
// Since we don't care about well-formedness or markup here, it does the job.

View File

@ -5,18 +5,21 @@
* @author mstephens
*
*/
class PDFTextExtractor extends FileTextExtractor {
public function isAvailable() {
class PDFTextExtractor extends FileTextExtractor
{
public function isAvailable()
{
$bin = $this->bin('pdftotext');
return (file_exists($bin) && is_executable($bin));
}
public function supportsExtension($extension) {
public function supportsExtension($extension)
{
return strtolower($extension) === 'pdf';
}
public function supportsMime($mime) {
public function supportsMime($mime)
{
return in_array(
strtolower($mime),
array(
@ -34,7 +37,8 @@ class PDFTextExtractor extends FileTextExtractor {
* @param string $prog Name of binary
* @return string
*/
protected function bin($prog = '') {
protected function bin($prog = '')
{
if ($this->config()->binary_location) {
// By config
$path = $this->config()->binary_location;
@ -50,8 +54,11 @@ class PDFTextExtractor extends FileTextExtractor {
return ($path ? $path . '/' : '') . $prog;
}
public function getContent($path) {
if(!$path) return ""; // no file
public function getContent($path)
{
if (!$path) {
return "";
} // no file
$content = $this->getRawOutput($path);
return $this->cleanupLigatures($content);
}
@ -63,7 +70,8 @@ class PDFTextExtractor extends FileTextExtractor {
* @return string Output
* @throws FileTextExtractor_Exception
*/
protected function getRawOutput($path) {
protected function getRawOutput($path)
{
exec(sprintf('%s %s - 2>&1', $this->bin('pdftotext'), escapeshellarg($path)), $content, $err);
if ($err) {
throw new FileTextExtractor_Exception(sprintf(
@ -83,7 +91,8 @@ class PDFTextExtractor extends FileTextExtractor {
* @param string $input
* @return string
*/
protected function cleanupLigatures($input) {
protected function cleanupLigatures($input)
{
$mapping = array(
'ff' => 'ff',
'fi' => 'fi',

View File

@ -10,8 +10,8 @@ use Guzzle\Http\Client;
* @author ischommer
* @see http://wiki.apache.org/solr/ExtractingRequestHandler
*/
class SolrCellTextExtractor extends FileTextExtractor {
class SolrCellTextExtractor extends FileTextExtractor
{
/**
* Base URL to use for solr text extraction.
* E.g. http://localhost:8983/solr/update/extract
@ -25,24 +25,30 @@ class SolrCellTextExtractor extends FileTextExtractor {
protected $httpClient;
public function getHttpClient() {
public function getHttpClient()
{
if (!$this->config()->get('base_url')) {
throw new InvalidArgumentException('SolrCellTextExtractor.base_url not specified');
}
if(!$this->httpClient) $this->httpClient = new Client($this->config()->get('base_url'));
if (!$this->httpClient) {
$this->httpClient = new Client($this->config()->get('base_url'));
}
return $this->httpClient;
}
public function setHttpClient($client) {
public function setHttpClient($client)
{
$this->httpClient = $client;
}
public function isAvailable() {
public function isAvailable()
{
$url = $this->config()->get('base_url');
return (boolean) $url;
}
public function supportsExtension($extension) {
public function supportsExtension($extension)
{
return in_array(
strtolower($extension),
array(
@ -53,13 +59,17 @@ class SolrCellTextExtractor extends FileTextExtractor {
);
}
public function supportsMime($mime) {
public function supportsMime($mime)
{
// Rely on supportsExtension
return false;
}
public function getContent($path) {
if (!$path) return ""; // no file
public function getContent($path)
{
if (!$path) {
return "";
} // no file
$fileName = basename($path);
$client = $this->getHttpClient();

View File

@ -5,8 +5,8 @@
*
* {@link http://tika.apache.org/1.7/gettingstarted.html}
*/
class TikaServerTextExtractor extends FileTextExtractor {
class TikaServerTextExtractor extends FileTextExtractor
{
/**
* Tika server is pretty efficient so use it immediately if available
*
@ -31,7 +31,8 @@ class TikaServerTextExtractor extends FileTextExtractor {
/**
* @return TikaRestClient
*/
public function getClient() {
public function getClient()
{
return $this->client ?:
($this->client =
Injector::inst()->createWithArgs(
@ -41,12 +42,15 @@ class TikaServerTextExtractor extends FileTextExtractor {
);
}
public function getServerEndpoint() {
public function getServerEndpoint()
{
if (defined('SS_TIKA_ENDPOINT')) {
return SS_TIKA_ENDPOINT;
}
if(getenv('SS_TIKA_ENDPOINT')) return getenv('SS_TIKA_ENDPOINT');
if (getenv('SS_TIKA_ENDPOINT')) {
return getenv('SS_TIKA_ENDPOINT');
}
// Default to configured endpoint
return $this->config()->server_endpoint;
@ -57,19 +61,22 @@ class TikaServerTextExtractor extends FileTextExtractor {
*
* @return float version of tika
*/
public function getVersion() {
public function getVersion()
{
return $this
->getClient()
->getVersion();
}
public function isAvailable() {
public function isAvailable()
{
return $this->getServerEndpoint() &&
$this->getClient()->isAvailable() &&
$this->getVersion() >= 1.7;
}
public function supportsExtension($extension) {
public function supportsExtension($extension)
{
// Determine support via mime type only
return false;
}
@ -82,23 +89,28 @@ class TikaServerTextExtractor extends FileTextExtractor {
*/
protected $supportedMimes = array();
public function supportsMime($mime) {
public function supportsMime($mime)
{
$supported = $this->supportedMimes ?:
($this->supportedMimes = $this->getClient()->getSupportedMimes());
// Check if supported (most common / quickest lookup)
if(isset($supported[$mime])) return true;
if (isset($supported[$mime])) {
return true;
}
// Check aliases
foreach ($supported as $info) {
if(isset($info['alias']) && in_array($mime, $info['alias'])) return true;
if (isset($info['alias']) && in_array($mime, $info['alias'])) {
return true;
}
}
return false;
}
public function getContent($path) {
public function getContent($path)
{
return $this->getClient()->tika($path);
}
}

View File

@ -5,8 +5,8 @@
*
* {@link http://tika.apache.org/1.7/gettingstarted.html}
*/
class TikaTextExtractor extends FileTextExtractor {
class TikaTextExtractor extends FileTextExtractor
{
/**
* Text extraction mode. Defaults to -t (plain text)
*
@ -20,7 +20,8 @@ class TikaTextExtractor extends FileTextExtractor {
*
* @return float version of tika
*/
public function getVersion() {
public function getVersion()
{
$code = $this->runShell('tika --version', $stdout);
// Parse output
@ -40,7 +41,8 @@ class TikaTextExtractor extends FileTextExtractor {
* @param string $input Content to pass via standard input
* @return int Exit code. 0 is success
*/
protected function runShell($command, &$stdout = '', &$stderr = '', $input = '') {
protected function runShell($command, &$stdout = '', &$stderr = '', $input = '')
{
$descriptorSpecs = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
@ -49,7 +51,9 @@ class TikaTextExtractor extends FileTextExtractor {
// Invoke command
$pipes = array();
$proc = proc_open($command, $descriptorSpecs, $pipes);
if (!is_resource($proc)) return 255;
if (!is_resource($proc)) {
return 255;
}
// Send content as input
fwrite($pipes[0], $input);
@ -65,30 +69,37 @@ class TikaTextExtractor extends FileTextExtractor {
return proc_close($proc);
}
public function getContent($path) {
public function getContent($path)
{
$mode = $this->config()->output_mode;
$command = sprintf('tika %s %s', $mode, escapeshellarg($path));
$code = $this->runShell($command, $output);
if($code == 0) return $output;
if ($code == 0) {
return $output;
}
}
public function isAvailable() {
public function isAvailable()
{
return $this->getVersion() > 0;
}
public function supportsExtension($extension) {
public function supportsExtension($extension)
{
// Determine support via mime type only
return false;
}
public function supportsMime($mime) {
public function supportsMime($mime)
{
// Get list of supported mime types
$code = $this->runShell('tika --list-supported-types', $supportedTypes, $error);
if($code) return false; // Error case
if ($code) {
return false;
} // Error case
// Check if the mime type is inside the result
$pattern = sprintf('/\b(%s)\b/', preg_quote($mime, '/'));
return (bool)preg_match($pattern, $supportedTypes);
}
}

View File

@ -3,14 +3,15 @@
use Guzzle\Http\Client;
use Guzzle\Http\Exception\RequestException;
class TikaRestClient extends Client {
class TikaRestClient extends Client
{
/**
* Detect if the service is available
*
* @return bool
*/
public function isAvailable() {
public function isAvailable()
{
try {
return $this
->get()->send()
@ -25,7 +26,8 @@ class TikaRestClient extends Client {
*
* @return float
*/
public function getVersion() {
public function getVersion()
{
$response = $this->get('version')->send();
// Parse output
if ($response->getStatusCode() == 200 &&
@ -44,8 +46,11 @@ class TikaRestClient extends Client {
*
* @return array
*/
public function getSupportedMimes() {
if($this->mimes) return $this->mimes;
public function getSupportedMimes()
{
if ($this->mimes) {
return $this->mimes;
}
$response = $this->get(
'mime-types',
@ -62,7 +67,8 @@ class TikaRestClient extends Client {
* @param string $file Full filesystem path to a file to post
* @return string Content of the file extracted as plain text
*/
public function tika($file) {
public function tika($file)
{
$text = null;
try {
$response = $this->put(
@ -90,5 +96,4 @@ class TikaRestClient extends Client {
return $text;
}
}

View File

@ -1,7 +1,8 @@
<?php
class FileTextCacheDatabaseTest extends SapphireTest {
public function testTruncatesByMaxLength() {
class FileTextCacheDatabaseTest extends SapphireTest
{
public function testTruncatesByMaxLength()
{
Config::nest();
Config::inst()->update('FileTextCache_Database', 'max_content_length', 5);
@ -13,5 +14,4 @@ class FileTextCacheDatabaseTest extends SapphireTest {
Config::unnest();
}
}

View File

@ -1,11 +1,12 @@
<?php
class FileTextExtractableTest extends SapphireTest {
class FileTextExtractableTest extends SapphireTest
{
protected $requiredExtensions = array(
'File' => array('FileTextExtractable')
);
public function setUp() {
public function setUp()
{
parent::setUp();
// Ensure that html is a valid extension
@ -14,12 +15,14 @@ class FileTextExtractableTest extends SapphireTest {
->update('File', 'allowed_extensions', array('html'));
}
public function tearDown() {
public function tearDown()
{
Config::unnest();
parent::tearDown();
}
function testExtractFileAsText() {
public function testExtractFileAsText()
{
// Create a copy of the file, as it may be clobbered by the test
// ($file->extractFileAsText() calls $file->write)
copy(BASE_PATH.'/textextraction/tests/fixtures/test1.html', BASE_PATH.'/textextraction/tests/fixtures/test1-copy.html');
@ -36,8 +39,8 @@ class FileTextExtractableTest extends SapphireTest {
$this->assertContains('Test Text', $content);
$this->assertEquals($content, $file->FileContentCache);
if(file_exists(BASE_PATH.'/textextraction/tests/fixtures/test1-copy.html')) unlink(BASE_PATH.'/textextraction/tests/fixtures/test1-copy.html');
if (file_exists(BASE_PATH.'/textextraction/tests/fixtures/test1-copy.html')) {
unlink(BASE_PATH.'/textextraction/tests/fixtures/test1-copy.html');
}
}
}

View File

@ -1,7 +1,8 @@
<?php
class HTMLTextExtractorTest extends SapphireTest {
function testExtraction() {
class HTMLTextExtractorTest extends SapphireTest
{
public function testExtraction()
{
$extractor = new HTMLTextExtractor();
$content = $extractor->getContent(Director::baseFolder() . '/textextraction/tests/fixtures/test1.html');
@ -10,5 +11,4 @@ class HTMLTextExtractorTest extends SapphireTest {
$this->assertNotContains('Test Style', $content, 'Strips non-content style tags');
$this->assertNotContains('Test Script', $content, 'Strips non-content script tags');
}
}

View File

@ -1,12 +1,14 @@
<?php
class PDFTextExtractorTest extends SapphireTest {
function testExtraction() {
class PDFTextExtractorTest extends SapphireTest
{
public function testExtraction()
{
$extractor = new PDFTextExtractor();
if(!$extractor->isAvailable()) $this->markTestSkipped('pdftotext not available');
if (!$extractor->isAvailable()) {
$this->markTestSkipped('pdftotext not available');
}
$content = $extractor->getContent(Director::baseFolder() . '/textextraction/tests/fixtures/test1.pdf');
$this->assertContains('This is a test file with a link', $content);
}
}

View File

@ -3,11 +3,14 @@
/**
* Tests the {@see TikaTextExtractor} class
*/
class TikaTextExtractorTest extends SapphireTest {
function testExtraction() {
class TikaTextExtractorTest extends SapphireTest
{
public function testExtraction()
{
$extractor = new TikaTextExtractor();
if(!$extractor->isAvailable()) $this->markTestSkipped('tika cli not available');
if (!$extractor->isAvailable()) {
$this->markTestSkipped('tika cli not available');
}
// Check file
$file = Director::baseFolder() . '/textextraction/tests/fixtures/test1.pdf';
@ -20,9 +23,12 @@ class TikaTextExtractorTest extends SapphireTest {
$this->assertFalse($extractor->supportsMime('application/not-supported'));
}
function testServerExtraction() {
public function testServerExtraction()
{
$extractor = new TikaServerTextExtractor();
if(!$extractor->isAvailable()) $this->markTestSkipped('tika server not available');
if (!$extractor->isAvailable()) {
$this->markTestSkipped('tika server not available');
}
// Check file
$file = Director::baseFolder() . '/textextraction/tests/fixtures/test1.pdf';
@ -34,5 +40,4 @@ class TikaTextExtractorTest extends SapphireTest {
$this->assertTrue($extractor->supportsMime('text/html'));
$this->assertFalse($extractor->supportsMime('application/not-supported'));
}
}