From 76c4692d13162e11cab47f526f5688931c001a82 Mon Sep 17 00:00:00 2001 From: Andrew Short Date: Wed, 9 Oct 2013 20:54:08 +1100 Subject: [PATCH] NEW: Add metadata to DMS links. Shortlink links are now augmented with data attributes containing the file extension and size. --- code/DMSShortcodeHandler.php | 35 +++++++++++++++++++++-------------- tests/DMSShortcodeTest.php | 23 +++++++++++++++++++++++ 2 files changed, 44 insertions(+), 14 deletions(-) create mode 100644 tests/DMSShortcodeTest.php diff --git a/code/DMSShortcodeHandler.php b/code/DMSShortcodeHandler.php index 452814f..e55c454 100644 --- a/code/DMSShortcodeHandler.php +++ b/code/DMSShortcodeHandler.php @@ -5,28 +5,35 @@ */ class DMSShortcodeHandler { - public static function handle($arguments, $content = null, $parser = null) { - $linkText = null; + public static function handle( + $arguments, $content, ShortcodeParser $parser, $tag, array $extra = array() + ) { + if(!empty($arguments['id'])) { + $document = DMSDocument::get()->byID($arguments['id']); - if (!empty($arguments['id'])) { - $document = DMSDocument::get()->filter(array('ID' => $arguments['id']))->First(); - if ($document && !$document->isHidden()) { - if (!empty($content)) { - $linkText = sprintf('%s', $document->Link(), $parser->parse($content)); + if($document && !$document->isHidden()) { + if($content) { + return sprintf( + '%s', $document->Link(), $parser->parse($content) + ); } else { - $linkText = $document->Link(); + if(isset($extra['element'])) { + $extra['element']->setAttribute('data-ext', $document->getExtension()); + $extra['element']->setAttribute('data-size', $document->getFileSizeFormatted()); + } + + return $document->Link(); } } } - if (empty($linkText)) { - $errorPage = ErrorPage::get()->filter(array('ErrorCode' => '404'))->First(); - if ($errorPage) { - $linkText = $errorPage->Link(); - } + $error = ErrorPage::get()->filter('ErrorCode', '404')->First(); + + if($error) { + return $error->Link(); } - return $linkText; + return ''; } } diff --git a/tests/DMSShortcodeTest.php b/tests/DMSShortcodeTest.php new file mode 100644 index 0000000..4cbe864 --- /dev/null +++ b/tests/DMSShortcodeTest.php @@ -0,0 +1,23 @@ +storeDocument($file); + + $result = ShortcodeParser::get('default')->parse(sprintf( + '

Document

', $document->ID + )); + + $value = Injector::inst()->create('HTMLValue', $result); + $link = $value->query('//a')->item(0); + + $this->assertEquals("/dmsdocument/$document->ID", $link->getAttribute('href')); + $this->assertEquals($document->getExtension(), $link->getAttribute('data-ext')); + $this->assertEquals($document->getFileSizeFormatted(), $link->getAttribute('data-size')); + } + +}