Converted to PSR-2

This commit is contained in:
helpfulrobot 2015-11-21 19:25:41 +13:00
parent 2f0cbfe4f6
commit ced8128190
26 changed files with 4223 additions and 4033 deletions

View File

@ -5,8 +5,8 @@
*
* @package docsviewer
*/
class DocumentationHelper {
class DocumentationHelper
{
/**
* String helper for cleaning a file name to a readable version.
*
@ -14,7 +14,8 @@ class DocumentationHelper {
*
* @return string $name output
*/
public static function clean_page_name($name) {
public static function clean_page_name($name)
{
$name = self::trim_extension_off($name);
$name = self::trim_sort_number($name);
@ -30,13 +31,14 @@ class DocumentationHelper {
*
* @return string $name output
*/
public static function clean_page_url($name) {
public static function clean_page_url($name)
{
$name = str_replace(array(' '), '_', $name);
$name = self::trim_extension_off($name);
$name = self::trim_sort_number($name);
if(preg_match('/^[\/]?index[\/]?/', $name)) {
if (preg_match('/^[\/]?index[\/]?/', $name)) {
return '';
}
@ -50,7 +52,8 @@ class DocumentationHelper {
*
* @return string
*/
public static function trim_sort_number($name) {
public static function trim_sort_number($name)
{
$name = preg_replace("/^[0-9]*[_-]+/", '', $name);
return $name;
@ -65,9 +68,10 @@ class DocumentationHelper {
*
* @return string
*/
public static function trim_extension_off($name) {
if(strrpos($name,'.') !== false) {
return substr($name, 0, strrpos($name,'.'));
public static function trim_extension_off($name)
{
if (strrpos($name, '.') !== false) {
return substr($name, 0, strrpos($name, '.'));
}
return $name;
@ -80,9 +84,10 @@ class DocumentationHelper {
*
* @return string
*/
public static function get_extension($name) {
if(preg_match('/\.[a-z]+$/', $name)) {
return substr($name, strrpos($name,'.') + 1);
public static function get_extension($name)
{
if (preg_match('/\.[a-z]+$/', $name)) {
return substr($name, strrpos($name, '.') + 1);
}
return null;

View File

@ -27,8 +27,8 @@
* @package framework
* @subpackage manifest
*/
class DocumentationManifest {
class DocumentationManifest
{
/**
* @config
*
@ -78,7 +78,8 @@ class DocumentationManifest {
* @param bool $includeTests Include tests in the manifest.
* @param bool $forceRegen Force the manifest to be regenerated.
*/
public function __construct($forceRegen = false) {
public function __construct($forceRegen = false)
{
$this->cacheKey = 'manifest';
$this->forceRegen = $forceRegen;
$this->registeredEntities = new ArrayList();
@ -97,23 +98,24 @@ class DocumentationManifest {
* Either manually registered through the YAML syntax or automatically
* loaded through investigating the file system for `docs` folder.
*/
public function setupEntities() {
if($this->registeredEntities->Count() > 0) {
public function setupEntities()
{
if ($this->registeredEntities->Count() > 0) {
return;
}
if(Config::inst()->get('DocumentationManifest', 'automatic_registration')) {
if (Config::inst()->get('DocumentationManifest', 'automatic_registration')) {
$this->populateEntitiesFromInstall();
}
$registered = Config::inst()->get('DocumentationManifest', 'register_entities');
foreach($registered as $details) {
foreach ($registered as $details) {
// validate the details provided through the YAML configuration
$required = array('Path', 'Title');
foreach($required as $require) {
if(!isset($details[$require])) {
foreach ($required as $require) {
if (!isset($details[$require])) {
throw new Exception("$require is a required key in DocumentationManifest.register_entities");
}
}
@ -124,7 +126,7 @@ class DocumentationManifest {
$key = (isset($details['Key'])) ? $details['Key'] : $details['Title'];
if(!$path || !is_dir($path)) {
if (!$path || !is_dir($path)) {
throw new Exception($details['Path'] . ' is not a valid documentation directory');
}
@ -134,11 +136,11 @@ class DocumentationManifest {
$langs = scandir($path);
if($langs) {
if ($langs) {
$possible = i18n::get_common_languages(true);
foreach($langs as $k => $lang) {
if(isset($possible[$lang])) {
foreach ($langs as $k => $lang) {
if (isset($possible[$lang])) {
$entity = Injector::inst()->create(
'DocumentationEntity', $key
);
@ -149,11 +151,11 @@ class DocumentationManifest {
$entity->setVersion($version);
$entity->setBranch($branch);
if(isset($details['Stable'])) {
if (isset($details['Stable'])) {
$entity->setIsStable($details['Stable']);
}
if(isset($details['DefaultEntity'])) {
if (isset($details['DefaultEntity'])) {
$entity->setIsDefaultEntity($details['DefaultEntity']);
}
@ -164,8 +166,9 @@ class DocumentationManifest {
}
}
public function getRealPath($path) {
if(substr($path, 0, 1) != '/') {
public function getRealPath($path)
{
if (substr($path, 0, 1) != '/') {
$path = Controller::join_links(BASE_PATH, $path);
}
@ -175,7 +178,8 @@ class DocumentationManifest {
/**
* @return ArrayList
*/
public function getEntities() {
public function getEntities()
{
return $this->registeredEntities;
}
@ -185,24 +189,25 @@ class DocumentationManifest {
*
* @return void
*/
public function populateEntitiesFromInstall() {
if($this->automaticallyPopulated) {
public function populateEntitiesFromInstall()
{
if ($this->automaticallyPopulated) {
// already run
return;
}
foreach(scandir(BASE_PATH) as $key => $entity) {
if($key == "themes") {
foreach (scandir(BASE_PATH) as $key => $entity) {
if ($key == "themes") {
continue;
}
$dir = Controller::join_links(BASE_PATH, $entity);
if(is_dir($dir)) {
if (is_dir($dir)) {
// check to see if it has docs
$docs = Controller::join_links($dir, 'docs');
if(is_dir($docs)) {
if (is_dir($docs)) {
$entities[] = array(
'Path' => $docs,
'Title' => DocumentationHelper::clean_page_name($entity),
@ -224,7 +229,8 @@ class DocumentationManifest {
/**
*
*/
protected function init() {
protected function init()
{
if (!$this->forceRegen && $data = $this->cache->load($this->cacheKey)) {
$this->pages = $data['pages'];
$this->redirects = $data['redirects'];
@ -240,7 +246,8 @@ class DocumentationManifest {
*
* @return array
*/
public function getPages() {
public function getPages()
{
if (!$this->inited) {
$this->init();
}
@ -248,8 +255,9 @@ class DocumentationManifest {
return $this->pages;
}
public function getRedirects() {
if(!$this->inited) {
public function getRedirects()
{
if (!$this->inited) {
$this->init();
}
@ -261,19 +269,20 @@ class DocumentationManifest {
*
* @return DocumentationPage
*/
public function getPage($url) {
public function getPage($url)
{
$pages = $this->getPages();
$url = $this->normalizeUrl($url);
if(!isset($pages[$url])) {
if (!isset($pages[$url])) {
return null;
}
$record = $pages[$url];
foreach($this->getEntities() as $entity) {
if(strpos($record['filepath'], $entity->getPath()) !== false) {
foreach ($this->getEntities() as $entity) {
if (strpos($record['filepath'], $entity->getPath()) !== false) {
$page = Injector::inst()->create(
$record['type'],
$entity,
@ -292,11 +301,12 @@ class DocumentationManifest {
* @param type $url
* @return string
*/
public function getRedirect($url) {
public function getRedirect($url)
{
$pages = $this->getRedirects();
$url = $this->normalizeUrl($url);
if(isset($pages[$url])) {
if (isset($pages[$url])) {
return $pages[$url];
}
}
@ -306,7 +316,8 @@ class DocumentationManifest {
*
* @param bool $cache
*/
public function regenerate($cache = true) {
public function regenerate($cache = true)
{
$finder = new DocumentationManifestFileFinder();
$finder->setOptions(array(
'dir_callback' => array($this, 'handleFolder'),
@ -314,7 +325,7 @@ class DocumentationManifest {
));
$this->redirects = array();
foreach($this->getEntities() as $entity) {
foreach ($this->getEntities() as $entity) {
$this->entity = $entity;
$this->handleFolder('', $this->entity->getPath(), 0);
@ -324,8 +335,8 @@ class DocumentationManifest {
// groupds
$grouped = array();
foreach($this->pages as $url => $page) {
if(!isset($grouped[$page['entitypath']])) {
foreach ($this->pages as $url => $page) {
if (!isset($grouped[$page['entitypath']])) {
$grouped[$page['entitypath']] = array();
}
@ -334,13 +345,13 @@ class DocumentationManifest {
$this->pages = array();
foreach($grouped as $entity) {
uasort($entity, function($a, $b) {
foreach ($grouped as $entity) {
uasort($entity, function ($a, $b) {
// ensure parent directories are first
$a['filepath'] = str_replace('index.md', '', $a['filepath']);
$b['filepath'] = str_replace('index.md', '', $b['filepath']);
if(strpos($b['filepath'], $a['filepath']) === 0) {
if (strpos($b['filepath'], $a['filepath']) === 0) {
return -1;
}
@ -373,7 +384,8 @@ class DocumentationManifest {
* @param string $link
* @return string
*/
protected function stripLinkBase($link) {
protected function stripLinkBase($link)
{
return ltrim(str_replace(
Config::inst()->get('DocumentationViewer', 'link_base'),
'',
@ -387,7 +399,8 @@ class DocumentationManifest {
* @param string $basename
* @param string $path
*/
protected function addPage($page, $basename, $path) {
protected function addPage($page, $basename, $path)
{
$link = $this->stripLinkBase($page->Link());
$this->pages[$link] = array(
@ -406,7 +419,8 @@ class DocumentationManifest {
* @param string $from
* @param string $to
*/
protected function addRedirect($from, $to) {
protected function addRedirect($from, $to)
{
$fromLink = $this->stripLinkBase($from);
$toLink = $this->stripLinkBase($to);
$this->redirects[$fromLink] = $toLink;
@ -415,7 +429,8 @@ class DocumentationManifest {
/**
*
*/
public function handleFolder($basename, $path, $depth) {
public function handleFolder($basename, $path, $depth)
{
$folder = Injector::inst()->create(
'DocumentationFolder', $this->entity, $basename, $path
);
@ -426,7 +441,7 @@ class DocumentationManifest {
// Add alternative link
$shortLink = $folder->Link(true);
if($shortLink != $fullLink) {
if ($shortLink != $fullLink) {
$this->addRedirect($shortLink, $fullLink);
}
}
@ -443,7 +458,8 @@ class DocumentationManifest {
* @param string $path
* @param int $depth
*/
public function handleFile($basename, $path, $depth) {
public function handleFile($basename, $path, $depth)
{
$page = Injector::inst()->create(
'DocumentationPage',
$this->entity, $basename, $path
@ -458,7 +474,7 @@ class DocumentationManifest {
// If this is a stable version, add the short link
$shortLink = $page->Link(true);
if($fullLink != $shortLink) {
if ($fullLink != $shortLink) {
$this->addRedirect($shortLink, $fullLink);
}
}
@ -471,7 +487,8 @@ class DocumentationManifest {
*
* @return ArrayList
*/
public function generateBreadcrumbs($record, $base) {
public function generateBreadcrumbs($record, $base)
{
$output = new ArrayList();
$parts = explode('/', trim($record->getRelativeLink(), '/'));
@ -484,8 +501,8 @@ class DocumentationManifest {
$progress = $base->Link();
foreach($parts as $part) {
if($part) {
foreach ($parts as $part) {
if ($part) {
$progress = Controller::join_links($progress, $part, '/');
$output->push(new ArrayData(array(
@ -509,21 +526,22 @@ class DocumentationManifest {
*
* @return ArrayData
*/
public function getNextPage($filepath, $entityBase) {
public function getNextPage($filepath, $entityBase)
{
$grabNext = false;
$fallback = null;
foreach($this->getPages() as $url => $page) {
if($grabNext && strpos($page['filepath'], $entityBase) !== false) {
foreach ($this->getPages() as $url => $page) {
if ($grabNext && strpos($page['filepath'], $entityBase) !== false) {
return new ArrayData(array(
'Link' => $url,
'Title' => $page['title']
));
}
if($filepath == $page['filepath']) {
if ($filepath == $page['filepath']) {
$grabNext = true;
} else if(!$fallback && strpos($page['filepath'], $filepath) !== false) {
} elseif (!$fallback && strpos($page['filepath'], $filepath) !== false) {
$fallback = new ArrayData(array(
'Link' => $url,
'Title' => $page['title'],
@ -532,7 +550,7 @@ class DocumentationManifest {
}
}
if(!$grabNext) {
if (!$grabNext) {
return $fallback;
}
@ -550,12 +568,13 @@ class DocumentationManifest {
*
* @return ArrayData
*/
public function getPreviousPage($filepath, $entityPath) {
public function getPreviousPage($filepath, $entityPath)
{
$previousUrl = $previousPage = null;
foreach($this->getPages() as $url => $page) {
if($filepath == $page['filepath']) {
if($previousUrl) {
foreach ($this->getPages() as $url => $page) {
if ($filepath == $page['filepath']) {
if ($previousUrl) {
return new ArrayData(array(
'Link' => $previousUrl,
'Title' => $previousPage['title']
@ -563,7 +582,7 @@ class DocumentationManifest {
}
}
if(strpos($page['filepath'], $entityPath) !== false) {
if (strpos($page['filepath'], $entityPath) !== false) {
$previousUrl = $url;
$previousPage = $page;
}
@ -577,11 +596,12 @@ class DocumentationManifest {
*
* @return string
*/
public function normalizeUrl($url) {
public function normalizeUrl($url)
{
$url = trim($url, '/') .'/';
// if the page is the index page then hide it from the menu
if(strpos(strtolower($url), '/index.md/')) {
if (strpos(strtolower($url), '/index.md/')) {
$url = substr($url, 0, strpos($url, "index.md/"));
}
@ -597,8 +617,9 @@ class DocumentationManifest {
*
* @return ArrayList
*/
public function getChildrenFor($entityPath, $recordPath = null) {
if(!$recordPath) {
public function getChildrenFor($entityPath, $recordPath = null)
{
if (!$recordPath) {
$recordPath = $entityPath;
}
@ -606,35 +627,33 @@ class DocumentationManifest {
$base = Config::inst()->get('DocumentationViewer', 'link_base');
$entityPath = $this->normalizeUrl($entityPath);
$recordPath = $this->normalizeUrl($recordPath);
$recordParts = explode(DIRECTORY_SEPARATOR, trim($recordPath,'/'));
$recordParts = explode(DIRECTORY_SEPARATOR, trim($recordPath, '/'));
$currentRecordPath = end($recordParts);
$depth = substr_count($entityPath, '/');
foreach($this->getPages() as $url => $page) {
foreach ($this->getPages() as $url => $page) {
$pagePath = $this->normalizeUrl($page['filepath']);
// check to see if this page is under the given path
if(strpos($pagePath, $entityPath) === false) {
if (strpos($pagePath, $entityPath) === false) {
continue;
}
// only pull it up if it's one more level depth
if(substr_count($pagePath, DIRECTORY_SEPARATOR) == ($depth + 1)) {
$pagePathParts = explode(DIRECTORY_SEPARATOR, trim($pagePath,'/'));
if (substr_count($pagePath, DIRECTORY_SEPARATOR) == ($depth + 1)) {
$pagePathParts = explode(DIRECTORY_SEPARATOR, trim($pagePath, '/'));
$currentPagePath = end($pagePathParts);
if($currentPagePath == $currentRecordPath) {
if ($currentPagePath == $currentRecordPath) {
$mode = 'current';
}
else if(strpos($recordPath, $pagePath) !== false) {
} elseif (strpos($recordPath, $pagePath) !== false) {
$mode = 'section';
}
else {
} else {
$mode = 'link';
}
$children = new ArrayList();
if($mode == 'section' || $mode == 'current') {
if ($mode == 'section' || $mode == 'current') {
$children = $this->getChildrenFor($pagePath, $recordPath);
}
@ -656,12 +675,13 @@ class DocumentationManifest {
*
* @return ArrayList
*/
public function getAllVersionsOfEntity(DocumentationEntity $entity) {
public function getAllVersionsOfEntity(DocumentationEntity $entity)
{
$all = new ArrayList();
foreach($this->getEntities() as $check) {
if($check->getKey() == $entity->getKey()) {
if($check->getLanguage() == $entity->getLanguage()) {
foreach ($this->getEntities() as $check) {
if ($check->getKey() == $entity->getKey()) {
if ($check->getLanguage() == $entity->getLanguage()) {
$all->push($check);
}
}
@ -675,11 +695,12 @@ class DocumentationManifest {
*
* @return DocumentationEntity
*/
public function getStableVersion(DocumentationEntity $entity) {
foreach($this->getEntities() as $check) {
if($check->getKey() == $entity->getKey()) {
if($check->getLanguage() == $entity->getLanguage()) {
if($check->getIsStable()) {
public function getStableVersion(DocumentationEntity $entity)
{
foreach ($this->getEntities() as $check) {
if ($check->getKey() == $entity->getKey()) {
if ($check->getLanguage() == $entity->getLanguage()) {
if ($check->getIsStable()) {
return $check;
}
}
@ -694,16 +715,17 @@ class DocumentationManifest {
*
* @return ArrayList
*/
public function getVersions($entity) {
if(!$entity) {
public function getVersions($entity)
{
if (!$entity) {
return null;
}
$output = new ArrayList();
foreach($this->getEntities() as $check) {
if($check->getKey() == $entity->getKey()) {
if($check->getLanguage() == $entity->getLanguage()) {
foreach ($this->getEntities() as $check) {
if ($check->getKey() == $entity->getKey()) {
if ($check->getLanguage() == $entity->getLanguage()) {
$same = ($check->getVersion() == $entity->getVersion());
$output->push(new ArrayData(array(
@ -712,7 +734,6 @@ class DocumentationManifest {
'LinkingMode' => ($same) ? 'current' : 'link',
'IsStable' => $check->getIsStable()
)));
}
}
}
@ -723,11 +744,12 @@ class DocumentationManifest {
/**
* Returns a sorted array of all the unique versions registered
*/
public function getAllVersions() {
public function getAllVersions()
{
$versions = array();
foreach($this->getEntities() as $entity) {
if($entity->getVersion()) {
foreach ($this->getEntities() as $entity) {
if ($entity->getVersion()) {
$versions[$entity->getVersion()] = $entity->getVersion();
} else {
$versions['0.0'] = _t('DocumentationManifest.MASTER', 'Master');

View File

@ -1,7 +1,7 @@
<?php
class DocumentationManifestFileFinder extends SS_FileFinder {
class DocumentationManifestFileFinder extends SS_FileFinder
{
/**
* @var array
*/
@ -23,16 +23,16 @@ class DocumentationManifestFileFinder extends SS_FileFinder {
/**
*
*/
public function acceptDir($basename, $pathname, $depth) {
public function acceptDir($basename, $pathname, $depth)
{
$ignored = Config::inst()->get('DocumentationManifestFileFinder', 'ignored_files');
if($ignored) {
if(in_array(strtolower($basename), $ignored)) {
if ($ignored) {
if (in_array(strtolower($basename), $ignored)) {
return false;
}
}
return true;
}
}

View File

@ -7,8 +7,8 @@
*
* @package docsviewer
*/
class DocumentationParser {
class DocumentationParser
{
const CODE_BLOCK_BACKTICK = 1;
const CODE_BLOCK_COLON = 2;
@ -41,8 +41,9 @@ class DocumentationParser {
*
* @return String
*/
public static function parse(DocumentationPage $page, $baselink = null) {
if(!$page || (!$page instanceof DocumentationPage)) {
public static function parse(DocumentationPage $page, $baselink = null)
{
if (!$page || (!$page instanceof DocumentationPage)) {
return false;
}
@ -65,7 +66,8 @@ class DocumentationParser {
return $text;
}
public static function rewrite_code_blocks($md) {
public static function rewrite_code_blocks($md)
{
$started = false;
$inner = false;
$mode = false;
@ -75,74 +77,88 @@ class DocumentationParser {
$lines = explode("\n", $md);
$output = array();
foreach($lines as $i => $line) {
if($debug) var_dump('Line '. ($i + 1) . ' '. $line);
foreach ($lines as $i => $line) {
if ($debug) {
var_dump('Line '. ($i + 1) . ' '. $line);
}
// if line just contains whitespace, continue down the page.
// Prevents code blocks with leading tabs adding an extra line.
if(preg_match('/^\s$/', $line) && !$started) {
if (preg_match('/^\s$/', $line) && !$started) {
continue;
}
if(!$started && preg_match('/^[\t]*:::\s*(.*)/', $line, $matches)) {
if (!$started && preg_match('/^[\t]*:::\s*(.*)/', $line, $matches)) {
// first line with custom formatting
if($debug) var_dump('Starts a new block with :::');
if ($debug) {
var_dump('Starts a new block with :::');
}
$started = true;
$mode = self::CODE_BLOCK_COLON;
$output[$i] = sprintf('```%s', (isset($matches[1])) ? trim($matches[1]) : "");
} else if(!$started && preg_match('/^\t*```\s*(.*)/', $line, $matches)) {
if($debug) var_dump('Starts a new block with ```');
} elseif (!$started && preg_match('/^\t*```\s*(.*)/', $line, $matches)) {
if ($debug) {
var_dump('Starts a new block with ```');
}
$started = true;
$mode = self::CODE_BLOCK_BACKTICK;
$output[$i] = sprintf('```%s', (isset($matches[1])) ? trim($matches[1]) : "");
} else if($started && $mode == self::CODE_BLOCK_BACKTICK) {
} elseif ($started && $mode == self::CODE_BLOCK_BACKTICK) {
// inside a backtick fenced box
if(preg_match('/^\t*```\s*/', $line, $matches)) {
if($debug) var_dump('End a block with ```');
if (preg_match('/^\t*```\s*/', $line, $matches)) {
if ($debug) {
var_dump('End a block with ```');
}
// end of the backtick fenced box. Unset the line that contains the backticks
$end = true;
} else {
if ($debug) {
var_dump('Still in a block with ```');
}
else {
if($debug) var_dump('Still in a block with ```');
// still inside the line.
if(!$started) {
if (!$started) {
$output[$i - 1] = '```';
}
$output[$i] = $line;
$inner = true;
}
} else if(preg_match('/^[\ ]{0,3}?[\t](.*)/', $line, $matches)) {
} elseif (preg_match('/^[\ ]{0,3}?[\t](.*)/', $line, $matches)) {
// inner line of block, or first line of standard markdown code block
// regex removes first tab (any following tabs are part of the code).
if(!$started) {
if($debug) var_dump('Start code block because of tab. No fence');
if (!$started) {
if ($debug) {
var_dump('Start code block because of tab. No fence');
}
$output[$i - 1] = '```';
} else {
if($debug) var_dump('Content is still tabbed so still inner');
if ($debug) {
var_dump('Content is still tabbed so still inner');
}
}
$output[$i] = $matches[1];
$inner = true;
$started = true;
} else if($started && $inner && trim($line) === "") {
if($debug) var_dump('Inner line of code block');
} elseif ($started && $inner && trim($line) === "") {
if ($debug) {
var_dump('Inner line of code block');
}
// still inside a colon based block, if the line is only whitespace
// then continue with with it. We can continue with it for now as
// it'll be tidied up later in the $end section.
$inner = true;
$output[$i] = $line;
} else if($started && $inner) {
} elseif ($started && $inner) {
// line contains something other than whitespace, or tabbed. E.g
// > code
// > \n
@ -152,7 +168,7 @@ class DocumentationParser {
// and include this line. The edge case where this will fail is
// new the following segment contains a code block as well as it
// will not open.
if($debug) {
if ($debug) {
var_dump('Contains something that isnt code. So end the code.');
}
@ -163,8 +179,10 @@ class DocumentationParser {
$output[$i] = $line;
}
if($end) {
if($debug) var_dump('End of code block');
if ($end) {
if ($debug) {
var_dump('End of code block');
}
$output = self::finalize_code_output($i, $output);
// reset state
@ -172,12 +190,11 @@ class DocumentationParser {
}
}
if($started) {
if ($started) {
$output = self::finalize_code_output($i+1, $output);
}
return implode("\n", $output);
}
/**
@ -188,18 +205,19 @@ class DocumentationParser {
*
* @return array
*/
private static function finalize_code_output($i, $output) {
if(isset($output[$i]) && trim($output[$i])) {
private static function finalize_code_output($i, $output)
{
if (isset($output[$i]) && trim($output[$i])) {
$output[$i] .= "\n```\n";
}
else {
} else {
$output[$i] = "```";
}
return $output;
}
public static function rewrite_image_links($md, $page) {
public static function rewrite_image_links($md, $page)
{
// Links with titles
$re = '/
!
@ -212,15 +230,15 @@ class DocumentationParser {
/x';
preg_match_all($re, $md, $images);
if($images) {
foreach($images[0] as $i => $match) {
if ($images) {
foreach ($images[0] as $i => $match) {
$title = $images[1][$i];
$url = $images[2][$i];
// Don't process absolute links (based on protocol detection)
$urlParts = parse_url($url);
if($urlParts && isset($urlParts['scheme'])) {
if ($urlParts && isset($urlParts['scheme'])) {
continue;
}
@ -230,7 +248,7 @@ class DocumentationParser {
);
// if the image starts with a slash, it's absolute
if(substr($url, 0, 1) == '/') {
if (substr($url, 0, 1) == '/') {
$relativeUrl = str_replace(BASE_PATH, '', Controller::join_links(
$page->getEntity()->getPath(),
$url
@ -240,7 +258,7 @@ class DocumentationParser {
}
// Resolve relative paths
while(strpos($relativeUrl, '/..') !== FALSE) {
while (strpos($relativeUrl, '/..') !== false) {
$relativeUrl = preg_replace('/\w+\/\.\.\//', '', $relativeUrl);
}
@ -278,7 +296,8 @@ class DocumentationParser {
* @param DocumentationPage $page
* @return String
*/
public static function rewrite_api_links($md, $page) {
public static function rewrite_api_links($md, $page)
{
// Links with titles
$re = '/
`?
@ -291,8 +310,8 @@ class DocumentationParser {
`?
/x';
preg_match_all($re, $md, $linksWithTitles);
if($linksWithTitles) {
foreach($linksWithTitles[0] as $i => $match) {
if ($linksWithTitles) {
foreach ($linksWithTitles[0] as $i => $match) {
$title = $linksWithTitles[1][$i];
$subject = $linksWithTitles[2][$i];
@ -320,8 +339,8 @@ class DocumentationParser {
`?
/x';
preg_match_all($re, $md, $links);
if($links) {
foreach($links[0] as $i => $match) {
if ($links) {
foreach ($links[0] as $i => $match) {
$subject = $links[1][$i];
$url = sprintf(
self::$api_link_base,
@ -344,7 +363,8 @@ class DocumentationParser {
/**
*
*/
public static function rewrite_heading_anchors($md, $page) {
public static function rewrite_heading_anchors($md, $page)
{
$re = '/^\#+(.*)/m';
$md = preg_replace_callback($re, array('DocumentationParser', '_rewrite_heading_anchors_callback'), $md);
@ -354,16 +374,18 @@ class DocumentationParser {
/**
*
*/
public static function _rewrite_heading_anchors_callback($matches) {
public static function _rewrite_heading_anchors_callback($matches)
{
$heading = $matches[0];
$headingText = $matches[1];
if(preg_match('/\{\#.*\}/', $headingText)) return $heading;
if(!isset(self::$heading_counts[$headingText])) {
self::$heading_counts[$headingText] = 1;
if (preg_match('/\{\#.*\}/', $headingText)) {
return $heading;
}
else {
if (!isset(self::$heading_counts[$headingText])) {
self::$heading_counts[$headingText] = 1;
} else {
self::$heading_counts[$headingText]++;
$headingText .= "-" . self::$heading_counts[$headingText];
}
@ -376,12 +398,13 @@ class DocumentationParser {
*
* @return String
*/
public static function generate_html_id($title) {
public static function generate_html_id($title)
{
$t = $title;
$t = str_replace('&amp;','-and-',$t);
$t = str_replace('&','-and-',$t);
$t = preg_replace('/[^A-Za-z0-9]+/','-',$t);
$t = preg_replace('/-+/','-',$t);
$t = str_replace('&amp;', '-and-', $t);
$t = str_replace('&', '-and-', $t);
$t = preg_replace('/[^A-Za-z0-9]+/', '-', $t);
$t = preg_replace('/-+/', '-', $t);
$t = trim($t, '-');
$t = strtolower($t);
@ -396,7 +419,8 @@ class DocumentationParser {
*
* @return String Markdown
*/
public static function rewrite_relative_links($md, $page) {
public static function rewrite_relative_links($md, $page)
{
$baselink = $page->getEntity()->Link();
$re = '/
@ -414,46 +438,49 @@ class DocumentationParser {
// For "sapphire/en/current/topics/templates", this would be "templates"
$relativePath = dirname($page->getRelativePath());
if(strpos($page->getRelativePath(), 'index.md')) {
if (strpos($page->getRelativePath(), 'index.md')) {
$relativeLink = $page->getRelativeLink();
} else {
$relativeLink = dirname($page->getRelativeLink());
}
if($relativePath == '.') {
if ($relativePath == '.') {
$relativePath = '';
}
if($relativeLink == ".") {
if ($relativeLink == ".") {
$relativeLink = '';
}
// file base link
$fileBaseLink = Director::makeRelative(dirname($page->getPath()));
if($matches) {
foreach($matches[0] as $i => $match) {
if ($matches) {
foreach ($matches[0] as $i => $match) {
$title = $matches[2][$i];
$url = $matches[3][$i];
// Don't process API links
if(preg_match('/^api:/', $url)) continue;
if (preg_match('/^api:/', $url)) {
continue;
}
// Don't process absolute links (based on protocol detection)
$urlParts = parse_url($url);
if($urlParts && isset($urlParts['scheme'])) continue;
if ($urlParts && isset($urlParts['scheme'])) {
continue;
}
// for images we need to use the file base path
if(preg_match('/_images/', $url)) {
if (preg_match('/_images/', $url)) {
$relativeUrl = Controller::join_links(
Director::absoluteBaseURL(),
$fileBaseLink,
$url
);
}
else {
} else {
// Rewrite public URL
if(preg_match('/^\//', $url)) {
if (preg_match('/^\//', $url)) {
// Absolute: Only path to module base
$relativeUrl = Controller::join_links($baselink, $url, '/');
} else {
@ -463,7 +490,7 @@ class DocumentationParser {
}
// Resolve relative paths
while(strpos($relativeUrl, '..') !== FALSE) {
while (strpos($relativeUrl, '..') !== false) {
$relativeUrl = preg_replace('/[-\w]+\/\.\.\//', '', $relativeUrl);
}
@ -487,17 +514,18 @@ class DocumentationParser {
*
* @param DocumentationPage
*/
public static function retrieve_meta_data(DocumentationPage &$page) {
if($md = $page->getMarkdown()) {
public static function retrieve_meta_data(DocumentationPage &$page)
{
if ($md = $page->getMarkdown()) {
$matches = preg_match_all('/
(?<key>[A-Za-z0-9_-]+):
\s*
(?<value>.*)
/x', $md, $meta);
if($matches) {
foreach($meta['key'] as $index => $key) {
if(isset($meta['value'][$index])) {
if ($matches) {
foreach ($meta['key'] as $index => $key) {
if (isset($meta['value'][$index])) {
$page->setMetaData($key, $meta['value'][$index]);
}
}

View File

@ -9,8 +9,8 @@
* @package docsviewer
*/
class DocumentationPermalinks {
class DocumentationPermalinks
{
/**
* @var array
*/
@ -30,11 +30,11 @@ class DocumentationPermalinks {
*
* @param array
*/
public static function add($map = array()) {
if(ArrayLib::is_associative($map)) {
public static function add($map = array())
{
if (ArrayLib::is_associative($map)) {
self::$mapping = array_merge(self::$mapping, $map);
}
else {
} else {
user_error("DocumentationPermalinks::add() requires an associative array", E_USER_ERROR);
}
}
@ -44,7 +44,8 @@ class DocumentationPermalinks {
*
* @return string|false
*/
public static function map($url) {
public static function map($url)
{
return (isset(self::$mapping[$url])) ? self::$mapping[$url] : false;
}
}

View File

@ -31,8 +31,8 @@ require_once 'Zend/Search/Lucene.php';
* @package docsviewer
*/
class DocumentationSearch {
class DocumentationSearch
{
/**
* @var bool - Is search enabled
*/
@ -82,11 +82,13 @@ class DocumentationSearch {
*/
private $modules, $versions;
public function setModules($modules) {
public function setModules($modules)
{
$this->modules = $modules;
}
public function setVersions($versions) {
public function setVersions($versions)
{
$this->versions = $versions;
}
@ -95,7 +97,8 @@ class DocumentationSearch {
*
* @param string
*/
public function setQuery($query) {
public function setQuery($query)
{
$this->query = $query;
}
@ -104,7 +107,8 @@ class DocumentationSearch {
*
* @return string
*/
public function getQuery() {
public function getQuery()
{
return $this->query;
}
@ -114,7 +118,8 @@ class DocumentationSearch {
*
* @param Controller
*/
public function setOutputController($controller) {
public function setOutputController($controller)
{
$this->outputController = $controller;
}
@ -129,10 +134,11 @@ class DocumentationSearch {
/**
* @return string
*/
public static function get_index_location() {
public static function get_index_location()
{
$location = Config::inst()->get('DocumentationSearch', 'index_location');
if(!$location) {
if (!$location) {
return Controller::join_links(TEMP_FOLDER, 'RebuildLuceneDocsIndex');
}
@ -142,8 +148,8 @@ class DocumentationSearch {
/**
* Perform a search query on the index
*/
public function performSearch() {
public function performSearch()
{
try {
$index = Zend_Search_Lucene::open(self::get_index_location());
@ -153,20 +159,20 @@ class DocumentationSearch {
$term = Zend_Search_Lucene_Search_QueryParser::parse($this->getQuery());
$query->addSubquery($term, true);
if($this->modules) {
if ($this->modules) {
$moduleQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach($this->modules as $module) {
foreach ($this->modules as $module) {
$moduleQuery->addTerm(new Zend_Search_Lucene_Index_Term($module, 'Entity'));
}
$query->addSubquery($moduleQuery, true);
}
if($this->versions) {
if ($this->versions) {
$versionQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach($this->versions as $version) {
foreach ($this->versions as $version) {
$versionQuery->addTerm(new Zend_Search_Lucene_Index_Term($version, 'Version'));
}
@ -178,8 +184,7 @@ class DocumentationSearch {
$this->results = $index->find($query);
error_reporting($er);
$this->totalResults = $index->numDocs();
}
catch(Zend_Search_Lucene_Exception $e) {
} catch (Zend_Search_Lucene_Exception $e) {
user_error($e .'. Ensure you have run the rebuld task (/dev/tasks/RebuildLuceneDocsIndex)', E_USER_ERROR);
}
}
@ -187,7 +192,8 @@ class DocumentationSearch {
/**
* @return ArrayData
*/
public function getSearchResults($request) {
public function getSearchResults($request)
{
$pageLength = (isset($_GET['length'])) ? (int) $_GET['length'] : 10;
$data = array(
@ -210,9 +216,9 @@ class DocumentationSearch {
$start = ($request->requestVar('start')) ? (int)$request->requestVar('start') : 0;
$query = ($request->requestVar('q')) ? $request->requestVar('q') : '';
$currentPage = floor( $start / $pageLength ) + 1;
$currentPage = floor($start / $pageLength) + 1;
$totalPages = ceil(count($this->results) / $pageLength );
$totalPages = ceil(count($this->results) / $pageLength);
if ($totalPages == 0) {
$totalPages = 1;
@ -224,9 +230,9 @@ class DocumentationSearch {
$results = new ArrayList();
if($this->results) {
foreach($this->results as $k => $hit) {
if($k < ($currentPage-1)*$pageLength || $k >= ($currentPage*$pageLength)) {
if ($this->results) {
foreach ($this->results as $k => $hit) {
if ($k < ($currentPage-1)*$pageLength || $k >= ($currentPage*$pageLength)) {
continue;
}
@ -237,9 +243,9 @@ class DocumentationSearch {
$obj = new ArrayData(array(
'Title' => DBField::create_field('Varchar', $doc->getFieldValue('Title')),
'BreadcrumbTitle' => DBField::create_field('HTMLText', $doc->getFieldValue('BreadcrumbTitle')),
'Link' => DBField::create_field('Varchar',$doc->getFieldValue('Link')),
'Language' => DBField::create_field('Varchar',$doc->getFieldValue('Language')),
'Version' => DBField::create_field('Varchar',$doc->getFieldValue('Version')),
'Link' => DBField::create_field('Varchar', $doc->getFieldValue('Link')),
'Language' => DBField::create_field('Varchar', $doc->getFieldValue('Language')),
'Version' => DBField::create_field('Varchar', $doc->getFieldValue('Version')),
'Entity' => DBField::create_field('Varchar', $doc->getFieldValue('Entity')),
'Content' => DBField::create_field('HTMLText', $content),
'Score' => $hit->score,
@ -260,21 +266,21 @@ class DocumentationSearch {
$data['EndResult'] = $start + count($results);
// Pagination links
if($currentPage > 1) {
if ($currentPage > 1) {
$data['PrevUrl'] = DBField::create_field('Text',
$this->buildQueryUrl(array('start' => ($currentPage - 2) * $pageLength))
);
}
if($currentPage < $totalPages) {
if ($currentPage < $totalPages) {
$data['NextUrl'] = DBField::create_field('Text',
$this->buildQueryUrl(array('start' => $currentPage * $pageLength))
);
}
if($totalPages > 1) {
if ($totalPages > 1) {
// Always show a certain number of pages at the start
for ( $i = 1; $i <= $totalPages; $i++ ) {
for ($i = 1; $i <= $totalPages; $i++) {
$obj = new DataObject();
$obj->IsEllipsis = false;
$obj->PageNumber = $i;
@ -283,7 +289,9 @@ class DocumentationSearch {
));
$obj->Current = false;
if ( $i == $currentPage ) $obj->Current = true;
if ($i == $currentPage) {
$obj->Current = true;
}
$data['SearchPages']->push($obj);
}
}
@ -296,13 +304,20 @@ class DocumentationSearch {
*
* @return string
*/
private function buildQueryUrl($params) {
private function buildQueryUrl($params)
{
$url = parse_url($_SERVER['REQUEST_URI']);
if ( ! array_key_exists('query', $url) ) $url['query'] = '';
if (! array_key_exists('query', $url)) {
$url['query'] = '';
}
parse_str($url['query'], $url['query']);
if ( ! is_array($url['query']) ) $url['query'] = array();
if (! is_array($url['query'])) {
$url['query'] = array();
}
// Remove 'start parameter if it exists
if ( array_key_exists('start', $url['query']) ) unset( $url['query']['start'] );
if (array_key_exists('start', $url['query'])) {
unset($url['query']['start']);
}
// Add extra parameters from argument
$url['query'] = array_merge($url['query'], $params);
$url['query'] = http_build_query($url['query']);
@ -314,7 +329,8 @@ class DocumentationSearch {
/**
* @return int
*/
public function getTotalResults() {
public function getTotalResults()
{
return (int) $this->totalResults;
}
@ -323,16 +339,20 @@ class DocumentationSearch {
*
* @return void
*/
public function optimizeIndex() {
public function optimizeIndex()
{
$index = Zend_Search_Lucene::open(self::get_index_location());
if($index) $index->optimize();
if ($index) {
$index->optimize();
}
}
/**
* @return String
*/
public function getTitle() {
public function getTitle()
{
return ($this->outputController) ? $this->outputController->Title : _t('DocumentationSearch.SEARCH', 'Search');
}
@ -342,13 +362,13 @@ class DocumentationSearch {
*
* @param array
*/
public static function set_meta_data($data) {
if(is_array($data)) {
foreach($data as $key => $value) {
public static function set_meta_data($data)
{
if (is_array($data)) {
foreach ($data as $key => $value) {
self::$meta_data[strtolower($key)] = $value;
}
}
else {
} else {
user_error("set_meta_data must be passed an array", E_USER_ERROR);
}
}
@ -358,7 +378,8 @@ class DocumentationSearch {
*
* @return array
*/
public static function get_meta_data() {
public static function get_meta_data()
{
$data = self::$meta_data;
$defaults = array(
@ -369,8 +390,10 @@ class DocumentationSearch {
'Author' => 'SilverStripe'
);
foreach($defaults as $key => $value) {
if(isset($data[$key])) $defaults[$key] = $data[$key];
foreach ($defaults as $key => $value) {
if (isset($data[$key])) {
$defaults[$key] = $data[$key];
}
}
return $defaults;
@ -380,12 +403,13 @@ class DocumentationSearch {
* Renders the search results into a template. Either the search results
* template or the Atom feed.
*/
public function renderResults() {
if(!$this->results && $this->query) {
public function renderResults()
{
if (!$this->results && $this->query) {
$this->performSearch();
}
if(!$this->outputController) {
if (!$this->outputController) {
return user_error('Call renderResults() on a DocumentationViewer instance.', E_USER_ERROR);
}
@ -393,7 +417,7 @@ class DocumentationSearch {
$data = $this->getSearchResults($request);
$templates = array('DocumentationViewer_search');
if($request->requestVar('format') && $request->requestVar('format') == "atom") {
if ($request->requestVar('format') && $request->requestVar('format') == "atom") {
// alter the fields for the opensearch xml.
$title = ($title = $this->getTitle()) ? ' - '. $title : "";

View File

@ -7,24 +7,26 @@
* @package docsviewer
*/
class DocumentationOpenSearchController extends Controller {
class DocumentationOpenSearchController extends Controller
{
private static $allowed_actions = array(
'description'
);
public function index() {
public function index()
{
return $this->httpError(404);
}
public function description() {
public function description()
{
$viewer = new DocumentationViewer();
if(!$viewer->canView()) {
if (!$viewer->canView()) {
return Security::permissionFailure($this);
}
if(!Config::inst()->get('DocumentationSearch', 'enabled')) {
if (!Config::inst()->get('DocumentationSearch', 'enabled')) {
return $this->httpError('404');
}

View File

@ -12,8 +12,8 @@
* @package docsviewer
*/
class DocumentationViewer extends Controller {
class DocumentationViewer extends Controller
{
/**
* @var array
*/
@ -82,10 +82,11 @@ class DocumentationViewer extends Controller {
/**
*
*/
public function init() {
public function init()
{
parent::init();
if(!$this->canView()) {
if (!$this->canView()) {
return Security::permissionFailure($this);
}
Requirements::javascript('//use.typekit.net/emt4dhq.js');
@ -111,18 +112,21 @@ class DocumentationViewer extends Controller {
*
* @return bool
*/
public function canView() {
public function canView()
{
return (Director::isDev() || Director::is_cli() ||
!$this->config()->get('check_permission') ||
Permission::check($this->config()->get('check_permission'))
);
}
public function hasAction($action) {
public function hasAction($action)
{
return true;
}
public function checkAccessAction($action) {
public function checkAccessAction($action)
{
return true;
}
@ -136,9 +140,10 @@ class DocumentationViewer extends Controller {
*
* @return SS_HTTPResponse
*/
public function handleAction($request, $action) {
public function handleAction($request, $action)
{
// if we submitted a form, let that pass
if(!$request->isGET()) {
if (!$request->isGET()) {
return parent::handleAction($request, $action);
}
@ -148,7 +153,7 @@ class DocumentationViewer extends Controller {
// If the current request has an extension attached to it, strip that
// off and redirect the user to the page without an extension.
//
if(DocumentationHelper::get_extension($url)) {
if (DocumentationHelper::get_extension($url)) {
$this->response = new SS_HTTPResponse();
$this->response->redirect(
DocumentationHelper::trim_extension_off($url) .'/',
@ -168,19 +173,18 @@ class DocumentationViewer extends Controller {
Config::inst()->get('DocumentationViewer', 'link_base'), '/'
);
if($base && strpos($url, $base) !== false) {
if ($base && strpos($url, $base) !== false) {
$url = substr(
ltrim($url, '/'),
strlen($base)
);
} else {
}
//
// Handle any permanent redirections that the developer has defined.
//
if($link = DocumentationPermalinks::map($url)) {
if ($link = DocumentationPermalinks::map($url)) {
// the first param is a shortcode for a page so redirect the user to
// the short code.
$this->response = new SS_HTTPResponse();
@ -199,16 +203,16 @@ class DocumentationViewer extends Controller {
//
$languages = i18n::get_common_languages();
if(!$lang = $request->param('Lang')) {
if (!$lang = $request->param('Lang')) {
$lang = $request->param('Action');
$action = $request->param('ID');
} else {
$action = $request->param('Action');
}
if(!$lang) {
if (!$lang) {
return $this->redirect($this->Link('en'));
} else if(!isset($languages[$lang])) {
} elseif (!isset($languages[$lang])) {
return $this->httpError(404);
}
@ -216,7 +220,7 @@ class DocumentationViewer extends Controller {
$allowed = $this->config()->allowed_actions;
if(in_array($action, $allowed)) {
if (in_array($action, $allowed)) {
//
// if it's one of the allowed actions such as search or all then the
// URL must be prefixed with one of the allowed languages.
@ -236,7 +240,7 @@ class DocumentationViewer extends Controller {
// return $redirect->redirect($cleaned, 302);
// }
if($record = $this->getManifest()->getPage($url)) {
if ($record = $this->getManifest()->getPage($url)) {
$this->record = $record;
$this->init();
@ -247,11 +251,11 @@ class DocumentationViewer extends Controller {
));
return new SS_HTTPResponse($body, 200);
} else if($redirect = $this->getManifest()->getRedirect($url)) {
} elseif ($redirect = $this->getManifest()->getRedirect($url)) {
$response = new SS_HTTPResponse();
$to = Controller::join_links(Director::baseURL(), $base, $redirect);
return $response->redirect($to, 301);
} else if(!$url || $url == $lang) {
} elseif (!$url || $url == $lang) {
$body = $this->renderWith(array(
"DocumentationViewer_DocumentationFolder",
"DocumentationViewer"
@ -270,7 +274,8 @@ class DocumentationViewer extends Controller {
*
* @return SS_HTTPResponse
*/
public function httpError($status, $message = null) {
public function httpError($status, $message = null)
{
$this->init();
$class = get_class($this);
@ -284,8 +289,9 @@ class DocumentationViewer extends Controller {
/**
* @return DocumentationManifest
*/
public function getManifest() {
if(!$this->manifest) {
public function getManifest()
{
if (!$this->manifest) {
$flush = SapphireTest::is_running_test() || (isset($_GET['flush']));
$this->manifest = new DocumentationManifest($flush);
@ -297,8 +303,9 @@ class DocumentationViewer extends Controller {
/**
* @return string
*/
public function getLanguage() {
if(!$lang = $this->request->param('Lang')) {
public function getLanguage()
{
if (!$lang = $this->request->param('Lang')) {
$lang = $this->request->param('Action');
}
@ -313,24 +320,25 @@ class DocumentationViewer extends Controller {
*
* @return DataObject
*/
public function getMenu() {
public function getMenu()
{
$entities = $this->getManifest()->getEntities();
$output = new ArrayList();
$record = $this->getPage();
$current = $this->getEntity();
foreach($entities as $entity) {
foreach ($entities as $entity) {
$checkLang = $entity->getLanguage();
$checkVers = $entity->getVersion();
// only show entities with the same language or any entity that
// isn't registered under any particular language (auto detected)
if($checkLang && $checkLang !== $this->getLanguage()) {
if ($checkLang && $checkLang !== $this->getLanguage()) {
continue;
}
if($current && $checkVers) {
if($entity->getVersion() !== $current->getVersion()) {
if ($current && $checkVers) {
if ($entity->getVersion() !== $current->getVersion()) {
continue;
}
}
@ -338,7 +346,7 @@ class DocumentationViewer extends Controller {
$mode = 'link';
$children = new ArrayList();
if($entity->hasRecord($record) || $entity->getIsDefaultEntity()) {
if ($entity->hasRecord($record) || $entity->getIsDefaultEntity()) {
$mode = 'current';
// add children
@ -346,7 +354,7 @@ class DocumentationViewer extends Controller {
$entity->getPath(), ($record) ? $record->getPath() : $entity->getPath()
);
} else {
if($current && $current->getKey() == $entity->getKey()) {
if ($current && $current->getKey() == $entity->getKey()) {
continue;
}
}
@ -372,7 +380,8 @@ class DocumentationViewer extends Controller {
*
* @return HTMLText
*/
public function getContent() {
public function getContent()
{
$page = $this->getPage();
$html = $page->getHTML();
$html = $this->replaceChildrenCalls($html);
@ -380,7 +389,8 @@ class DocumentationViewer extends Controller {
return $html;
}
public function replaceChildrenCalls($html) {
public function replaceChildrenCalls($html)
{
$codes = new ShortcodeParser();
$codes->register('CHILDREN', array($this, 'includeChildren'));
@ -390,8 +400,9 @@ class DocumentationViewer extends Controller {
/**
* Short code parser
*/
public function includeChildren($args) {
if(isset($args['Folder'])) {
public function includeChildren($args)
{
if (isset($args['Folder'])) {
$children = $this->getManifest()->getChildrenFor(
Controller::join_links(dirname($this->record->getPath()), $args['Folder'])
);
@ -401,12 +412,12 @@ class DocumentationViewer extends Controller {
);
}
if(isset($args['Exclude'])) {
if (isset($args['Exclude'])) {
$exclude = explode(',', $args['Exclude']);
foreach($children as $k => $child) {
foreach($exclude as $e) {
if($child->Link == Controller::join_links($this->record->Link(), strtolower($e), '/')) {
foreach ($children as $k => $child) {
foreach ($exclude as $e) {
if ($child->Link == Controller::join_links($this->record->Link(), strtolower($e), '/')) {
unset($children[$k]);
}
}
@ -421,12 +432,13 @@ class DocumentationViewer extends Controller {
/**
* @return ArrayList
*/
public function getChildren() {
if($this->record instanceof DocumentationFolder) {
public function getChildren()
{
if ($this->record instanceof DocumentationFolder) {
return $this->getManifest()->getChildrenFor(
$this->record->getPath()
);
} else if($this->record) {
} elseif ($this->record) {
return $this->getManifest()->getChildrenFor(
dirname($this->record->getPath())
);
@ -440,8 +452,9 @@ class DocumentationViewer extends Controller {
*
* @return ArrayList
*/
public function getBreadcrumbs() {
if($this->record) {
public function getBreadcrumbs()
{
if ($this->record) {
return $this->getManifest()->generateBreadcrumbs(
$this->record,
$this->record->getEntity()
@ -452,21 +465,24 @@ class DocumentationViewer extends Controller {
/**
* @return DocumentationPage
*/
public function getPage() {
public function getPage()
{
return $this->record;
}
/**
* @return DocumentationEntity
*/
public function getEntity() {
public function getEntity()
{
return ($this->record) ? $this->record->getEntity() : null;
}
/**
* @return ArrayList
*/
public function getVersions() {
public function getVersions()
{
return $this->getManifest()->getVersions($this->getEntity());
}
@ -475,14 +491,16 @@ class DocumentationViewer extends Controller {
*
* @return string
*/
public function getTitle() {
public function getTitle()
{
return ($this->record) ? $this->record->getTitle() : null;
}
/**
* @return string
*/
public function AbsoluteLink($action) {
public function AbsoluteLink($action)
{
return Controller::join_links(
Director::absoluteBaseUrl(),
$this->Link($action)
@ -494,7 +512,8 @@ class DocumentationViewer extends Controller {
*
* @return string
*/
public function Link($action = '') {
public function Link($action = '')
{
$link = Controller::join_links(
Config::inst()->get('DocumentationViewer', 'link_base'),
$this->getLanguage(),
@ -511,14 +530,15 @@ class DocumentationViewer extends Controller {
*
* @return GroupedList
*/
public function AllPages() {
public function AllPages()
{
$pages = $this->getManifest()->getPages();
$output = new ArrayList();
foreach($pages as $url => $page) {
foreach ($pages as $url => $page) {
$first = strtoupper(trim(substr($page['title'], 0, 1)));
if($first) {
if ($first) {
$output->push(new ArrayData(array(
'Link' => $url,
'Title' => $page['title'],
@ -536,8 +556,9 @@ class DocumentationViewer extends Controller {
*
* @return Form
*/
public function DocumentationSearchForm() {
if(!Config::inst()->get('DocumentationSearch','enabled')) {
public function DocumentationSearchForm()
{
if (!Config::inst()->get('DocumentationSearch', 'enabled')) {
return false;
}
@ -568,7 +589,8 @@ class DocumentationViewer extends Controller {
* @param string link
* @param array options ('rewritetrunktomaster')
*/
public static function set_edit_link($module, $link, $options = array()) {
public static function set_edit_link($module, $link, $options = array())
{
self::$edit_links[$module] = array(
'url' => $link,
'options' => $options
@ -580,29 +602,28 @@ class DocumentationViewer extends Controller {
*
* @return string
*/
public function getEditLink() {
public function getEditLink()
{
$page = $this->getPage();
if($page) {
if ($page) {
$entity = $page->getEntity();
if($entity && isset(self::$edit_links[strtolower($entity->title)])) {
if ($entity && isset(self::$edit_links[strtolower($entity->title)])) {
// build the edit link, using the version defined
$url = self::$edit_links[strtolower($entity->title)];
$version = $entity->getVersion();
if($entity->getBranch()){
if ($entity->getBranch()) {
$version = $entity->getBranch();
}
if($version == "trunk" && (isset($url['options']['rewritetrunktomaster']))) {
if($url['options']['rewritetrunktomaster']) {
if ($version == "trunk" && (isset($url['options']['rewritetrunktomaster']))) {
if ($url['options']['rewritetrunktomaster']) {
$version = "master";
}
}
@ -632,7 +653,8 @@ class DocumentationViewer extends Controller {
*
* @return DocumentationPage
*/
public function getNextPage() {
public function getNextPage()
{
return ($this->record)
? $this->getManifest()->getNextPage(
$this->record->getPath(), $this->getEntity()->getPath())
@ -645,7 +667,8 @@ class DocumentationViewer extends Controller {
*
* @return DocumentationPage
*/
public function getPreviousPage() {
public function getPreviousPage()
{
return ($this->record)
? $this->getManifest()->getPreviousPage(
$this->record->getPath(), $this->getEntity()->getPath())
@ -655,10 +678,11 @@ class DocumentationViewer extends Controller {
/**
* @return string
*/
public function getGoogleAnalyticsCode() {
public function getGoogleAnalyticsCode()
{
$code = $this->config()->get('google_analytics_code');
if($code) {
if ($code) {
return $code;
}
}
@ -666,11 +690,13 @@ class DocumentationViewer extends Controller {
/**
* @return string
*/
public function getDocumentationTitle() {
public function getDocumentationTitle()
{
return $this->config()->get('documentation_title');
}
public function getDocumentationBaseHref() {
public function getDocumentationBaseHref()
{
return Config::inst()->get('DocumentationViewer', 'link_base');
}
}

View File

@ -1,20 +1,20 @@
<?php
class DocumentationSearchExtension extends Extension {
class DocumentationSearchExtension extends Extension
{
/**
* Return an array of folders and titles
*
* @return array
*/
public function getSearchedEntities() {
public function getSearchedEntities()
{
$entities = array();
if(!empty($_REQUEST['Entities'])) {
if(is_array($_REQUEST['Entities'])) {
if (!empty($_REQUEST['Entities'])) {
if (is_array($_REQUEST['Entities'])) {
$entities = Convert::raw2att($_REQUEST['Entities']);
}
else {
} else {
$entities = explode(',', Convert::raw2att($_REQUEST['Entities']));
$entities = array_combine($entities, $entities);
}
@ -28,15 +28,15 @@ class DocumentationSearchExtension extends Extension {
*
* @return array
*/
public function getSearchedVersions() {
public function getSearchedVersions()
{
$versions = array();
if(!empty($_REQUEST['Versions'])) {
if(is_array($_REQUEST['Versions'])) {
if (!empty($_REQUEST['Versions'])) {
if (is_array($_REQUEST['Versions'])) {
$versions = Convert::raw2att($_REQUEST['Versions']);
$versions = array_combine($versions, $versions);
}
else {
} else {
$version = Convert::raw2att($_REQUEST['Versions']);
$versions[$version] = $version;
}
@ -50,10 +50,11 @@ class DocumentationSearchExtension extends Extension {
*
* @return HTMLText|null
*/
public function getSearchQuery() {
if(isset($_REQUEST['Search'])) {
public function getSearchQuery()
{
if (isset($_REQUEST['Search'])) {
return DBField::create_field('HTMLText', $_REQUEST['Search']);
} else if(isset($_REQUEST['q'])) {
} elseif (isset($_REQUEST['q'])) {
return DBField::create_field('HTMLText', $_REQUEST['q']);
}
}
@ -61,7 +62,8 @@ class DocumentationSearchExtension extends Extension {
/**
* Past straight to results, display and encode the query.
*/
public function getSearchResults() {
public function getSearchResults()
{
$query = $this->getSearchQuery();
$search = new DocumentationSearch();
@ -79,15 +81,16 @@ class DocumentationSearchExtension extends Extension {
*
* @return Form
*/
public function AdvancedSearchForm() {
public function AdvancedSearchForm()
{
return new DocumentationAdvancedSearchForm($this->owner);
}
/**
* @return bool
*/
public function getAdvancedSearchEnabled() {
public function getAdvancedSearchEnabled()
{
return Config::inst()->get("DocumentationSearch", 'advanced_search_enabled');
}
}

View File

@ -25,12 +25,13 @@
*
* @package docsviewer
*/
class DocumentationStaticPublisherExtension extends Extension {
public function alterExportUrls(&$urls) {
class DocumentationStaticPublisherExtension extends Extension
{
public function alterExportUrls(&$urls)
{
$manifest = new DocumentationManifest(true);
foreach($manifest->getPages() as $url => $page) {
foreach ($manifest->getPages() as $url => $page) {
$urls[$url] = $url;
}
}

View File

@ -7,37 +7,37 @@
* @return false|ArrayData
*/
class DocumentationViewerVersionWarning extends Extension {
public function VersionWarning() {
class DocumentationViewerVersionWarning extends Extension
{
public function VersionWarning()
{
$page = $this->owner->getPage();
if(!$page) {
if (!$page) {
return false;
}
$entity = $page->getEntity();
if(!$entity) {
if (!$entity) {
return false;
}
$versions = $this->owner->getManifest()->getAllVersionsOfEntity($entity);
if($entity->getIsStable()) {
if ($entity->getIsStable()) {
return false;
}
$stable = $this->owner->getManifest()->getStableVersion($entity);
$compare = $entity->compare($stable);
if($entity->getVersion() == "master" || $compare > 0) {
if ($entity->getVersion() == "master" || $compare > 0) {
return $this->owner->customise(new ArrayData(array(
'FutureRelease' => true,
'StableVersion' => DBField::create_field('HTMLText', $stable->getVersion())
)));
}
else {
} else {
return $this->owner->customise(new ArrayData(array(
'OutdatedRelease' => true,
'StableVersion' => DBField::create_field('HTMLText', $stable->getVersion())

View File

@ -3,9 +3,10 @@
/**
* @package docsviewer
*/
class DocumentationAdvancedSearchForm extends Form {
public function __construct($controller) {
class DocumentationAdvancedSearchForm extends Form
{
public function __construct($controller)
{
$versions = $controller->getManifest()->getAllVersions();
$entities = $controller->getManifest()->getEntities();
@ -17,13 +18,13 @@ class DocumentationAdvancedSearchForm extends Form {
// if we haven't gone any search limit then we're searching everything
$searchedEntities = $controller->getSearchedEntities();
if(count($searchedEntities) < 1) {
if (count($searchedEntities) < 1) {
$searchedEntities = $entities;
}
$searchedVersions = $controller->getSearchedVersions();
if(count($searchedVersions) < 1) {
if (count($searchedVersions) < 1) {
$searchedVersions = $versions;
}

View File

@ -1,10 +1,9 @@
<?php
class DocumentationSearchForm extends Form {
public function __construct($controller) {
class DocumentationSearchForm extends Form
{
public function __construct($controller)
{
$fields = new FieldList(
TextField::create('q', _t('DocumentationViewer.SEARCH', 'Search'), '')
->setAttribute('placeholder', _t('DocumentationViewer.SEARCH', 'Search'))
@ -12,7 +11,7 @@ class DocumentationSearchForm extends Form {
$page = $controller->getPage();
if($page){
if ($page) {
$versions = HiddenField::create(
'Versions',
_t('DocumentationViewer.VERSIONS', 'Versions'),

View File

@ -16,8 +16,8 @@
* @subpackage models
*/
class DocumentationEntity extends ViewableData {
class DocumentationEntity extends ViewableData
{
/**
* The key to match entities with that is not localized. For instance, you
* may have three entities (en, de, fr) that you want to display a nice
@ -79,7 +79,8 @@ class DocumentationEntity extends ViewableData {
/**
*
*/
public function __construct($key) {
public function __construct($key)
{
$this->key = DocumentationHelper::clean_page_url($key);
}
@ -89,8 +90,9 @@ class DocumentationEntity extends ViewableData {
*
* @return string
*/
public function getTitle() {
if(!$this->title) {
public function getTitle()
{
if (!$this->title) {
$this->title = DocumentationHelper::clean_page_name($this->key);
}
@ -101,7 +103,8 @@ class DocumentationEntity extends ViewableData {
* @param string $title
* @return this
*/
public function setTitle($title) {
public function setTitle($title)
{
$this->title = $title;
return $this;
@ -116,8 +119,9 @@ class DocumentationEntity extends ViewableData {
* This might omit the version number if this is the default version.
* @return string
*/
public function Link($short = false) {
if($this->getIsDefaultEntity()) {
public function Link($short = false)
{
if ($this->getIsDefaultEntity()) {
$base = Controller::join_links(
Config::inst()->get('DocumentationViewer', 'link_base'),
$this->getLanguage(),
@ -134,7 +138,7 @@ class DocumentationEntity extends ViewableData {
$base = ltrim(str_replace('//', '/', $base), '/');
if($short && $this->stable) {
if ($short && $this->stable) {
return $base;
}
@ -148,7 +152,8 @@ class DocumentationEntity extends ViewableData {
/**
* @return string
*/
public function __toString() {
public function __toString()
{
return sprintf('DocumentationEntity: %s)', $this->getPath());
}
@ -157,8 +162,9 @@ class DocumentationEntity extends ViewableData {
*
* @return boolean
*/
public function hasRecord($page) {
if(!$page) {
public function hasRecord($page)
{
if (!$page) {
return false;
}
@ -168,7 +174,8 @@ class DocumentationEntity extends ViewableData {
/**
* @param boolean $bool
*/
public function setIsDefaultEntity($bool) {
public function setIsDefaultEntity($bool)
{
$this->defaultEntity = $bool;
return $this;
@ -177,21 +184,24 @@ class DocumentationEntity extends ViewableData {
/**
* @return boolean
*/
public function getIsDefaultEntity() {
public function getIsDefaultEntity()
{
return $this->defaultEntity;
}
/**
* @return string
*/
public function getKey() {
public function getKey()
{
return $this->key;
}
/**
* @return string
*/
public function getLanguage() {
public function getLanguage()
{
return $this->language;
}
@ -200,7 +210,8 @@ class DocumentationEntity extends ViewableData {
*
* @return this
*/
public function setLanguage($language) {
public function setLanguage($language)
{
$this->language = $language;
return $this;
@ -209,7 +220,8 @@ class DocumentationEntity extends ViewableData {
/**
* @param string
*/
public function setVersion($version) {
public function setVersion($version)
{
$this->version = $version;
return $this;
@ -218,14 +230,16 @@ class DocumentationEntity extends ViewableData {
/**
* @return float
*/
public function getVersion() {
public function getVersion()
{
return $this->version;
}
/**
* @param string
*/
public function setBranch($branch) {
public function setBranch($branch)
{
$this->branch = $branch;
return $this;
@ -234,14 +248,16 @@ class DocumentationEntity extends ViewableData {
/**
* @return float
*/
public function getBranch() {
public function getBranch()
{
return $this->branch;
}
/**
* @return string
*/
public function getPath() {
public function getPath()
{
return $this->path;
}
@ -250,7 +266,8 @@ class DocumentationEntity extends ViewableData {
*
* @return this
*/
public function setPath($path) {
public function setPath($path)
{
$this->path = $path;
return $this;
@ -259,7 +276,8 @@ class DocumentationEntity extends ViewableData {
/**
* @param boolean
*/
public function setIsStable($stable) {
public function setIsStable($stable)
{
$this->stable = $stable;
return $this;
@ -268,7 +286,8 @@ class DocumentationEntity extends ViewableData {
/**
* @return boolean
*/
public function getIsStable() {
public function getIsStable()
{
return $this->stable;
}
@ -282,14 +301,16 @@ class DocumentationEntity extends ViewableData {
* @param string $version
* @return int
*/
public function compare(DocumentationEntity $other) {
public function compare(DocumentationEntity $other)
{
return version_compare($this->getVersion(), $other->getVersion());
}
/**
* @return array
*/
public function toMap() {
public function toMap()
{
return array(
'Key' => $this->key,
'Path' => $this->getPath(),

View File

@ -8,13 +8,13 @@
* @package docsviewer
* @subpackage model
*/
class DocumentationFolder extends DocumentationPage {
class DocumentationFolder extends DocumentationPage
{
/**
* @return string
*/
public function getTitle() {
public function getTitle()
{
return $this->getTitleFromFolder();
}
}

View File

@ -10,8 +10,8 @@
* @package docsviewer
* @subpackage model
*/
class DocumentationPage extends ViewableData {
class DocumentationPage extends ViewableData
{
/**
* @var string
*/
@ -41,7 +41,8 @@ class DocumentationPage extends ViewableData {
* @param string $filename
* @param string $path
*/
public function __construct(DocumentationEntity $entity, $filename, $path) {
public function __construct(DocumentationEntity $entity, $filename, $path)
{
$this->filename = $filename;
$this->path = $path;
$this->entity = $entity;
@ -50,7 +51,8 @@ class DocumentationPage extends ViewableData {
/**
* @return string
*/
public function getExtension() {
public function getExtension()
{
return DocumentationHelper::get_extension($this->filename);
}
@ -59,7 +61,8 @@ class DocumentationPage extends ViewableData {
*
* @return string
*/
public function getBreadcrumbTitle($divider = ' - ') {
public function getBreadcrumbTitle($divider = ' - ')
{
$pathParts = explode('/', trim($this->getRelativePath(), '/'));
// from the page from this
@ -72,13 +75,13 @@ class DocumentationPage extends ViewableData {
'DocumentationHelper', 'clean_page_name'
), $pathParts);
$titleParts = array_filter($titleParts, function($val) {
if($val) {
$titleParts = array_filter($titleParts, function ($val) {
if ($val) {
return $val;
}
});
if($this->getTitle()) {
if ($this->getTitle()) {
array_unshift($titleParts, $this->getTitle());
}
@ -88,28 +91,31 @@ class DocumentationPage extends ViewableData {
/**
* @return DocumentationEntity
*/
public function getEntity() {
public function getEntity()
{
return $this->entity;
}
/**
* @return string
*/
public function getTitle() {
if($this->title) {
public function getTitle()
{
if ($this->title) {
return $this->title;
}
$page = DocumentationHelper::clean_page_name($this->filename);
if($page == "Index") {
if ($page == "Index") {
return $this->getTitleFromFolder();
}
return $page;
}
public function getTitleFromFolder() {
public function getTitleFromFolder()
{
$folder = $this->getPath();
$entity = $this->getEntity()->getPath();
@ -117,7 +123,7 @@ class DocumentationPage extends ViewableData {
// if it's the root of the entity then we want to use the entity name
// otherwise we'll get 'En' for the entity folder
if($folder == $entity) {
if ($folder == $entity) {
return $this->getEntity()->getTitle();
} else {
$path = explode(DIRECTORY_SEPARATOR, trim($folder, DIRECTORY_SEPARATOR));
@ -130,7 +136,8 @@ class DocumentationPage extends ViewableData {
/**
* @return string
*/
public function getSummary() {
public function getSummary()
{
return $this->summary;
}
@ -141,7 +148,8 @@ class DocumentationPage extends ViewableData {
*
* @return string
*/
public function getMarkdown($removeMetaData = false) {
public function getMarkdown($removeMetaData = false)
{
try {
if ($md = file_get_contents($this->getPath())) {
$this->populateMetaDataFromText($md, $removeMetaData);
@ -150,22 +158,22 @@ class DocumentationPage extends ViewableData {
}
$this->read = true;
}
catch(InvalidArgumentException $e) {
} catch (InvalidArgumentException $e) {
}
return false;
}
public function setMetaData($key, $value) {
public function setMetaData($key, $value)
{
$key = strtolower($key);
$this->$key = $value;
}
public function getIntroduction() {
if(!$this->read) {
public function getIntroduction()
{
if (!$this->read) {
$this->getMarkdown();
}
@ -179,7 +187,8 @@ class DocumentationPage extends ViewableData {
*
* @return string
*/
public function getHTML() {
public function getHTML()
{
$html = DocumentationParser::parse(
$this,
$this->entity->Link()
@ -195,10 +204,11 @@ class DocumentationPage extends ViewableData {
*
* @return string
*/
public function getRelativeLink() {
public function getRelativeLink()
{
$path = $this->getRelativePath();
$url = explode('/', $path);
$url = implode('/', array_map(function($a) {
$url = implode('/', array_map(function ($a) {
return DocumentationHelper::clean_page_url($a);
}, $url));
@ -213,15 +223,16 @@ class DocumentationPage extends ViewableData {
*
* @return string
*/
public function getRelativePath() {
public function getRelativePath()
{
return str_replace($this->entity->getPath(), '', $this->getPath());
}
/**
* @return string
*/
public function getPath() {
public function getPath()
{
return $this->path;
}
@ -233,7 +244,8 @@ class DocumentationPage extends ViewableData {
* This might omit the version number if this is the default version.
* @return string
*/
public function Link($short = false) {
public function Link($short = false)
{
return ltrim(Controller::join_links(
$this->entity->Link($short),
$this->getRelativeLink()
@ -247,21 +259,22 @@ class DocumentationPage extends ViewableData {
* @param DocumentationPage $md
* @param bool $remove
*/
public function populateMetaDataFromText(&$md, $removeMetaData = false) {
if($md) {
public function populateMetaDataFromText(&$md, $removeMetaData = false)
{
if ($md) {
// get the text up to the first whiteline
$extPattern = "/^(.+)\n(\r)*\n/Uis";
$matches = preg_match($extPattern, $md, $block);
if($matches && $block[1]) {
if ($matches && $block[1]) {
$metaDataFound = false;
// find the key/value pairs
$intPattern = '/(?<key>[A-Za-z][A-Za-z0-9_-]+)[\t]*:[\t]*(?<value>[^:\n\r\/]+)/x';
$matches = preg_match_all($intPattern, $block[1], $meta);
foreach($meta['key'] as $index => $key) {
if(isset($meta['value'][$index])) {
foreach ($meta['key'] as $index => $key) {
if (isset($meta['value'][$index])) {
// check if a property exists for this key
if (property_exists(get_class(), $key)) {
$this->$key = $meta['value'][$index];
@ -279,11 +292,13 @@ class DocumentationPage extends ViewableData {
}
}
public function getVersion() {
public function getVersion()
{
return $this->entity->getVersion();
}
public function __toString() {
public function __toString()
{
return sprintf(get_class($this) .': %s)', $this->getPath());
}
}

View File

@ -1,14 +1,14 @@
<?php
class DocumentationBuild extends BuildTask {
public function run($request) {
class DocumentationBuild extends BuildTask
{
public function run($request)
{
$manifest = new DocumentationManifest(true);
echo "<pre>";
print_r($manifest->getPages());
echo "</pre>";
die();;
die();
;
}
}

View File

@ -9,18 +9,20 @@
* @subpackage tasks
*/
class RebuildLuceneDocsIndex extends BuildTask {
class RebuildLuceneDocsIndex extends BuildTask
{
protected $title = "Rebuild Documentation Search Indexes";
protected $description = "
Rebuilds the indexes used for the search engine in the docsviewer.";
public function run($request) {
public function run($request)
{
$this->rebuildIndexes();
}
public function rebuildIndexes($quiet = false) {
public function rebuildIndexes($quiet = false)
{
require_once 'Zend/Search/Lucene.php';
ini_set("memory_limit", -1);
@ -35,8 +37,8 @@ class RebuildLuceneDocsIndex extends BuildTask {
echo "Building index in ". DocumentationSearch::get_index_location() . PHP_EOL;
if($lockFileFresh && !isset($_REQUEST['flush'])) {
if(!$quiet) {
if ($lockFileFresh && !isset($_REQUEST['flush'])) {
if (!$quiet) {
echo "Index recently rebuilt. If you want to force reindex use ?flush=1";
}
@ -46,15 +48,13 @@ class RebuildLuceneDocsIndex extends BuildTask {
try {
$index = Zend_Search_Lucene::open(DocumentationSearch::get_index_location());
$index->removeReference();
}
catch (Zend_Search_Lucene_Exception $e) {
} catch (Zend_Search_Lucene_Exception $e) {
user_error($e);
}
try {
$index = Zend_Search_Lucene::create(DocumentationSearch::get_index_location());
}
catch(Zend_Search_Lucene_Exception $c) {
} catch (Zend_Search_Lucene_Exception $c) {
user_error($c);
}
@ -62,16 +62,16 @@ class RebuildLuceneDocsIndex extends BuildTask {
$manifest = new DocumentationManifest(true);
$pages = $manifest->getPages();
if($pages) {
if ($pages) {
$count = 0;
// iconv complains about all the markdown formatting
// turn off notices while we parse
if(!Director::is_cli()) {
if (!Director::is_cli()) {
echo "<ul>";
}
foreach($pages as $url => $record) {
foreach ($pages as $url => $record) {
$count++;
$page = $manifest->getPage($url);
@ -107,8 +107,8 @@ class RebuildLuceneDocsIndex extends BuildTask {
$boost = Config::inst()->get('DocumentationSearch', 'boost_by_path');
foreach($boost as $pathExpr => $boost) {
if(preg_match($pathExpr, $page->getRelativePath())) {
foreach ($boost as $pathExpr => $boost) {
if (preg_match($pathExpr, $page->getRelativePath())) {
$doc->boost = $boost;
}
}
@ -116,16 +116,19 @@ class RebuildLuceneDocsIndex extends BuildTask {
error_reporting(E_ALL ^ E_NOTICE);
$index->addDocument($doc);
if(!$quiet) {
if(Director::is_cli()) echo " * adding ". $page->getPath() ."\n";
else echo "<li>adding ". $page->getPath() ."</li>\n";
if (!$quiet) {
if (Director::is_cli()) {
echo " * adding ". $page->getPath() ."\n";
} else {
echo "<li>adding ". $page->getPath() ."</li>\n";
}
}
}
}
$index->commit();
if(!$quiet) {
if (!$quiet) {
echo "complete.";
}
}

View File

@ -4,15 +4,17 @@
* @package docsviewer
* @subpackage tests
*/
class DocumentationHelperTests extends SapphireTest {
public function testCleanName() {
class DocumentationHelperTests extends SapphireTest
{
public function testCleanName()
{
$this->assertEquals("File path", DocumentationHelper::clean_page_name(
'00_file-path.md'
));
}
public function testCleanUrl() {
public function testCleanUrl()
{
$this->assertEquals("some_path", DocumentationHelper::clean_page_url(
'Some Path'
));
@ -22,7 +24,8 @@ class DocumentationHelperTests extends SapphireTest {
));
}
public function testTrimSortNumber() {
public function testTrimSortNumber()
{
$this->assertEquals('file', DocumentationHelper::trim_sort_number(
'0_file'
));
@ -36,7 +39,8 @@ class DocumentationHelperTests extends SapphireTest {
));
}
public function testTrimExtension() {
public function testTrimExtension()
{
$this->assertEquals('file', DocumentationHelper::trim_extension_off(
'file.md'
));
@ -46,7 +50,8 @@ class DocumentationHelperTests extends SapphireTest {
));
}
public function testGetExtension() {
public function testGetExtension()
{
$this->assertEquals('md', DocumentationHelper::get_extension(
'file.md'
));

View File

@ -4,11 +4,12 @@
* @package docsviewer
* @subpackage tests
*/
class DocumentationManifestTests extends SapphireTest {
class DocumentationManifestTests extends SapphireTest
{
private $manifest;
public function setUp() {
public function setUp()
{
parent::setUp();
Config::nest();
@ -57,7 +58,8 @@ class DocumentationManifestTests extends SapphireTest {
$this->manifest = new DocumentationManifest(true);
}
public function tearDown() {
public function tearDown()
{
parent::tearDown();
Config::unnest();
@ -67,7 +69,8 @@ class DocumentationManifestTests extends SapphireTest {
/**
* Check that the manifest matches what we'd expect.
*/
public function testRegenerate() {
public function testRegenerate()
{
$match = array(
'de/testdocs/2.3/',
'de/testdocs/2.3/german/',
@ -100,7 +103,8 @@ class DocumentationManifestTests extends SapphireTest {
$this->assertEquals($match, array_keys($this->manifest->getPages()));
}
public function testGetNextPage() {
public function testGetNextPage()
{
// get next page at the end of one subfolder goes back up to the top
// most directory
$this->assertStringEndsWith('2.3/test/', $this->manifest->getNextPage(
@ -129,7 +133,8 @@ class DocumentationManifestTests extends SapphireTest {
));
}
public function testGetPreviousPage() {
public function testGetPreviousPage()
{
// goes right into subfolders
$this->assertContains('subfolder/subsubfolder/subsubpage', $this->manifest->getPreviousPage(
DOCSVIEWER_PATH . '/tests/docs/en/test.md',
@ -149,15 +154,18 @@ class DocumentationManifestTests extends SapphireTest {
));
}
public function testGetPage() {
public function testGetPage()
{
$this->markTestIncomplete();
}
public function testGenerateBreadcrumbs() {
public function testGenerateBreadcrumbs()
{
$this->markTestIncomplete();
}
public function testGetChildrenFor() {
public function testGetChildrenFor()
{
$expected = array(
array('Title' => 'Test', 'LinkingMode' => 'link')
);
@ -178,7 +186,8 @@ class DocumentationManifestTests extends SapphireTest {
));
}
public function testGetAllVersions() {
public function testGetAllVersions()
{
$expected = array(
'2.3' => '2.3',
'2.4' => '2.4',
@ -189,7 +198,8 @@ class DocumentationManifestTests extends SapphireTest {
$this->assertEquals($expected, $this->manifest->getAllVersions());
}
public function testGetAllEntityVersions() {
public function testGetAllEntityVersions()
{
$expected = array(
'Version' => '2.3',
'Version' => '2.4',
@ -205,7 +215,8 @@ class DocumentationManifestTests extends SapphireTest {
$this->assertEquals(1, $this->manifest->getAllVersionsOfEntity($entity)->count());
}
public function testGetStableVersion() {
public function testGetStableVersion()
{
$this->markTestIncomplete();
}
}

View File

@ -4,11 +4,12 @@
* @package docsviewer
* @subpackage tests
*/
class DocumentationPageTest extends SapphireTest {
class DocumentationPageTest extends SapphireTest
{
protected $entity;
public function setUp() {
public function setUp()
{
parent::setUp();
$this->entity = new DocumentationEntity('doctest');
@ -26,13 +27,15 @@ class DocumentationPageTest extends SapphireTest {
$manifest = new DocumentationManifest(true);
}
public function tearDown() {
public function tearDown()
{
parent::tearDown();
Config::unnest();
}
public function testGetLink() {
public function testGetLink()
{
$page = new DocumentationPage(
$this->entity,
'test.md',
@ -61,7 +64,8 @@ class DocumentationPageTest extends SapphireTest {
$this->assertEquals('dev/docs/en/doctest/2.4/sort/basic/', $page->Link());
}
public function testGetBreadcrumbTitle() {
public function testGetBreadcrumbTitle()
{
$page = new DocumentationPage(
$this->entity,
'test.md',
@ -85,6 +89,5 @@ class DocumentationPageTest extends SapphireTest {
);
$this->assertEquals('Sort - Doctest', $page->getBreadcrumbTitle());
}
}

View File

@ -4,17 +4,19 @@
* @package docsviewer
* @subpackage tests
*/
class DocumentationParserTest extends SapphireTest {
class DocumentationParserTest extends SapphireTest
{
protected $entity, $entityAlt, $page, $subPage, $subSubPage, $filePage, $metaDataPage, $indexPage;
public function tearDown() {
public function tearDown()
{
parent::tearDown();
Config::unnest();
}
public function setUp() {
public function setUp()
{
parent::setUp();
Config::nest();
@ -73,7 +75,8 @@ class DocumentationParserTest extends SapphireTest {
$manifest = new DocumentationManifest(true);
}
public function testRewriteCodeBlocks() {
public function testRewriteCodeBlocks()
{
$codePage = new DocumentationPage(
$this->entityAlt,
'CodeSnippets.md',
@ -161,7 +164,8 @@ HTML;
$this->assertContains($expected, $result, 'Backtick with newlines');
}
public function testRelativeLinks() {
public function testRelativeLinks()
{
// index.md
$result = DocumentationParser::rewrite_relative_links(
$this->indexPage->getMarkdown(),
@ -266,7 +270,8 @@ HTML;
);
}
public function testGenerateHtmlId() {
public function testGenerateHtmlId()
{
$this->assertEquals('title-one', DocumentationParser::generate_html_id('title one'));
$this->assertEquals('title-one', DocumentationParser::generate_html_id('Title one'));
$this->assertEquals('title-and-one', DocumentationParser::generate_html_id('Title &amp; One'));
@ -277,8 +282,8 @@ HTML;
public function testImageRewrites() {
public function testImageRewrites()
{
$result = DocumentationParser::rewrite_image_links(
$this->subPage->getMarkdown(),
$this->subPage
@ -310,7 +315,8 @@ HTML;
);
}
public function testApiLinks() {
public function testApiLinks()
{
$result = DocumentationParser::rewrite_api_links(
$this->page->getMarkdown(),
$this->page
@ -326,7 +332,8 @@ HTML;
);
}
public function testHeadlineAnchors() {
public function testHeadlineAnchors()
{
$result = DocumentationParser::rewrite_heading_anchors(
$this->page->getMarkdown(),
$this->page
@ -357,18 +364,19 @@ HTML;
$this->assertContains('## Heading duplicate {#heading-duplicate}', $result);
$this->assertContains('## Heading duplicate {#heading-duplicate-2}', $result);
$this->assertContains('## Heading duplicate {#heading-duplicate-3}', $result);
}
public function testRetrieveMetaData() {
public function testRetrieveMetaData()
{
DocumentationParser::retrieve_meta_data($this->metaDataPage);
$this->assertEquals('Dr. Foo Bar.', $this->metaDataPage->author);
$this->assertEquals("Foo Bar's Test page.", $this->metaDataPage->getTitle());
}
public function testRewritingRelativeLinksToFiles() {
public function testRewritingRelativeLinksToFiles()
{
$parsed = DocumentationParser::parse($this->filePage);
$this->assertContains(

View File

@ -4,9 +4,10 @@
* @package docsviewer
* @subpackage tests
*/
class DocumentationPermalinksTest extends FunctionalTest {
public function testSavingAndAccessingMapping() {
class DocumentationPermalinksTest extends FunctionalTest
{
public function testSavingAndAccessingMapping()
{
// basic test
DocumentationPermalinks::add(array(
'foo' => 'en/framework/subfolder/foo',
@ -26,7 +27,8 @@ class DocumentationPermalinksTest extends FunctionalTest {
* Tests to make sure short codes get translated to full paths.
*
*/
public function testRedirectingMapping() {
public function testRedirectingMapping()
{
DocumentationPermalinks::add(array(
'foo' => 'en/framework/subfolder/foo',
'bar' => 'en/cms/bar'

View File

@ -5,9 +5,10 @@
* @subpackage tests
*/
class DocumentationSearchTest extends FunctionalTest {
public function setUp() {
class DocumentationSearchTest extends FunctionalTest
{
public function setUp()
{
parent::setUp();
Config::nest();
@ -35,13 +36,15 @@ class DocumentationSearchTest extends FunctionalTest {
$this->manifest = new DocumentationManifest(true);
}
public function tearDown() {
public function tearDown()
{
parent::tearDown();
Config::unnest();
}
public function testOpenSearchControllerAccessible() {
public function testOpenSearchControllerAccessible()
{
$c = new DocumentationOpenSearchController();
$response = $c->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst());
$this->assertEquals(404, $response->getStatusCode());

View File

@ -8,13 +8,14 @@
* @subpackage tests
*/
class DocumentationViewerTest extends FunctionalTest {
class DocumentationViewerTest extends FunctionalTest
{
protected $autoFollowRedirection = false;
protected $manifest;
public function setUp() {
public function setUp()
{
parent::setUp();
Config::nest();
@ -65,7 +66,8 @@ class DocumentationViewerTest extends FunctionalTest {
$this->manifest = new DocumentationManifest(true);
}
public function tearDown() {
public function tearDown()
{
parent::tearDown();
Config::unnest();
@ -74,7 +76,8 @@ class DocumentationViewerTest extends FunctionalTest {
/**
* This tests that all the locations will exist if we access it via the urls.
*/
public function testLocationsExists() {
public function testLocationsExists()
{
$this->autoFollowRedirection = false;
$response = $this->get('dev/docs/en/doc_test/2.3/subfolder/');
@ -141,7 +144,8 @@ class DocumentationViewerTest extends FunctionalTest {
}
public function testGetMenu() {
public function testGetMenu()
{
$v = new DocumentationViewer();
// check with children
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.3/'), DataModel::inst());
@ -174,7 +178,8 @@ class DocumentationViewerTest extends FunctionalTest {
public function testGetLanguage() {
public function testGetLanguage()
{
$v = new DocumentationViewer();
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.3/'), DataModel::inst());
@ -185,7 +190,8 @@ class DocumentationViewerTest extends FunctionalTest {
}
public function testAccessingAll() {
public function testAccessingAll()
{
$response = $this->get('dev/docs/en/all/');
// should response with the documentation index
@ -210,6 +216,5 @@ class DocumentationViewerTest extends FunctionalTest {
// accessing all without a language should fail
$response = $this->get('dev/docs/all/');
$this->assertEquals(404, $response->getStatusCode());
}
}

View File

@ -4,13 +4,14 @@
* @package docsviewer
* @subpackage tests
*/
class DocumentationViewerVersionWarningTest extends SapphireTest {
class DocumentationViewerVersionWarningTest extends SapphireTest
{
protected $autoFollowRedirection = false;
private $manifest;
public function setUp() {
public function setUp()
{
parent::setUp();
Config::nest();
@ -54,14 +55,15 @@ class DocumentationViewerVersionWarningTest extends SapphireTest {
$this->manifest = new DocumentationManifest(true);
}
public function tearDown() {
public function tearDown()
{
parent::tearDown();
Config::unnest();
}
public function testVersionWarning() {
public function testVersionWarning()
{
$v = new DocumentationViewer();
// the current version is set to 2.4, no notice should be shown on that page