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,86 +5,91 @@
*
* @package docsviewer
*/
class DocumentationHelper {
class DocumentationHelper
{
/**
* String helper for cleaning a file name to a readable version.
*
* @param string $name to convert
*
* @return string $name output
*/
public static function clean_page_name($name)
{
$name = self::trim_extension_off($name);
$name = self::trim_sort_number($name);
/**
* String helper for cleaning a file name to a readable version.
*
* @param string $name to convert
*
* @return string $name output
*/
public static function clean_page_name($name) {
$name = self::trim_extension_off($name);
$name = self::trim_sort_number($name);
$name = str_replace(array('-', '_'), ' ', $name);
$name = str_replace(array('-', '_'), ' ', $name);
return ucfirst(trim($name));
}
return ucfirst(trim($name));
}
/**
* String helper for cleaning a file name to a URL safe version.
*
* @param string $name to convert
*
* @return string $name output
*/
public static function clean_page_url($name)
{
$name = str_replace(array(' '), '_', $name);
/**
* String helper for cleaning a file name to a URL safe version.
*
* @param string $name to convert
*
* @return string $name output
*/
public static function clean_page_url($name) {
$name = str_replace(array(' '), '_', $name);
$name = self::trim_extension_off($name);
$name = self::trim_sort_number($name);
$name = self::trim_extension_off($name);
$name = self::trim_sort_number($name);
if (preg_match('/^[\/]?index[\/]?/', $name)) {
return '';
}
if(preg_match('/^[\/]?index[\/]?/', $name)) {
return '';
}
return strtolower($name);
}
return strtolower($name);
}
/**
* Removes leading numbers from pages (used to control sort order).
*
* @param string
*
* @return string
*/
public static function trim_sort_number($name)
{
$name = preg_replace("/^[0-9]*[_-]+/", '', $name);
/**
* Removes leading numbers from pages (used to control sort order).
*
* @param string
*
* @return string
*/
public static function trim_sort_number($name) {
$name = preg_replace("/^[0-9]*[_-]+/", '', $name);
return $name;
}
return $name;
}
/**
* Helper function to strip the extension off and return the name without
* the extension.
*
* @param string
*
* @return string
*/
public static function trim_extension_off($name) {
if(strrpos($name,'.') !== false) {
return substr($name, 0, strrpos($name,'.'));
}
/**
* Helper function to strip the extension off and return the name without
* the extension.
*
* @param string
*
* @return string
*/
public static function trim_extension_off($name)
{
if (strrpos($name, '.') !== false) {
return substr($name, 0, strrpos($name, '.'));
}
return $name;
}
return $name;
}
/**
* Helper function to get the extension of the filename.
*
* @param string
*
* @return string
*/
public static function get_extension($name) {
if(preg_match('/\.[a-z]+$/', $name)) {
return substr($name, strrpos($name,'.') + 1);
}
/**
* Helper function to get the extension of the filename.
*
* @param string
*
* @return string
*/
public static function get_extension($name)
{
if (preg_match('/\.[a-z]+$/', $name)) {
return substr($name, strrpos($name, '.') + 1);
}
return null;
}
return null;
}
}

View File

@ -27,715 +27,737 @@
* @package framework
* @subpackage manifest
*/
class DocumentationManifest {
/**
* @config
*
* @var boolean $automatic_registration
*/
private static $automatic_registration = true;
/**
* @config
*
* @var array $registered_entities
*/
private static $register_entities = array();
protected $cache;
protected $cacheKey;
protected $inited;
protected $forceRegen;
/**
* @var array $pages
*/
protected $pages = array();
protected $redirects = array();
/**
* @var DocumentationEntity
*/
private $entity;
/**
* @var boolean
*/
private $automaticallyPopulated = false;
/**
* @var ArrayList
*/
private $registeredEntities;
/**
* Constructs a new template manifest. The manifest is not actually built
* or loaded from cache until needed.
*
* @param bool $includeTests Include tests in the manifest.
* @param bool $forceRegen Force the manifest to be regenerated.
*/
public function __construct($forceRegen = false) {
$this->cacheKey = 'manifest';
$this->forceRegen = $forceRegen;
$this->registeredEntities = new ArrayList();
$this->cache = SS_Cache::factory('DocumentationManifest', 'Core', array(
'automatic_serialization' => true,
'lifetime' => null
));
$this->setupEntities();
}
/**
* Sets up the top level entities.
*
* 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) {
return;
}
if(Config::inst()->get('DocumentationManifest', 'automatic_registration')) {
$this->populateEntitiesFromInstall();
}
$registered = Config::inst()->get('DocumentationManifest', 'register_entities');
foreach($registered as $details) {
// validate the details provided through the YAML configuration
$required = array('Path', 'Title');
foreach($required as $require) {
if(!isset($details[$require])) {
throw new Exception("$require is a required key in DocumentationManifest.register_entities");
}
}
// if path is not an absolute value then assume it is relative from
// the BASE_PATH.
$path = $this->getRealPath($details['Path']);
$key = (isset($details['Key'])) ? $details['Key'] : $details['Title'];
if(!$path || !is_dir($path)) {
throw new Exception($details['Path'] . ' is not a valid documentation directory');
}
$version = (isset($details['Version'])) ? $details['Version'] : '';
$branch = (isset($details['Branch'])) ? $details['Branch'] : '';
$langs = scandir($path);
if($langs) {
$possible = i18n::get_common_languages(true);
foreach($langs as $k => $lang) {
if(isset($possible[$lang])) {
$entity = Injector::inst()->create(
'DocumentationEntity', $key
);
$entity->setPath(Controller::join_links($path, $lang, '/'));
$entity->setTitle($details['Title']);
$entity->setLanguage($lang);
$entity->setVersion($version);
$entity->setBranch($branch);
if(isset($details['Stable'])) {
$entity->setIsStable($details['Stable']);
}
if(isset($details['DefaultEntity'])) {
$entity->setIsDefaultEntity($details['DefaultEntity']);
}
$this->registeredEntities->push($entity);
}
}
}
}
}
public function getRealPath($path) {
if(substr($path, 0, 1) != '/') {
$path = Controller::join_links(BASE_PATH, $path);
}
return $path;
}
/**
* @return ArrayList
*/
public function getEntities() {
return $this->registeredEntities;
}
/**
* Scans the current installation and picks up all the SilverStripe modules
* that contain a `docs` folder.
*
* @return void
*/
public function populateEntitiesFromInstall() {
if($this->automaticallyPopulated) {
// already run
return;
}
foreach(scandir(BASE_PATH) as $key => $entity) {
if($key == "themes") {
continue;
}
$dir = Controller::join_links(BASE_PATH, $entity);
if(is_dir($dir)) {
// check to see if it has docs
$docs = Controller::join_links($dir, 'docs');
if(is_dir($docs)) {
$entities[] = array(
'Path' => $docs,
'Title' => DocumentationHelper::clean_page_name($entity),
'Version' => 'master',
'Branch' => 'master',
'Stable' => true
);
}
}
}
Config::inst()->update(
'DocumentationManifest', 'register_entities', $entities
);
$this->automaticallyPopulated = true;
}
/**
*
*/
protected function init() {
if (!$this->forceRegen && $data = $this->cache->load($this->cacheKey)) {
$this->pages = $data['pages'];
$this->redirects = $data['redirects'];
$this->inited = true;
} else {
$this->regenerate();
}
}
/**
* Returns a map of all documentation pages.
*
* @return array
*/
public function getPages() {
if (!$this->inited) {
$this->init();
}
return $this->pages;
}
public function getRedirects() {
if(!$this->inited) {
$this->init();
}
return $this->redirects;
}
/**
* Returns a particular page for the requested URL.
*
* @return DocumentationPage
*/
public function getPage($url) {
$pages = $this->getPages();
$url = $this->normalizeUrl($url);
if(!isset($pages[$url])) {
return null;
}
$record = $pages[$url];
foreach($this->getEntities() as $entity) {
if(strpos($record['filepath'], $entity->getPath()) !== false) {
$page = Injector::inst()->create(
$record['type'],
$entity,
$record['basename'],
$record['filepath']
);
return $page;
}
}
}
/**
* Get any redirect for the given url
*
* @param type $url
* @return string
*/
public function getRedirect($url) {
$pages = $this->getRedirects();
$url = $this->normalizeUrl($url);
if(isset($pages[$url])) {
return $pages[$url];
}
}
/**
* Regenerates the manifest by scanning the base path.
*
* @param bool $cache
*/
public function regenerate($cache = true) {
$finder = new DocumentationManifestFileFinder();
$finder->setOptions(array(
'dir_callback' => array($this, 'handleFolder'),
'file_callback' => array($this, 'handleFile')
));
$this->redirects = array();
foreach($this->getEntities() as $entity) {
$this->entity = $entity;
$this->handleFolder('', $this->entity->getPath(), 0);
$finder->find($this->entity->getPath());
}
// groupds
$grouped = array();
foreach($this->pages as $url => $page) {
if(!isset($grouped[$page['entitypath']])) {
$grouped[$page['entitypath']] = array();
}
$grouped[$page['entitypath']][$url] = $page;
}
$this->pages = array();
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) {
return -1;
}
if ($a['filepath'] == $b['filepath']) {
return 0;
}
return ($a['filepath'] < $b['filepath']) ? -1 : 1;
});
$this->pages = array_merge($this->pages, $entity);
}
if ($cache) {
$this->cache->save(
array(
'pages' => $this->pages,
'redirects' => $this->redirects
),
$this->cacheKey
);
}
$this->inited = true;
}
/**
* Remove the link_base from the start of a link
*
* @param string $link
* @return string
*/
protected function stripLinkBase($link) {
return ltrim(str_replace(
Config::inst()->get('DocumentationViewer', 'link_base'),
'',
$link
), '/');
}
/**
*
* @param DocumentationPage $page
* @param string $basename
* @param string $path
*/
protected function addPage($page, $basename, $path) {
$link = $this->stripLinkBase($page->Link());
$this->pages[$link] = array(
'title' => $page->getTitle(),
'basename' => $basename,
'filepath' => $path,
'type' => get_class($page),
'entitypath' => $this->entity->getPath(),
'summary' => $page->getSummary()
);
}
/**
* Add a redirect
*
* @param string $from
* @param string $to
*/
protected function addRedirect($from, $to) {
$fromLink = $this->stripLinkBase($from);
$toLink = $this->stripLinkBase($to);
$this->redirects[$fromLink] = $toLink;
}
/**
*
*/
public function handleFolder($basename, $path, $depth) {
$folder = Injector::inst()->create(
'DocumentationFolder', $this->entity, $basename, $path
);
// Add main folder link
$fullLink = $folder->Link();
$this->addPage($folder, $basename, $path);
// Add alternative link
$shortLink = $folder->Link(true);
if($shortLink != $fullLink) {
$this->addRedirect($shortLink, $fullLink);
}
}
/**
* Individual files can optionally provide a nice title and a better URL
* through the use of markdown meta data. This creates a new
* {@link DocumentationPage} instance for the file.
*
* If the markdown does not specify the title in the meta data it falls back
* to using the file name.
*
* @param string $basename
* @param string $path
* @param int $depth
*/
public function handleFile($basename, $path, $depth) {
$page = Injector::inst()->create(
'DocumentationPage',
$this->entity, $basename, $path
);
// populate any meta data
$page->getMarkdown();
// Add main link
$fullLink = $page->Link();
$this->addPage($page, $basename, $path);
// If this is a stable version, add the short link
$shortLink = $page->Link(true);
if($fullLink != $shortLink) {
$this->addRedirect($shortLink, $fullLink);
}
}
/**
* Generate an {@link ArrayList} of the pages to the given page.
*
* @param DocumentationPage
* @param DocumentationEntityLanguage
*
* @return ArrayList
*/
public function generateBreadcrumbs($record, $base) {
$output = new ArrayList();
$parts = explode('/', trim($record->getRelativeLink(), '/'));
// Add the base link.
$output->push(new ArrayData(array(
'Link' => $base->Link(),
'Title' => $base->Title
)));
$progress = $base->Link();
foreach($parts as $part) {
if($part) {
$progress = Controller::join_links($progress, $part, '/');
$output->push(new ArrayData(array(
'Link' => $progress,
'Title' => DocumentationHelper::clean_page_name($part)
)));
}
}
return $output;
}
/**
* Determine the next page from the given page.
*
* Relies on the fact when the manifest was built, it was generated in
* order.
*
* @param string $filepath
* @param string $entityBase
*
* @return ArrayData
*/
public function getNextPage($filepath, $entityBase) {
$grabNext = false;
$fallback = null;
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']) {
$grabNext = true;
} else if(!$fallback && strpos($page['filepath'], $filepath) !== false) {
$fallback = new ArrayData(array(
'Link' => $url,
'Title' => $page['title'],
'Fallback' => true
));
}
}
if(!$grabNext) {
return $fallback;
}
return null;
}
/**
* Determine the previous page from the given page.
*
* Relies on the fact when the manifest was built, it was generated in
* order.
*
* @param string $filepath
* @param string $entityBase
*
* @return ArrayData
*/
public function getPreviousPage($filepath, $entityPath) {
$previousUrl = $previousPage = null;
foreach($this->getPages() as $url => $page) {
if($filepath == $page['filepath']) {
if($previousUrl) {
return new ArrayData(array(
'Link' => $previousUrl,
'Title' => $previousPage['title']
));
}
}
if(strpos($page['filepath'], $entityPath) !== false) {
$previousUrl = $url;
$previousPage = $page;
}
}
return null;
}
/**
* @param string
*
* @return string
*/
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/')) {
$url = substr($url, 0, strpos($url, "index.md/"));
}
return $url;
}
/**
* Return the children of the provided record path.
*
* Looks for any pages in the manifest which have one more slash attached.
*
* @param string $path
*
* @return ArrayList
*/
public function getChildrenFor($entityPath, $recordPath = null) {
if(!$recordPath) {
$recordPath = $entityPath;
}
$output = new ArrayList();
$base = Config::inst()->get('DocumentationViewer', 'link_base');
$entityPath = $this->normalizeUrl($entityPath);
$recordPath = $this->normalizeUrl($recordPath);
$recordParts = explode(DIRECTORY_SEPARATOR, trim($recordPath,'/'));
$currentRecordPath = end($recordParts);
$depth = substr_count($entityPath, '/');
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) {
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,'/'));
$currentPagePath = end($pagePathParts);
if($currentPagePath == $currentRecordPath) {
$mode = 'current';
}
else if(strpos($recordPath, $pagePath) !== false) {
$mode = 'section';
}
else {
$mode = 'link';
}
$children = new ArrayList();
if($mode == 'section' || $mode == 'current') {
$children = $this->getChildrenFor($pagePath, $recordPath);
}
$output->push(new ArrayData(array(
'Link' => Controller::join_links($base, $url, '/'),
'Title' => $page['title'],
'LinkingMode' => $mode,
'Summary' => $page['summary'],
'Children' => $children
)));
}
}
return $output;
}
/**
* @param DocumentationEntity
*
* @return ArrayList
*/
public function getAllVersionsOfEntity(DocumentationEntity $entity) {
$all = new ArrayList();
foreach($this->getEntities() as $check) {
if($check->getKey() == $entity->getKey()) {
if($check->getLanguage() == $entity->getLanguage()) {
$all->push($check);
}
}
}
return $all;
}
/**
* @param DocumentationEntity
*
* @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()) {
return $check;
}
}
}
}
return $entity;
}
/**
* @param DocumentationEntity
*
* @return ArrayList
*/
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()) {
$same = ($check->getVersion() == $entity->getVersion());
$output->push(new ArrayData(array(
'Title' => $check->getVersion(),
'Link' => $check->Link(),
'LinkingMode' => ($same) ? 'current' : 'link',
'IsStable' => $check->getIsStable()
)));
}
}
}
return $output;
}
/**
* Returns a sorted array of all the unique versions registered
*/
public function getAllVersions() {
$versions = array();
foreach($this->getEntities() as $entity) {
if($entity->getVersion()) {
$versions[$entity->getVersion()] = $entity->getVersion();
} else {
$versions['0.0'] = _t('DocumentationManifest.MASTER', 'Master');
}
}
asort($versions);
return $versions;
}
class DocumentationManifest
{
/**
* @config
*
* @var boolean $automatic_registration
*/
private static $automatic_registration = true;
/**
* @config
*
* @var array $registered_entities
*/
private static $register_entities = array();
protected $cache;
protected $cacheKey;
protected $inited;
protected $forceRegen;
/**
* @var array $pages
*/
protected $pages = array();
protected $redirects = array();
/**
* @var DocumentationEntity
*/
private $entity;
/**
* @var boolean
*/
private $automaticallyPopulated = false;
/**
* @var ArrayList
*/
private $registeredEntities;
/**
* Constructs a new template manifest. The manifest is not actually built
* or loaded from cache until needed.
*
* @param bool $includeTests Include tests in the manifest.
* @param bool $forceRegen Force the manifest to be regenerated.
*/
public function __construct($forceRegen = false)
{
$this->cacheKey = 'manifest';
$this->forceRegen = $forceRegen;
$this->registeredEntities = new ArrayList();
$this->cache = SS_Cache::factory('DocumentationManifest', 'Core', array(
'automatic_serialization' => true,
'lifetime' => null
));
$this->setupEntities();
}
/**
* Sets up the top level entities.
*
* 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) {
return;
}
if (Config::inst()->get('DocumentationManifest', 'automatic_registration')) {
$this->populateEntitiesFromInstall();
}
$registered = Config::inst()->get('DocumentationManifest', 'register_entities');
foreach ($registered as $details) {
// validate the details provided through the YAML configuration
$required = array('Path', 'Title');
foreach ($required as $require) {
if (!isset($details[$require])) {
throw new Exception("$require is a required key in DocumentationManifest.register_entities");
}
}
// if path is not an absolute value then assume it is relative from
// the BASE_PATH.
$path = $this->getRealPath($details['Path']);
$key = (isset($details['Key'])) ? $details['Key'] : $details['Title'];
if (!$path || !is_dir($path)) {
throw new Exception($details['Path'] . ' is not a valid documentation directory');
}
$version = (isset($details['Version'])) ? $details['Version'] : '';
$branch = (isset($details['Branch'])) ? $details['Branch'] : '';
$langs = scandir($path);
if ($langs) {
$possible = i18n::get_common_languages(true);
foreach ($langs as $k => $lang) {
if (isset($possible[$lang])) {
$entity = Injector::inst()->create(
'DocumentationEntity', $key
);
$entity->setPath(Controller::join_links($path, $lang, '/'));
$entity->setTitle($details['Title']);
$entity->setLanguage($lang);
$entity->setVersion($version);
$entity->setBranch($branch);
if (isset($details['Stable'])) {
$entity->setIsStable($details['Stable']);
}
if (isset($details['DefaultEntity'])) {
$entity->setIsDefaultEntity($details['DefaultEntity']);
}
$this->registeredEntities->push($entity);
}
}
}
}
}
public function getRealPath($path)
{
if (substr($path, 0, 1) != '/') {
$path = Controller::join_links(BASE_PATH, $path);
}
return $path;
}
/**
* @return ArrayList
*/
public function getEntities()
{
return $this->registeredEntities;
}
/**
* Scans the current installation and picks up all the SilverStripe modules
* that contain a `docs` folder.
*
* @return void
*/
public function populateEntitiesFromInstall()
{
if ($this->automaticallyPopulated) {
// already run
return;
}
foreach (scandir(BASE_PATH) as $key => $entity) {
if ($key == "themes") {
continue;
}
$dir = Controller::join_links(BASE_PATH, $entity);
if (is_dir($dir)) {
// check to see if it has docs
$docs = Controller::join_links($dir, 'docs');
if (is_dir($docs)) {
$entities[] = array(
'Path' => $docs,
'Title' => DocumentationHelper::clean_page_name($entity),
'Version' => 'master',
'Branch' => 'master',
'Stable' => true
);
}
}
}
Config::inst()->update(
'DocumentationManifest', 'register_entities', $entities
);
$this->automaticallyPopulated = true;
}
/**
*
*/
protected function init()
{
if (!$this->forceRegen && $data = $this->cache->load($this->cacheKey)) {
$this->pages = $data['pages'];
$this->redirects = $data['redirects'];
$this->inited = true;
} else {
$this->regenerate();
}
}
/**
* Returns a map of all documentation pages.
*
* @return array
*/
public function getPages()
{
if (!$this->inited) {
$this->init();
}
return $this->pages;
}
public function getRedirects()
{
if (!$this->inited) {
$this->init();
}
return $this->redirects;
}
/**
* Returns a particular page for the requested URL.
*
* @return DocumentationPage
*/
public function getPage($url)
{
$pages = $this->getPages();
$url = $this->normalizeUrl($url);
if (!isset($pages[$url])) {
return null;
}
$record = $pages[$url];
foreach ($this->getEntities() as $entity) {
if (strpos($record['filepath'], $entity->getPath()) !== false) {
$page = Injector::inst()->create(
$record['type'],
$entity,
$record['basename'],
$record['filepath']
);
return $page;
}
}
}
/**
* Get any redirect for the given url
*
* @param type $url
* @return string
*/
public function getRedirect($url)
{
$pages = $this->getRedirects();
$url = $this->normalizeUrl($url);
if (isset($pages[$url])) {
return $pages[$url];
}
}
/**
* Regenerates the manifest by scanning the base path.
*
* @param bool $cache
*/
public function regenerate($cache = true)
{
$finder = new DocumentationManifestFileFinder();
$finder->setOptions(array(
'dir_callback' => array($this, 'handleFolder'),
'file_callback' => array($this, 'handleFile')
));
$this->redirects = array();
foreach ($this->getEntities() as $entity) {
$this->entity = $entity;
$this->handleFolder('', $this->entity->getPath(), 0);
$finder->find($this->entity->getPath());
}
// groupds
$grouped = array();
foreach ($this->pages as $url => $page) {
if (!isset($grouped[$page['entitypath']])) {
$grouped[$page['entitypath']] = array();
}
$grouped[$page['entitypath']][$url] = $page;
}
$this->pages = array();
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) {
return -1;
}
if ($a['filepath'] == $b['filepath']) {
return 0;
}
return ($a['filepath'] < $b['filepath']) ? -1 : 1;
});
$this->pages = array_merge($this->pages, $entity);
}
if ($cache) {
$this->cache->save(
array(
'pages' => $this->pages,
'redirects' => $this->redirects
),
$this->cacheKey
);
}
$this->inited = true;
}
/**
* Remove the link_base from the start of a link
*
* @param string $link
* @return string
*/
protected function stripLinkBase($link)
{
return ltrim(str_replace(
Config::inst()->get('DocumentationViewer', 'link_base'),
'',
$link
), '/');
}
/**
*
* @param DocumentationPage $page
* @param string $basename
* @param string $path
*/
protected function addPage($page, $basename, $path)
{
$link = $this->stripLinkBase($page->Link());
$this->pages[$link] = array(
'title' => $page->getTitle(),
'basename' => $basename,
'filepath' => $path,
'type' => get_class($page),
'entitypath' => $this->entity->getPath(),
'summary' => $page->getSummary()
);
}
/**
* Add a redirect
*
* @param string $from
* @param string $to
*/
protected function addRedirect($from, $to)
{
$fromLink = $this->stripLinkBase($from);
$toLink = $this->stripLinkBase($to);
$this->redirects[$fromLink] = $toLink;
}
/**
*
*/
public function handleFolder($basename, $path, $depth)
{
$folder = Injector::inst()->create(
'DocumentationFolder', $this->entity, $basename, $path
);
// Add main folder link
$fullLink = $folder->Link();
$this->addPage($folder, $basename, $path);
// Add alternative link
$shortLink = $folder->Link(true);
if ($shortLink != $fullLink) {
$this->addRedirect($shortLink, $fullLink);
}
}
/**
* Individual files can optionally provide a nice title and a better URL
* through the use of markdown meta data. This creates a new
* {@link DocumentationPage} instance for the file.
*
* If the markdown does not specify the title in the meta data it falls back
* to using the file name.
*
* @param string $basename
* @param string $path
* @param int $depth
*/
public function handleFile($basename, $path, $depth)
{
$page = Injector::inst()->create(
'DocumentationPage',
$this->entity, $basename, $path
);
// populate any meta data
$page->getMarkdown();
// Add main link
$fullLink = $page->Link();
$this->addPage($page, $basename, $path);
// If this is a stable version, add the short link
$shortLink = $page->Link(true);
if ($fullLink != $shortLink) {
$this->addRedirect($shortLink, $fullLink);
}
}
/**
* Generate an {@link ArrayList} of the pages to the given page.
*
* @param DocumentationPage
* @param DocumentationEntityLanguage
*
* @return ArrayList
*/
public function generateBreadcrumbs($record, $base)
{
$output = new ArrayList();
$parts = explode('/', trim($record->getRelativeLink(), '/'));
// Add the base link.
$output->push(new ArrayData(array(
'Link' => $base->Link(),
'Title' => $base->Title
)));
$progress = $base->Link();
foreach ($parts as $part) {
if ($part) {
$progress = Controller::join_links($progress, $part, '/');
$output->push(new ArrayData(array(
'Link' => $progress,
'Title' => DocumentationHelper::clean_page_name($part)
)));
}
}
return $output;
}
/**
* Determine the next page from the given page.
*
* Relies on the fact when the manifest was built, it was generated in
* order.
*
* @param string $filepath
* @param string $entityBase
*
* @return ArrayData
*/
public function getNextPage($filepath, $entityBase)
{
$grabNext = false;
$fallback = null;
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']) {
$grabNext = true;
} elseif (!$fallback && strpos($page['filepath'], $filepath) !== false) {
$fallback = new ArrayData(array(
'Link' => $url,
'Title' => $page['title'],
'Fallback' => true
));
}
}
if (!$grabNext) {
return $fallback;
}
return null;
}
/**
* Determine the previous page from the given page.
*
* Relies on the fact when the manifest was built, it was generated in
* order.
*
* @param string $filepath
* @param string $entityBase
*
* @return ArrayData
*/
public function getPreviousPage($filepath, $entityPath)
{
$previousUrl = $previousPage = null;
foreach ($this->getPages() as $url => $page) {
if ($filepath == $page['filepath']) {
if ($previousUrl) {
return new ArrayData(array(
'Link' => $previousUrl,
'Title' => $previousPage['title']
));
}
}
if (strpos($page['filepath'], $entityPath) !== false) {
$previousUrl = $url;
$previousPage = $page;
}
}
return null;
}
/**
* @param string
*
* @return string
*/
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/')) {
$url = substr($url, 0, strpos($url, "index.md/"));
}
return $url;
}
/**
* Return the children of the provided record path.
*
* Looks for any pages in the manifest which have one more slash attached.
*
* @param string $path
*
* @return ArrayList
*/
public function getChildrenFor($entityPath, $recordPath = null)
{
if (!$recordPath) {
$recordPath = $entityPath;
}
$output = new ArrayList();
$base = Config::inst()->get('DocumentationViewer', 'link_base');
$entityPath = $this->normalizeUrl($entityPath);
$recordPath = $this->normalizeUrl($recordPath);
$recordParts = explode(DIRECTORY_SEPARATOR, trim($recordPath, '/'));
$currentRecordPath = end($recordParts);
$depth = substr_count($entityPath, '/');
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) {
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, '/'));
$currentPagePath = end($pagePathParts);
if ($currentPagePath == $currentRecordPath) {
$mode = 'current';
} elseif (strpos($recordPath, $pagePath) !== false) {
$mode = 'section';
} else {
$mode = 'link';
}
$children = new ArrayList();
if ($mode == 'section' || $mode == 'current') {
$children = $this->getChildrenFor($pagePath, $recordPath);
}
$output->push(new ArrayData(array(
'Link' => Controller::join_links($base, $url, '/'),
'Title' => $page['title'],
'LinkingMode' => $mode,
'Summary' => $page['summary'],
'Children' => $children
)));
}
}
return $output;
}
/**
* @param DocumentationEntity
*
* @return ArrayList
*/
public function getAllVersionsOfEntity(DocumentationEntity $entity)
{
$all = new ArrayList();
foreach ($this->getEntities() as $check) {
if ($check->getKey() == $entity->getKey()) {
if ($check->getLanguage() == $entity->getLanguage()) {
$all->push($check);
}
}
}
return $all;
}
/**
* @param DocumentationEntity
*
* @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()) {
return $check;
}
}
}
}
return $entity;
}
/**
* @param DocumentationEntity
*
* @return ArrayList
*/
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()) {
$same = ($check->getVersion() == $entity->getVersion());
$output->push(new ArrayData(array(
'Title' => $check->getVersion(),
'Link' => $check->Link(),
'LinkingMode' => ($same) ? 'current' : 'link',
'IsStable' => $check->getIsStable()
)));
}
}
}
return $output;
}
/**
* Returns a sorted array of all the unique versions registered
*/
public function getAllVersions()
{
$versions = array();
foreach ($this->getEntities() as $entity) {
if ($entity->getVersion()) {
$versions[$entity->getVersion()] = $entity->getVersion();
} else {
$versions['0.0'] = _t('DocumentationManifest.MASTER', 'Master');
}
}
asort($versions);
return $versions;
}
}

View File

@ -1,38 +1,38 @@
<?php
class DocumentationManifestFileFinder extends SS_FileFinder {
class DocumentationManifestFileFinder extends SS_FileFinder
{
/**
* @var array
*/
private static $ignored_files = array(
'.', '..', '.ds_store',
'.svn', '.git', 'assets', 'themes', '_images'
);
/**
* @var array
*/
private static $ignored_files = array(
'.', '..', '.ds_store',
'.svn', '.git', 'assets', 'themes', '_images'
);
/**
* @var array
*/
protected static $default_options = array(
'name_regex' => '/\.(md|markdown)$/i',
'file_callback' => null,
'dir_callback' => null,
'ignore_vcs' => true
);
/**
* @var array
*/
protected static $default_options = array(
'name_regex' => '/\.(md|markdown)$/i',
'file_callback' => null,
'dir_callback' => null,
'ignore_vcs' => true
);
/**
*
*/
public function acceptDir($basename, $pathname, $depth)
{
$ignored = Config::inst()->get('DocumentationManifestFileFinder', 'ignored_files');
/**
*
*/
public function acceptDir($basename, $pathname, $depth) {
$ignored = Config::inst()->get('DocumentationManifestFileFinder', 'ignored_files');
if($ignored) {
if(in_array(strtolower($basename), $ignored)) {
return false;
}
}
return true;
}
if ($ignored) {
if (in_array(strtolower($basename), $ignored)) {
return false;
}
}
return true;
}
}

View File

@ -7,201 +7,219 @@
*
* @package docsviewer
*/
class DocumentationParser {
class DocumentationParser
{
const CODE_BLOCK_BACKTICK = 1;
const CODE_BLOCK_COLON = 2;
const CODE_BLOCK_BACKTICK = 1;
const CODE_BLOCK_COLON = 2;
/**
* @var string Rewriting of api links in the format "[api:MyClass]" or "[api:MyClass::$my_property]".
*/
public static $api_link_base = 'http://api.silverstripe.org/search/lookup/?q=%s&amp;version=%s&amp;module=%s';
/**
* @var string Rewriting of api links in the format "[api:MyClass]" or "[api:MyClass::$my_property]".
*/
public static $api_link_base = 'http://api.silverstripe.org/search/lookup/?q=%s&amp;version=%s&amp;module=%s';
/**
* @var array
*/
public static $heading_counts = array();
/**
* @var array
*/
public static $heading_counts = array();
/**
* Parse a given path to the documentation for a file. Performs a case
* insensitive lookup on the file system. Automatically appends the file
* extension to one of the markdown extensions as well so /install/ in a
* web browser will match /install.md or /INSTALL.md.
*
* Filepath: /var/www/myproject/src/cms/en/folder/subfolder/page.md
* URL: http://myhost/mywebroot/dev/docs/2.4/cms/en/folder/subfolder/page
* Webroot: http://myhost/mywebroot/
* Baselink: dev/docs/2.4/cms/en/
* Pathparts: folder/subfolder/page
*
* @param DocumentationPage $page
* @param String $baselink Link relative to webroot, up until the "root"
* of the module. Necessary to rewrite relative
* links
*
* @return String
*/
public static function parse(DocumentationPage $page, $baselink = null)
{
if (!$page || (!$page instanceof DocumentationPage)) {
return false;
}
/**
* Parse a given path to the documentation for a file. Performs a case
* insensitive lookup on the file system. Automatically appends the file
* extension to one of the markdown extensions as well so /install/ in a
* web browser will match /install.md or /INSTALL.md.
*
* Filepath: /var/www/myproject/src/cms/en/folder/subfolder/page.md
* URL: http://myhost/mywebroot/dev/docs/2.4/cms/en/folder/subfolder/page
* Webroot: http://myhost/mywebroot/
* Baselink: dev/docs/2.4/cms/en/
* Pathparts: folder/subfolder/page
*
* @param DocumentationPage $page
* @param String $baselink Link relative to webroot, up until the "root"
* of the module. Necessary to rewrite relative
* links
*
* @return String
*/
public static function parse(DocumentationPage $page, $baselink = null) {
if(!$page || (!$page instanceof DocumentationPage)) {
return false;
}
$md = $page->getMarkdown(true);
$md = $page->getMarkdown(true);
// Pre-processing
$md = self::rewrite_image_links($md, $page);
$md = self::rewrite_relative_links($md, $page, $baselink);
// Pre-processing
$md = self::rewrite_image_links($md, $page);
$md = self::rewrite_relative_links($md, $page, $baselink);
$md = self::rewrite_api_links($md, $page);
$md = self::rewrite_heading_anchors($md, $page);
$md = self::rewrite_api_links($md, $page);
$md = self::rewrite_heading_anchors($md, $page);
$md = self::rewrite_code_blocks($md);
$md = self::rewrite_code_blocks($md);
$parser = new ParsedownExtra();
$parser->setBreaksEnabled(false);
$parser = new ParsedownExtra();
$parser->setBreaksEnabled(false);
$text = $parser->text($md);
$text = $parser->text($md);
return $text;
}
return $text;
}
public static function rewrite_code_blocks($md)
{
$started = false;
$inner = false;
$mode = false;
$end = false;
$debug = false;
public static function rewrite_code_blocks($md) {
$started = false;
$inner = false;
$mode = false;
$end = false;
$debug = false;
$lines = explode("\n", $md);
$output = array();
$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) {
continue;
}
// 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) {
continue;
}
if (!$started && preg_match('/^[\t]*:::\s*(.*)/', $line, $matches)) {
// first line with custom formatting
if ($debug) {
var_dump('Starts a new block with :::');
}
if(!$started && preg_match('/^[\t]*:::\s*(.*)/', $line, $matches)) {
// first line with custom formatting
if($debug) var_dump('Starts a new block with :::');
$started = true;
$mode = self::CODE_BLOCK_COLON;
$started = true;
$mode = self::CODE_BLOCK_COLON;
$output[$i] = sprintf('```%s', (isset($matches[1])) ? trim($matches[1]) : "");
} elseif (!$started && preg_match('/^\t*```\s*(.*)/', $line, $matches)) {
if ($debug) {
var_dump('Starts a new block with ```');
}
$output[$i] = sprintf('```%s', (isset($matches[1])) ? trim($matches[1]) : "");
$started = true;
$mode = self::CODE_BLOCK_BACKTICK;
} else if(!$started && preg_match('/^\t*```\s*(.*)/', $line, $matches)) {
if($debug) var_dump('Starts a new block with ```');
$output[$i] = sprintf('```%s', (isset($matches[1])) ? trim($matches[1]) : "");
} 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 ```');
}
$started = true;
$mode = self::CODE_BLOCK_BACKTICK;
// 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 ```');
}
$output[$i] = sprintf('```%s', (isset($matches[1])) ? trim($matches[1]) : "");
} else if($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 ```');
// still inside the line.
if (!$started) {
$output[$i - 1] = '```';
}
// 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 ```');
$output[$i] = $line;
$inner = true;
}
} elseif (preg_match('/^[\ ]{0,3}?[\t](.*)/', $line, $matches)) {
// still inside the line.
if(!$started) {
$output[$i - 1] = '```';
}
// 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');
}
$output[$i] = $line;
$inner = true;
}
} else if(preg_match('/^[\ ]{0,3}?[\t](.*)/', $line, $matches)) {
$output[$i - 1] = '```';
} else {
if ($debug) {
var_dump('Content is still tabbed so still inner');
}
}
// 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');
$output[$i] = $matches[1];
$inner = true;
$started = true;
} elseif ($started && $inner && trim($line) === "") {
if ($debug) {
var_dump('Inner line of code block');
}
$output[$i - 1] = '```';
} else {
if($debug) var_dump('Content is still tabbed so still inner');
}
// 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;
} elseif ($started && $inner) {
// line contains something other than whitespace, or tabbed. E.g
// > code
// > \n
// > some message
//
// So actually want to reset $i to the line before this new line
// 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) {
var_dump('Contains something that isnt code. So end the code.');
}
$output[$i] = $matches[1];
$inner = true;
$started = true;
} else if($started && $inner && trim($line) === "") {
if($debug) var_dump('Inner line of code block');
$end = true;
$output[$i] = $line;
$i = $i - 1;
} else {
$output[$i] = $line;
}
// 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) {
// line contains something other than whitespace, or tabbed. E.g
// > code
// > \n
// > some message
//
// So actually want to reset $i to the line before this new line
// 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) {
var_dump('Contains something that isnt code. So end the code.');
}
if ($end) {
if ($debug) {
var_dump('End of code block');
}
$output = self::finalize_code_output($i, $output);
$end = true;
$output[$i] = $line;
$i = $i - 1;
} else {
$output[$i] = $line;
}
// reset state
$started = $inner = $mode = $end = false;
}
}
if($end) {
if($debug) var_dump('End of code block');
$output = self::finalize_code_output($i, $output);
if ($started) {
$output = self::finalize_code_output($i+1, $output);
}
// reset state
$started = $inner = $mode = $end = false;
}
}
return implode("\n", $output);
}
if($started) {
$output = self::finalize_code_output($i+1, $output);
}
/**
* Adds the closing code backticks. Removes trailing whitespace.
*
* @param int
* @param array
*
* @return array
*/
private static function finalize_code_output($i, $output)
{
if (isset($output[$i]) && trim($output[$i])) {
$output[$i] .= "\n```\n";
} else {
$output[$i] = "```";
}
return implode("\n", $output);
return $output;
}
}
/**
* Adds the closing code backticks. Removes trailing whitespace.
*
* @param int
* @param array
*
* @return array
*/
private static function finalize_code_output($i, $output) {
if(isset($output[$i]) && trim($output[$i])) {
$output[$i] .= "\n```\n";
}
else {
$output[$i] = "```";
}
return $output;
}
public static function rewrite_image_links($md, $page) {
// Links with titles
$re = '/
public static function rewrite_image_links($md, $page)
{
// Links with titles
$re = '/
!
\[
(.*?) # image title (non greedy)
@ -210,77 +228,78 @@ class DocumentationParser {
(.*?) # image url (non greedy)
\)
/x';
preg_match_all($re, $md, $images);
preg_match_all($re, $md, $images);
if($images) {
foreach($images[0] as $i => $match) {
$title = $images[1][$i];
$url = $images[2][$i];
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);
// 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;
}
// Rewrite URL (relative or absolute)
$baselink = Director::makeRelative(
dirname($page->getPath())
);
// Rewrite URL (relative or absolute)
$baselink = Director::makeRelative(
dirname($page->getPath())
);
// if the image starts with a slash, it's absolute
if(substr($url, 0, 1) == '/') {
$relativeUrl = str_replace(BASE_PATH, '', Controller::join_links(
$page->getEntity()->getPath(),
$url
));
} else {
$relativeUrl = rtrim($baselink, '/') . '/' . ltrim($url, '/');
}
// if the image starts with a slash, it's absolute
if (substr($url, 0, 1) == '/') {
$relativeUrl = str_replace(BASE_PATH, '', Controller::join_links(
$page->getEntity()->getPath(),
$url
));
} else {
$relativeUrl = rtrim($baselink, '/') . '/' . ltrim($url, '/');
}
// Resolve relative paths
while(strpos($relativeUrl, '/..') !== FALSE) {
$relativeUrl = preg_replace('/\w+\/\.\.\//', '', $relativeUrl);
}
// Resolve relative paths
while (strpos($relativeUrl, '/..') !== false) {
$relativeUrl = preg_replace('/\w+\/\.\.\//', '', $relativeUrl);
}
// Make it absolute again
$absoluteUrl = Controller::join_links(
Director::absoluteBaseURL(),
$relativeUrl
);
// Make it absolute again
$absoluteUrl = Controller::join_links(
Director::absoluteBaseURL(),
$relativeUrl
);
// Replace any double slashes (apart from protocol)
// Replace any double slashes (apart from protocol)
// $absoluteUrl = preg_replace('/([^:])\/{2,}/', '$1/', $absoluteUrl);
// Replace in original content
$md = str_replace(
$match,
sprintf('![%s](%s)', $title, $absoluteUrl),
$md
);
}
}
// Replace in original content
$md = str_replace(
$match,
sprintf('![%s](%s)', $title, $absoluteUrl),
$md
);
}
}
return $md;
}
return $md;
}
/**
* Rewrite links with special "api:" prefix, from two possible formats:
* 1. [api:DataObject]
* 2. (My Title)(api:DataObject)
*
* Hack: Replaces any backticks with "<code>" blocks,
* as the currently used markdown parser doesn't resolve links in backticks,
* but does resolve in "<code>" blocks.
*
* @param String $md
* @param DocumentationPage $page
* @return String
*/
public static function rewrite_api_links($md, $page) {
// Links with titles
$re = '/
/**
* Rewrite links with special "api:" prefix, from two possible formats:
* 1. [api:DataObject]
* 2. (My Title)(api:DataObject)
*
* Hack: Replaces any backticks with "<code>" blocks,
* as the currently used markdown parser doesn't resolve links in backticks,
* but does resolve in "<code>" blocks.
*
* @param String $md
* @param DocumentationPage $page
* @return String
*/
public static function rewrite_api_links($md, $page)
{
// Links with titles
$re = '/
`?
\[
(.*?) # link title (non greedy)
@ -290,116 +309,121 @@ class DocumentationParser {
\)
`?
/x';
preg_match_all($re, $md, $linksWithTitles);
if($linksWithTitles) {
foreach($linksWithTitles[0] as $i => $match) {
$title = $linksWithTitles[1][$i];
$subject = $linksWithTitles[2][$i];
preg_match_all($re, $md, $linksWithTitles);
if ($linksWithTitles) {
foreach ($linksWithTitles[0] as $i => $match) {
$title = $linksWithTitles[1][$i];
$subject = $linksWithTitles[2][$i];
$url = sprintf(
self::$api_link_base,
urlencode($subject),
urlencode($page->getVersion()),
urlencode($page->getEntity()->getKey())
);
$url = sprintf(
self::$api_link_base,
urlencode($subject),
urlencode($page->getVersion()),
urlencode($page->getEntity()->getKey())
);
$md = str_replace(
$match,
sprintf('[%s](%s)', $title, $url),
$md
);
}
}
$md = str_replace(
$match,
sprintf('[%s](%s)', $title, $url),
$md
);
}
}
// Bare links
$re = '/
// Bare links
$re = '/
`?
\[
api:(.*?)
\]
`?
/x';
preg_match_all($re, $md, $links);
if($links) {
foreach($links[0] as $i => $match) {
$subject = $links[1][$i];
$url = sprintf(
self::$api_link_base,
$subject,
$page->getVersion(),
$page->getEntity()->getKey()
);
preg_match_all($re, $md, $links);
if ($links) {
foreach ($links[0] as $i => $match) {
$subject = $links[1][$i];
$url = sprintf(
self::$api_link_base,
$subject,
$page->getVersion(),
$page->getEntity()->getKey()
);
$md = str_replace(
$match,
sprintf('[%s](%s)', $subject, $url),
$md
);
}
}
$md = str_replace(
$match,
sprintf('[%s](%s)', $subject, $url),
$md
);
}
}
return $md;
}
return $md;
}
/**
*
*/
public static function rewrite_heading_anchors($md, $page) {
$re = '/^\#+(.*)/m';
$md = preg_replace_callback($re, array('DocumentationParser', '_rewrite_heading_anchors_callback'), $md);
/**
*
*/
public static function rewrite_heading_anchors($md, $page)
{
$re = '/^\#+(.*)/m';
$md = preg_replace_callback($re, array('DocumentationParser', '_rewrite_heading_anchors_callback'), $md);
return $md;
}
return $md;
}
/**
*
*/
public static function _rewrite_heading_anchors_callback($matches) {
$heading = $matches[0];
$headingText = $matches[1];
/**
*
*/
public static function _rewrite_heading_anchors_callback($matches)
{
$heading = $matches[0];
$headingText = $matches[1];
if(preg_match('/\{\#.*\}/', $headingText)) return $heading;
if (preg_match('/\{\#.*\}/', $headingText)) {
return $heading;
}
if(!isset(self::$heading_counts[$headingText])) {
self::$heading_counts[$headingText] = 1;
}
else {
self::$heading_counts[$headingText]++;
$headingText .= "-" . self::$heading_counts[$headingText];
}
if (!isset(self::$heading_counts[$headingText])) {
self::$heading_counts[$headingText] = 1;
} else {
self::$heading_counts[$headingText]++;
$headingText .= "-" . self::$heading_counts[$headingText];
}
return sprintf("%s {#%s}", preg_replace('/\n/', '', $heading), self::generate_html_id($headingText));
}
return sprintf("%s {#%s}", preg_replace('/\n/', '', $heading), self::generate_html_id($headingText));
}
/**
* Generate an html element id from a string
*
* @return String
*/
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 = trim($t, '-');
$t = strtolower($t);
/**
* Generate an html element id from a string
*
* @return String
*/
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 = trim($t, '-');
$t = strtolower($t);
return $t;
}
return $t;
}
/**
* Resolves all relative links within markdown.
*
* @param String $md Markdown content
* @param DocumentationPage $page
*
* @return String Markdown
*/
public static function rewrite_relative_links($md, $page) {
$baselink = $page->getEntity()->Link();
/**
* Resolves all relative links within markdown.
*
* @param String $md Markdown content
* @param DocumentationPage $page
*
* @return String Markdown
*/
public static function rewrite_relative_links($md, $page)
{
$baselink = $page->getEntity()->Link();
$re = '/
$re = '/
([^\!]?) # exclude image format
\[
(.*?) # link title (non greedy)
@ -408,100 +432,104 @@ class DocumentationParser {
(.*?) # link url (non greedy)
\)
/x';
preg_match_all($re, $md, $matches);
preg_match_all($re, $md, $matches);
// relative path (relative to module base folder), without the filename.
// For "sapphire/en/current/topics/templates", this would be "templates"
$relativePath = dirname($page->getRelativePath());
// relative path (relative to module base folder), without the filename.
// For "sapphire/en/current/topics/templates", this would be "templates"
$relativePath = dirname($page->getRelativePath());
if(strpos($page->getRelativePath(), 'index.md')) {
$relativeLink = $page->getRelativeLink();
} else {
$relativeLink = dirname($page->getRelativeLink());
}
if (strpos($page->getRelativePath(), 'index.md')) {
$relativeLink = $page->getRelativeLink();
} else {
$relativeLink = dirname($page->getRelativeLink());
}
if($relativePath == '.') {
$relativePath = '';
}
if ($relativePath == '.') {
$relativePath = '';
}
if($relativeLink == ".") {
$relativeLink = '';
}
if ($relativeLink == ".") {
$relativeLink = '';
}
// file base link
$fileBaseLink = Director::makeRelative(dirname($page->getPath()));
// file base link
$fileBaseLink = Director::makeRelative(dirname($page->getPath()));
if($matches) {
foreach($matches[0] as $i => $match) {
$title = $matches[2][$i];
$url = $matches[3][$i];
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;
// Don't process API links
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;
// Don't process absolute links (based on protocol detection)
$urlParts = parse_url($url);
if ($urlParts && isset($urlParts['scheme'])) {
continue;
}
// for images we need to use the file base path
if(preg_match('/_images/', $url)) {
$relativeUrl = Controller::join_links(
Director::absoluteBaseURL(),
$fileBaseLink,
$url
);
}
else {
// Rewrite public URL
if(preg_match('/^\//', $url)) {
// Absolute: Only path to module base
$relativeUrl = Controller::join_links($baselink, $url, '/');
} else {
// Relative: Include path to module base and any folders
$relativeUrl = Controller::join_links($baselink, $relativeLink, $url, '/');
}
}
// for images we need to use the file base path
if (preg_match('/_images/', $url)) {
$relativeUrl = Controller::join_links(
Director::absoluteBaseURL(),
$fileBaseLink,
$url
);
} else {
// Rewrite public URL
if (preg_match('/^\//', $url)) {
// Absolute: Only path to module base
$relativeUrl = Controller::join_links($baselink, $url, '/');
} else {
// Relative: Include path to module base and any folders
$relativeUrl = Controller::join_links($baselink, $relativeLink, $url, '/');
}
}
// Resolve relative paths
while(strpos($relativeUrl, '..') !== FALSE) {
$relativeUrl = preg_replace('/[-\w]+\/\.\.\//', '', $relativeUrl);
}
// Resolve relative paths
while (strpos($relativeUrl, '..') !== false) {
$relativeUrl = preg_replace('/[-\w]+\/\.\.\//', '', $relativeUrl);
}
// Replace any double slashes (apart from protocol)
$relativeUrl = preg_replace('/([^:])\/{2,}/', '$1/', $relativeUrl);
// Replace any double slashes (apart from protocol)
$relativeUrl = preg_replace('/([^:])\/{2,}/', '$1/', $relativeUrl);
// Replace in original content
$md = str_replace(
$match,
sprintf('%s[%s](%s)', $matches[1][$i], $title, $relativeUrl),
$md
);
}
}
// Replace in original content
$md = str_replace(
$match,
sprintf('%s[%s](%s)', $matches[1][$i], $title, $relativeUrl),
$md
);
}
}
return $md;
}
return $md;
}
/**
* Strips out the metadata for a page
*
* @param DocumentationPage
*/
public static function retrieve_meta_data(DocumentationPage &$page) {
if($md = $page->getMarkdown()) {
$matches = preg_match_all('/
/**
* Strips out the metadata for a page
*
* @param DocumentationPage
*/
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])) {
$page->setMetaData($key, $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,42 +9,43 @@
* @package docsviewer
*/
class DocumentationPermalinks {
class DocumentationPermalinks
{
/**
* @var array
*/
private static $mapping = array();
/**
* @var array
*/
private static $mapping = array();
/**
* Add a mapping of nice short permalinks to a full long path
*
* <code>
* DocumentationPermalinks::add(array(
* 'debugging' => 'current/en/sapphire/topics/debugging'
* ));
* </code>
*
* Do not need to include the language or the version current as it
* will add it based off the language or version in the session
*
* @param array
*/
public static function add($map = array())
{
if (ArrayLib::is_associative($map)) {
self::$mapping = array_merge(self::$mapping, $map);
} else {
user_error("DocumentationPermalinks::add() requires an associative array", E_USER_ERROR);
}
}
/**
* Add a mapping of nice short permalinks to a full long path
*
* <code>
* DocumentationPermalinks::add(array(
* 'debugging' => 'current/en/sapphire/topics/debugging'
* ));
* </code>
*
* Do not need to include the language or the version current as it
* will add it based off the language or version in the session
*
* @param array
*/
public static function add($map = array()) {
if(ArrayLib::is_associative($map)) {
self::$mapping = array_merge(self::$mapping, $map);
}
else {
user_error("DocumentationPermalinks::add() requires an associative array", E_USER_ERROR);
}
}
/**
* Return the location for a given short value.
*
* @return string|false
*/
public static function map($url) {
return (isset(self::$mapping[$url])) ? self::$mapping[$url] : false;
}
/**
* Return the location for a given short value.
*
* @return string|false
*/
public static function map($url)
{
return (isset(self::$mapping[$url])) ? self::$mapping[$url] : false;
}
}

View File

@ -1,8 +1,8 @@
<?php
set_include_path(
dirname(dirname(__FILE__)) . '/thirdparty/'. PATH_SEPARATOR .
get_include_path()
dirname(dirname(__FILE__)) . '/thirdparty/'. PATH_SEPARATOR .
get_include_path()
);
require_once 'Zend/Search/Lucene.php';
@ -31,382 +31,406 @@ require_once 'Zend/Search/Lucene.php';
* @package docsviewer
*/
class DocumentationSearch {
/**
* @var bool - Is search enabled
*/
private static $enabled = false;
/**
* @var bool - Is advanced search enabled
*/
private static $advanced_search_enabled = true;
/**
* @var string - OpenSearch metadata. Please use {@link DocumentationSearch::set_meta_data()}
*/
private static $meta_data = array();
/**
* @var Array Regular expression mapped to a "boost factor" for the searched document.
* Defaults to 1.0, lower to decrease relevancy. Requires reindex.
* Uses {@link DocumentationPage->getRelativePath()} for comparison.
*/
private static $boost_by_path = array();
/**
* @var ArrayList - Results
*/
private $results;
/**
* @var int
*/
private $totalResults;
/**
* @var string
*/
private $query;
/**
* @var Controller
*/
private $outputController;
/**
* Optionally filter by module and version
*
* @var array
*/
private $modules, $versions;
public function setModules($modules) {
$this->modules = $modules;
}
public function setVersions($versions) {
$this->versions = $versions;
}
/**
* Set the current search query
*
* @param string
*/
public function setQuery($query) {
$this->query = $query;
}
/**
* Returns the current search query
*
* @return string
*/
public function getQuery() {
return $this->query;
}
/**
* Sets the {@link DocumentationViewer} or {@link DocumentationSearch} instance which this search is rendering
* on based on whether it is the results display or RSS feed
*
* @param Controller
*/
public function setOutputController($controller) {
$this->outputController = $controller;
}
/**
* Folder name for indexes (in the temp folder).
*
* @config
* @var string
*/
private static $index_location;
/**
* @return string
*/
public static function get_index_location() {
$location = Config::inst()->get('DocumentationSearch', 'index_location');
if(!$location) {
return Controller::join_links(TEMP_FOLDER, 'RebuildLuceneDocsIndex');
}
return $location;
}
/**
* Perform a search query on the index
*/
public function performSearch() {
try {
$index = Zend_Search_Lucene::open(self::get_index_location());
Zend_Search_Lucene::setResultSetLimit(100);
$query = new Zend_Search_Lucene_Search_Query_Boolean();
$term = Zend_Search_Lucene_Search_QueryParser::parse($this->getQuery());
$query->addSubquery($term, true);
if($this->modules) {
$moduleQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach($this->modules as $module) {
$moduleQuery->addTerm(new Zend_Search_Lucene_Index_Term($module, 'Entity'));
}
$query->addSubquery($moduleQuery, true);
}
if($this->versions) {
$versionQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach($this->versions as $version) {
$versionQuery->addTerm(new Zend_Search_Lucene_Index_Term($version, 'Version'));
}
$query->addSubquery($versionQuery, true);
}
$er = error_reporting();
error_reporting('E_ALL ^ E_NOTICE');
$this->results = $index->find($query);
error_reporting($er);
$this->totalResults = $index->numDocs();
}
catch(Zend_Search_Lucene_Exception $e) {
user_error($e .'. Ensure you have run the rebuld task (/dev/tasks/RebuildLuceneDocsIndex)', E_USER_ERROR);
}
}
/**
* @return ArrayData
*/
public function getSearchResults($request) {
$pageLength = (isset($_GET['length'])) ? (int) $_GET['length'] : 10;
$data = array(
'Results' => null,
'Query' => null,
'Versions' => DBField::create_field('Text', implode(', ', $this->versions)),
'Modules' => DBField::create_field('Text', implode(', ', $this->modules)),
'Title' => _t('DocumentationSearch.SEARCHRESULTS', 'Search Results'),
'TotalResults' => null,
'TotalPages' => null,
'ThisPage' => null,
'StartResult' => null,
'PageLength' => $pageLength,
'EndResult' => null,
'PrevUrl' => DBField::create_field('Text', 'false'),
'NextUrl' => DBField::create_field('Text', 'false'),
'SearchPages' => new ArrayList()
);
$start = ($request->requestVar('start')) ? (int)$request->requestVar('start') : 0;
$query = ($request->requestVar('q')) ? $request->requestVar('q') : '';
$currentPage = floor( $start / $pageLength ) + 1;
$totalPages = ceil(count($this->results) / $pageLength );
if ($totalPages == 0) {
$totalPages = 1;
}
if ($currentPage > $totalPages) {
$currentPage = $totalPages;
}
$results = new ArrayList();
if($this->results) {
foreach($this->results as $k => $hit) {
if($k < ($currentPage-1)*$pageLength || $k >= ($currentPage*$pageLength)) {
continue;
}
$doc = $hit->getDocument();
$content = $hit->content;
$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')),
'Entity' => DBField::create_field('Varchar', $doc->getFieldValue('Entity')),
'Content' => DBField::create_field('HTMLText', $content),
'Score' => $hit->score,
'Number' => $k + 1,
'ID' => md5($doc->getFieldValue('Link'))
));
$results->push($obj);
}
}
$data['Results'] = $results;
$data['Query'] = DBField::create_field('Text', $query);
$data['TotalResults'] = DBField::create_field('Text', count($this->results));
$data['TotalPages'] = DBField::create_field('Text', $totalPages);
$data['ThisPage'] = DBField::create_field('Text', $currentPage);
$data['StartResult'] = $start + 1;
$data['EndResult'] = $start + count($results);
// Pagination links
if($currentPage > 1) {
$data['PrevUrl'] = DBField::create_field('Text',
$this->buildQueryUrl(array('start' => ($currentPage - 2) * $pageLength))
);
}
if($currentPage < $totalPages) {
$data['NextUrl'] = DBField::create_field('Text',
$this->buildQueryUrl(array('start' => $currentPage * $pageLength))
);
}
if($totalPages > 1) {
// Always show a certain number of pages at the start
for ( $i = 1; $i <= $totalPages; $i++ ) {
$obj = new DataObject();
$obj->IsEllipsis = false;
$obj->PageNumber = $i;
$obj->Link = $this->buildQueryUrl(array(
'start' => ($i - 1) * $pageLength
));
$obj->Current = false;
if ( $i == $currentPage ) $obj->Current = true;
$data['SearchPages']->push($obj);
}
}
return new ArrayData($data);
}
/**
* Build a nice query string for the results
*
* @return string
*/
private function buildQueryUrl($params) {
$url = parse_url($_SERVER['REQUEST_URI']);
if ( ! array_key_exists('query', $url) ) $url['query'] = '';
parse_str($url['query'], $url['query']);
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'] );
// Add extra parameters from argument
$url['query'] = array_merge($url['query'], $params);
$url['query'] = http_build_query($url['query']);
$url = $url['path'] . ($url['query'] ? '?'.$url['query'] : '');
return $url;
}
/**
* @return int
*/
public function getTotalResults() {
return (int) $this->totalResults;
}
/**
* Optimizes the search indexes on the File System
*
* @return void
*/
public function optimizeIndex() {
$index = Zend_Search_Lucene::open(self::get_index_location());
if($index) $index->optimize();
}
/**
* @return String
*/
public function getTitle() {
return ($this->outputController) ? $this->outputController->Title : _t('DocumentationSearch.SEARCH', 'Search');
}
/**
* OpenSearch MetaData fields. For a list of fields consult
* {@link self::get_meta_data()}
*
* @param array
*/
public static function set_meta_data($data) {
if(is_array($data)) {
foreach($data as $key => $value) {
self::$meta_data[strtolower($key)] = $value;
}
}
else {
user_error("set_meta_data must be passed an array", E_USER_ERROR);
}
}
/**
* Returns the meta data needed by opensearch.
*
* @return array
*/
public static function get_meta_data() {
$data = self::$meta_data;
$defaults = array(
'Description' => _t('DocumentationViewer.OPENSEARCHDESC', 'Search the documentation'),
'Tags' => _t('DocumentationViewer.OPENSEARCHTAGS', 'documentation'),
'Contact' => Config::inst()->get('Email', 'admin_email'),
'ShortName' => _t('DocumentationViewer.OPENSEARCHNAME', 'Documentation Search'),
'Author' => 'SilverStripe'
);
foreach($defaults as $key => $value) {
if(isset($data[$key])) $defaults[$key] = $data[$key];
}
return $defaults;
}
/**
* Renders the search results into a template. Either the search results
* template or the Atom feed.
*/
public function renderResults() {
if(!$this->results && $this->query) {
$this->performSearch();
}
if(!$this->outputController) {
return user_error('Call renderResults() on a DocumentationViewer instance.', E_USER_ERROR);
}
$request = $this->outputController->getRequest();
$data = $this->getSearchResults($request);
$templates = array('DocumentationViewer_search');
if($request->requestVar('format') && $request->requestVar('format') == "atom") {
// alter the fields for the opensearch xml.
$title = ($title = $this->getTitle()) ? ' - '. $title : "";
$link = Controller::join_links(
$this->outputController->Link(), 'DocumentationOpenSearchController/description/'
);
$data->setField('Title', $data->Title . $title);
$data->setField('DescriptionURL', $link);
array_unshift($templates, 'OpenSearchResults');
}
return $this->outputController->customise($data)->renderWith($templates);
}
class DocumentationSearch
{
/**
* @var bool - Is search enabled
*/
private static $enabled = false;
/**
* @var bool - Is advanced search enabled
*/
private static $advanced_search_enabled = true;
/**
* @var string - OpenSearch metadata. Please use {@link DocumentationSearch::set_meta_data()}
*/
private static $meta_data = array();
/**
* @var Array Regular expression mapped to a "boost factor" for the searched document.
* Defaults to 1.0, lower to decrease relevancy. Requires reindex.
* Uses {@link DocumentationPage->getRelativePath()} for comparison.
*/
private static $boost_by_path = array();
/**
* @var ArrayList - Results
*/
private $results;
/**
* @var int
*/
private $totalResults;
/**
* @var string
*/
private $query;
/**
* @var Controller
*/
private $outputController;
/**
* Optionally filter by module and version
*
* @var array
*/
private $modules, $versions;
public function setModules($modules)
{
$this->modules = $modules;
}
public function setVersions($versions)
{
$this->versions = $versions;
}
/**
* Set the current search query
*
* @param string
*/
public function setQuery($query)
{
$this->query = $query;
}
/**
* Returns the current search query
*
* @return string
*/
public function getQuery()
{
return $this->query;
}
/**
* Sets the {@link DocumentationViewer} or {@link DocumentationSearch} instance which this search is rendering
* on based on whether it is the results display or RSS feed
*
* @param Controller
*/
public function setOutputController($controller)
{
$this->outputController = $controller;
}
/**
* Folder name for indexes (in the temp folder).
*
* @config
* @var string
*/
private static $index_location;
/**
* @return string
*/
public static function get_index_location()
{
$location = Config::inst()->get('DocumentationSearch', 'index_location');
if (!$location) {
return Controller::join_links(TEMP_FOLDER, 'RebuildLuceneDocsIndex');
}
return $location;
}
/**
* Perform a search query on the index
*/
public function performSearch()
{
try {
$index = Zend_Search_Lucene::open(self::get_index_location());
Zend_Search_Lucene::setResultSetLimit(100);
$query = new Zend_Search_Lucene_Search_Query_Boolean();
$term = Zend_Search_Lucene_Search_QueryParser::parse($this->getQuery());
$query->addSubquery($term, true);
if ($this->modules) {
$moduleQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach ($this->modules as $module) {
$moduleQuery->addTerm(new Zend_Search_Lucene_Index_Term($module, 'Entity'));
}
$query->addSubquery($moduleQuery, true);
}
if ($this->versions) {
$versionQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach ($this->versions as $version) {
$versionQuery->addTerm(new Zend_Search_Lucene_Index_Term($version, 'Version'));
}
$query->addSubquery($versionQuery, true);
}
$er = error_reporting();
error_reporting('E_ALL ^ E_NOTICE');
$this->results = $index->find($query);
error_reporting($er);
$this->totalResults = $index->numDocs();
} catch (Zend_Search_Lucene_Exception $e) {
user_error($e .'. Ensure you have run the rebuld task (/dev/tasks/RebuildLuceneDocsIndex)', E_USER_ERROR);
}
}
/**
* @return ArrayData
*/
public function getSearchResults($request)
{
$pageLength = (isset($_GET['length'])) ? (int) $_GET['length'] : 10;
$data = array(
'Results' => null,
'Query' => null,
'Versions' => DBField::create_field('Text', implode(', ', $this->versions)),
'Modules' => DBField::create_field('Text', implode(', ', $this->modules)),
'Title' => _t('DocumentationSearch.SEARCHRESULTS', 'Search Results'),
'TotalResults' => null,
'TotalPages' => null,
'ThisPage' => null,
'StartResult' => null,
'PageLength' => $pageLength,
'EndResult' => null,
'PrevUrl' => DBField::create_field('Text', 'false'),
'NextUrl' => DBField::create_field('Text', 'false'),
'SearchPages' => new ArrayList()
);
$start = ($request->requestVar('start')) ? (int)$request->requestVar('start') : 0;
$query = ($request->requestVar('q')) ? $request->requestVar('q') : '';
$currentPage = floor($start / $pageLength) + 1;
$totalPages = ceil(count($this->results) / $pageLength);
if ($totalPages == 0) {
$totalPages = 1;
}
if ($currentPage > $totalPages) {
$currentPage = $totalPages;
}
$results = new ArrayList();
if ($this->results) {
foreach ($this->results as $k => $hit) {
if ($k < ($currentPage-1)*$pageLength || $k >= ($currentPage*$pageLength)) {
continue;
}
$doc = $hit->getDocument();
$content = $hit->content;
$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')),
'Entity' => DBField::create_field('Varchar', $doc->getFieldValue('Entity')),
'Content' => DBField::create_field('HTMLText', $content),
'Score' => $hit->score,
'Number' => $k + 1,
'ID' => md5($doc->getFieldValue('Link'))
));
$results->push($obj);
}
}
$data['Results'] = $results;
$data['Query'] = DBField::create_field('Text', $query);
$data['TotalResults'] = DBField::create_field('Text', count($this->results));
$data['TotalPages'] = DBField::create_field('Text', $totalPages);
$data['ThisPage'] = DBField::create_field('Text', $currentPage);
$data['StartResult'] = $start + 1;
$data['EndResult'] = $start + count($results);
// Pagination links
if ($currentPage > 1) {
$data['PrevUrl'] = DBField::create_field('Text',
$this->buildQueryUrl(array('start' => ($currentPage - 2) * $pageLength))
);
}
if ($currentPage < $totalPages) {
$data['NextUrl'] = DBField::create_field('Text',
$this->buildQueryUrl(array('start' => $currentPage * $pageLength))
);
}
if ($totalPages > 1) {
// Always show a certain number of pages at the start
for ($i = 1; $i <= $totalPages; $i++) {
$obj = new DataObject();
$obj->IsEllipsis = false;
$obj->PageNumber = $i;
$obj->Link = $this->buildQueryUrl(array(
'start' => ($i - 1) * $pageLength
));
$obj->Current = false;
if ($i == $currentPage) {
$obj->Current = true;
}
$data['SearchPages']->push($obj);
}
}
return new ArrayData($data);
}
/**
* Build a nice query string for the results
*
* @return string
*/
private function buildQueryUrl($params)
{
$url = parse_url($_SERVER['REQUEST_URI']);
if (! array_key_exists('query', $url)) {
$url['query'] = '';
}
parse_str($url['query'], $url['query']);
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']);
}
// Add extra parameters from argument
$url['query'] = array_merge($url['query'], $params);
$url['query'] = http_build_query($url['query']);
$url = $url['path'] . ($url['query'] ? '?'.$url['query'] : '');
return $url;
}
/**
* @return int
*/
public function getTotalResults()
{
return (int) $this->totalResults;
}
/**
* Optimizes the search indexes on the File System
*
* @return void
*/
public function optimizeIndex()
{
$index = Zend_Search_Lucene::open(self::get_index_location());
if ($index) {
$index->optimize();
}
}
/**
* @return String
*/
public function getTitle()
{
return ($this->outputController) ? $this->outputController->Title : _t('DocumentationSearch.SEARCH', 'Search');
}
/**
* OpenSearch MetaData fields. For a list of fields consult
* {@link self::get_meta_data()}
*
* @param array
*/
public static function set_meta_data($data)
{
if (is_array($data)) {
foreach ($data as $key => $value) {
self::$meta_data[strtolower($key)] = $value;
}
} else {
user_error("set_meta_data must be passed an array", E_USER_ERROR);
}
}
/**
* Returns the meta data needed by opensearch.
*
* @return array
*/
public static function get_meta_data()
{
$data = self::$meta_data;
$defaults = array(
'Description' => _t('DocumentationViewer.OPENSEARCHDESC', 'Search the documentation'),
'Tags' => _t('DocumentationViewer.OPENSEARCHTAGS', 'documentation'),
'Contact' => Config::inst()->get('Email', 'admin_email'),
'ShortName' => _t('DocumentationViewer.OPENSEARCHNAME', 'Documentation Search'),
'Author' => 'SilverStripe'
);
foreach ($defaults as $key => $value) {
if (isset($data[$key])) {
$defaults[$key] = $data[$key];
}
}
return $defaults;
}
/**
* Renders the search results into a template. Either the search results
* template or the Atom feed.
*/
public function renderResults()
{
if (!$this->results && $this->query) {
$this->performSearch();
}
if (!$this->outputController) {
return user_error('Call renderResults() on a DocumentationViewer instance.', E_USER_ERROR);
}
$request = $this->outputController->getRequest();
$data = $this->getSearchResults($request);
$templates = array('DocumentationViewer_search');
if ($request->requestVar('format') && $request->requestVar('format') == "atom") {
// alter the fields for the opensearch xml.
$title = ($title = $this->getTitle()) ? ' - '. $title : "";
$link = Controller::join_links(
$this->outputController->Link(), 'DocumentationOpenSearchController/description/'
);
$data->setField('Title', $data->Title . $title);
$data->setField('DescriptionURL', $link);
array_unshift($templates, 'OpenSearchResults');
}
return $this->outputController->customise($data)->renderWith($templates);
}
}

View File

@ -7,40 +7,42 @@
* @package docsviewer
*/
class DocumentationOpenSearchController extends Controller {
class DocumentationOpenSearchController extends Controller
{
private static $allowed_actions = array(
'description'
);
private static $allowed_actions = array(
'description'
);
public function index()
{
return $this->httpError(404);
}
public function index() {
return $this->httpError(404);
}
public function description()
{
$viewer = new DocumentationViewer();
public function description() {
$viewer = new DocumentationViewer();
if (!$viewer->canView()) {
return Security::permissionFailure($this);
}
if(!$viewer->canView()) {
return Security::permissionFailure($this);
}
if (!Config::inst()->get('DocumentationSearch', 'enabled')) {
return $this->httpError('404');
}
if(!Config::inst()->get('DocumentationSearch', 'enabled')) {
return $this->httpError('404');
}
$data = DocumentationSearch::get_meta_data();
$link = Director::absoluteBaseUrl() .
$data['SearchPageLink'] = Controller::join_links(
$viewer->Link(),
'results/?Search={searchTerms}&start={startIndex}&length={count}&action_results=1'
);
$data = DocumentationSearch::get_meta_data();
$link = Director::absoluteBaseUrl() .
$data['SearchPageLink'] = Controller::join_links(
$viewer->Link(),
'results/?Search={searchTerms}&start={startIndex}&length={count}&action_results=1'
);
$data['SearchPageAtom'] = $data['SearchPageLink'] . '&format=atom';
$data['SearchPageAtom'] = $data['SearchPageLink'] . '&format=atom';
return $this->customise(
new ArrayData($data)
)->renderWith(array(
'OpenSearchDescription'
));
}
return $this->customise(
new ArrayData($data)
)->renderWith(array(
'OpenSearchDescription'
));
}
}

View File

@ -12,665 +12,691 @@
* @package docsviewer
*/
class DocumentationViewer extends Controller {
/**
* @var array
*/
private static $extensions = array(
'DocumentationViewerVersionWarning',
'DocumentationSearchExtension'
);
/**
* @var string
*/
private static $google_analytics_code = '';
/**
* @var string
*/
private static $documentation_title = 'SilverStripe Documentation';
/**
* @var array
*/
private static $allowed_actions = array(
'all',
'results',
'handleAction'
);
/**
* The string name of the currently accessed {@link DocumentationEntity}
* object. To access the entire object use {@link getEntity()}
*
* @var string
*/
protected $entity = '';
/**
* @var DocumentationPage
*/
protected $record;
/**
* @var DocumentationManifest
*/
protected $manifest;
/**
* @config
*
* @var string same as the routing pattern set through Director::addRules().
*/
private static $link_base = 'dev/docs/';
/**
* @config
*
* @var string|array Optional permission check
*/
private static $check_permission = 'ADMIN';
/**
* @var array map of modules to edit links.
* @see {@link getEditLink()}
*/
private static $edit_links = array();
/**
*
*/
public function init() {
parent::init();
if(!$this->canView()) {
return Security::permissionFailure($this);
}
Requirements::javascript('//use.typekit.net/emt4dhq.js');
Requirements::customScript('try{Typekit.load();}catch(e){}');
Requirements::javascript(THIRDPARTY_DIR .'/jquery/jquery.js');
Requirements::javascript('https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js');
Requirements::javascript(DOCSVIEWER_DIR .'/javascript/DocumentationViewer.js');
Requirements::combine_files('docs.css', array(
DOCSVIEWER_DIR .'/css/normalize.css',
DOCSVIEWER_DIR .'/css/utilities.css',
DOCSVIEWER_DIR .'/css/typography.css',
DOCSVIEWER_DIR .'/css/forms.css',
DOCSVIEWER_DIR .'/css/layout.css',
DOCSVIEWER_DIR .'/css/small.css'
));
}
/**
* Can the user view this documentation. Hides all functionality for private
* wikis.
*
* @return bool
*/
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) {
return true;
}
public function checkAccessAction($action) {
return true;
}
/**
* Overloaded to avoid "action doesn't exist" errors - all URL parts in
* this controller are virtual and handled through handleRequest(), not
* controller methods.
*
* @param $request
* @param $action
*
* @return SS_HTTPResponse
*/
public function handleAction($request, $action) {
// if we submitted a form, let that pass
if(!$request->isGET()) {
return parent::handleAction($request, $action);
}
$url = $request->getURL();
//
// 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)) {
$this->response = new SS_HTTPResponse();
$this->response->redirect(
DocumentationHelper::trim_extension_off($url) .'/',
301
);
$request->shift();
$request->shift();
return $this->response;
}
//
// Strip off the base url
//
$base = ltrim(
Config::inst()->get('DocumentationViewer', 'link_base'), '/'
);
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)) {
// the first param is a shortcode for a page so redirect the user to
// the short code.
$this->response = new SS_HTTPResponse();
$this->response->redirect($link, 301);
$request->shift();
$request->shift();
return $this->response;
}
//
// Validate the language provided. Language is a required URL parameter.
// as we use it for generic interfaces and language selection. If
// language is not set, redirects to 'en'
//
$languages = i18n::get_common_languages();
if(!$lang = $request->param('Lang')) {
$lang = $request->param('Action');
$action = $request->param('ID');
} else {
$action = $request->param('Action');
}
if(!$lang) {
return $this->redirect($this->Link('en'));
} else if(!isset($languages[$lang])) {
return $this->httpError(404);
}
$request->shift(10);
$allowed = $this->config()->allowed_actions;
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.
//
return parent::handleAction($request, $action);
} else {
//
// look up the manifest to see find the nearest match against the
// list of the URL. If the URL exists then set that as the current
// page to match against.
// strip off any extensions.
// if($cleaned !== $url) {
// $redirect = new SS_HTTPResponse();
// return $redirect->redirect($cleaned, 302);
// }
if($record = $this->getManifest()->getPage($url)) {
$this->record = $record;
$this->init();
$type = get_class($this->record);
$body = $this->renderWith(array(
"DocumentationViewer_{$type}",
"DocumentationViewer"
));
return new SS_HTTPResponse($body, 200);
} else if($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) {
$body = $this->renderWith(array(
"DocumentationViewer_DocumentationFolder",
"DocumentationViewer"
));
return new SS_HTTPResponse($body, 200);
}
}
return $this->httpError(404);
}
/**
* @param int $status
* @param string $message
*
* @return SS_HTTPResponse
*/
public function httpError($status, $message = null) {
$this->init();
$class = get_class($this);
$body = $this->customise(new ArrayData(array(
'Message' => $message
)))->renderWith(array("{$class}_error", $class));
return new SS_HTTPResponse($body, $status);
}
/**
* @return DocumentationManifest
*/
public function getManifest() {
if(!$this->manifest) {
$flush = SapphireTest::is_running_test() || (isset($_GET['flush']));
$this->manifest = new DocumentationManifest($flush);
}
return $this->manifest;
}
/**
* @return string
*/
public function getLanguage() {
if(!$lang = $this->request->param('Lang')) {
$lang = $this->request->param('Action');
}
return $lang;
}
/**
* Generate a list of {@link Documentation } which have been registered and which can
* be documented.
*
* @return DataObject
*/
public function getMenu() {
$entities = $this->getManifest()->getEntities();
$output = new ArrayList();
$record = $this->getPage();
$current = $this->getEntity();
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()) {
continue;
}
if($current && $checkVers) {
if($entity->getVersion() !== $current->getVersion()) {
continue;
}
}
$mode = 'link';
$children = new ArrayList();
if($entity->hasRecord($record) || $entity->getIsDefaultEntity()) {
$mode = 'current';
// add children
$children = $this->getManifest()->getChildrenFor(
$entity->getPath(), ($record) ? $record->getPath() : $entity->getPath()
);
} else {
if($current && $current->getKey() == $entity->getKey()) {
continue;
}
}
$link = $entity->Link();
$output->push(new ArrayData(array(
'Title' => $entity->getTitle(),
'Link' => $link,
'LinkingMode' => $mode,
'DefaultEntity' => $entity->getIsDefaultEntity(),
'Children' => $children
)));
}
return $output;
}
/**
* Return the content for the page. If its an actual documentation page then
* display the content from the page, otherwise display the contents from
* the index.md file if its a folder
*
* @return HTMLText
*/
public function getContent() {
$page = $this->getPage();
$html = $page->getHTML();
$html = $this->replaceChildrenCalls($html);
return $html;
}
public function replaceChildrenCalls($html) {
$codes = new ShortcodeParser();
$codes->register('CHILDREN', array($this, 'includeChildren'));
return $codes->parse($html);
}
/**
* Short code parser
*/
public function includeChildren($args) {
if(isset($args['Folder'])) {
$children = $this->getManifest()->getChildrenFor(
Controller::join_links(dirname($this->record->getPath()), $args['Folder'])
);
} else {
$children = $this->getManifest()->getChildrenFor(
dirname($this->record->getPath())
);
}
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), '/')) {
unset($children[$k]);
}
}
}
}
return $this->customise(new ArrayData(array(
'Children' => $children
)))->renderWith('Includes/DocumentationPages');
}
/**
* @return ArrayList
*/
public function getChildren() {
if($this->record instanceof DocumentationFolder) {
return $this->getManifest()->getChildrenFor(
$this->record->getPath()
);
} else if($this->record) {
return $this->getManifest()->getChildrenFor(
dirname($this->record->getPath())
);
}
return new ArrayList();
}
/**
* Generate a list of breadcrumbs for the user.
*
* @return ArrayList
*/
public function getBreadcrumbs() {
if($this->record) {
return $this->getManifest()->generateBreadcrumbs(
$this->record,
$this->record->getEntity()
);
}
}
/**
* @return DocumentationPage
*/
public function getPage() {
return $this->record;
}
/**
* @return DocumentationEntity
*/
public function getEntity() {
return ($this->record) ? $this->record->getEntity() : null;
}
/**
* @return ArrayList
*/
public function getVersions() {
return $this->getManifest()->getVersions($this->getEntity());
}
/**
* Generate a string for the title tag in the URL.
*
* @return string
*/
public function getTitle() {
return ($this->record) ? $this->record->getTitle() : null;
}
/**
* @return string
*/
public function AbsoluteLink($action) {
return Controller::join_links(
Director::absoluteBaseUrl(),
$this->Link($action)
);
}
/**
* Return the base link to this documentation location.
*
* @return string
*/
public function Link($action = '') {
$link = Controller::join_links(
Config::inst()->get('DocumentationViewer', 'link_base'),
$this->getLanguage(),
$action,
'/'
);
return $link;
}
/**
* Generate a list of all the pages in the documentation grouped by the
* first letter of the page.
*
* @return GroupedList
*/
public function AllPages() {
$pages = $this->getManifest()->getPages();
$output = new ArrayList();
foreach($pages as $url => $page) {
$first = strtoupper(trim(substr($page['title'], 0, 1)));
if($first) {
$output->push(new ArrayData(array(
'Link' => $url,
'Title' => $page['title'],
'FirstLetter' => $first
)));
}
}
return GroupedList::create($output->sort('Title', 'ASC'));
}
/**
* Documentation Search Form. Allows filtering of the results by many entities
* and multiple versions.
*
* @return Form
*/
public function DocumentationSearchForm() {
if(!Config::inst()->get('DocumentationSearch','enabled')) {
return false;
}
return new DocumentationSearchForm($this);
}
/**
* Sets the mapping between a entity name and the link for the end user
* to jump into editing the documentation.
*
* Some variables are replaced:
* - %version%
* - %entity%
* - %path%
* - %lang%
*
* For example to provide an edit link to the framework module in github:
*
* <code>
* DocumentationViewer::set_edit_link(
* 'framework',
* 'https://github.com/silverstripe/%entity%/edit/%version%/docs/%lang%/%path%',
* $opts
* ));
* </code>
*
* @param string module name
* @param string link
* @param array options ('rewritetrunktomaster')
*/
public static function set_edit_link($module, $link, $options = array()) {
self::$edit_links[$module] = array(
'url' => $link,
'options' => $options
);
}
/**
* Returns an edit link to the current page (optional).
*
* @return string
*/
public function getEditLink() {
$page = $this->getPage();
if($page) {
$entity = $page->getEntity();
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()){
$version = $entity->getBranch();
}
if($version == "trunk" && (isset($url['options']['rewritetrunktomaster']))) {
if($url['options']['rewritetrunktomaster']) {
$version = "master";
}
}
return str_replace(
array('%entity%', '%lang%', '%version%', '%path%'),
array(
$entity->title,
$this->getLanguage(),
$version,
ltrim($page->getRelativePath(), '/')
),
$url['url']
);
}
}
return false;
}
/**
* Returns the next page. Either retrieves the sibling of the current page
* or return the next sibling of the parent page.
*
* @return DocumentationPage
*/
public function getNextPage() {
return ($this->record)
? $this->getManifest()->getNextPage(
$this->record->getPath(), $this->getEntity()->getPath())
: null;
}
/**
* Returns the previous page. Either returns the previous sibling or the
* parent of this page
*
* @return DocumentationPage
*/
public function getPreviousPage() {
return ($this->record)
? $this->getManifest()->getPreviousPage(
$this->record->getPath(), $this->getEntity()->getPath())
: null;
}
/**
* @return string
*/
public function getGoogleAnalyticsCode() {
$code = $this->config()->get('google_analytics_code');
if($code) {
return $code;
}
}
/**
* @return string
*/
public function getDocumentationTitle() {
return $this->config()->get('documentation_title');
}
public function getDocumentationBaseHref() {
return Config::inst()->get('DocumentationViewer', 'link_base');
}
class DocumentationViewer extends Controller
{
/**
* @var array
*/
private static $extensions = array(
'DocumentationViewerVersionWarning',
'DocumentationSearchExtension'
);
/**
* @var string
*/
private static $google_analytics_code = '';
/**
* @var string
*/
private static $documentation_title = 'SilverStripe Documentation';
/**
* @var array
*/
private static $allowed_actions = array(
'all',
'results',
'handleAction'
);
/**
* The string name of the currently accessed {@link DocumentationEntity}
* object. To access the entire object use {@link getEntity()}
*
* @var string
*/
protected $entity = '';
/**
* @var DocumentationPage
*/
protected $record;
/**
* @var DocumentationManifest
*/
protected $manifest;
/**
* @config
*
* @var string same as the routing pattern set through Director::addRules().
*/
private static $link_base = 'dev/docs/';
/**
* @config
*
* @var string|array Optional permission check
*/
private static $check_permission = 'ADMIN';
/**
* @var array map of modules to edit links.
* @see {@link getEditLink()}
*/
private static $edit_links = array();
/**
*
*/
public function init()
{
parent::init();
if (!$this->canView()) {
return Security::permissionFailure($this);
}
Requirements::javascript('//use.typekit.net/emt4dhq.js');
Requirements::customScript('try{Typekit.load();}catch(e){}');
Requirements::javascript(THIRDPARTY_DIR .'/jquery/jquery.js');
Requirements::javascript('https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js');
Requirements::javascript(DOCSVIEWER_DIR .'/javascript/DocumentationViewer.js');
Requirements::combine_files('docs.css', array(
DOCSVIEWER_DIR .'/css/normalize.css',
DOCSVIEWER_DIR .'/css/utilities.css',
DOCSVIEWER_DIR .'/css/typography.css',
DOCSVIEWER_DIR .'/css/forms.css',
DOCSVIEWER_DIR .'/css/layout.css',
DOCSVIEWER_DIR .'/css/small.css'
));
}
/**
* Can the user view this documentation. Hides all functionality for private
* wikis.
*
* @return bool
*/
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)
{
return true;
}
public function checkAccessAction($action)
{
return true;
}
/**
* Overloaded to avoid "action doesn't exist" errors - all URL parts in
* this controller are virtual and handled through handleRequest(), not
* controller methods.
*
* @param $request
* @param $action
*
* @return SS_HTTPResponse
*/
public function handleAction($request, $action)
{
// if we submitted a form, let that pass
if (!$request->isGET()) {
return parent::handleAction($request, $action);
}
$url = $request->getURL();
//
// 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)) {
$this->response = new SS_HTTPResponse();
$this->response->redirect(
DocumentationHelper::trim_extension_off($url) .'/',
301
);
$request->shift();
$request->shift();
return $this->response;
}
//
// Strip off the base url
//
$base = ltrim(
Config::inst()->get('DocumentationViewer', 'link_base'), '/'
);
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)) {
// the first param is a shortcode for a page so redirect the user to
// the short code.
$this->response = new SS_HTTPResponse();
$this->response->redirect($link, 301);
$request->shift();
$request->shift();
return $this->response;
}
//
// Validate the language provided. Language is a required URL parameter.
// as we use it for generic interfaces and language selection. If
// language is not set, redirects to 'en'
//
$languages = i18n::get_common_languages();
if (!$lang = $request->param('Lang')) {
$lang = $request->param('Action');
$action = $request->param('ID');
} else {
$action = $request->param('Action');
}
if (!$lang) {
return $this->redirect($this->Link('en'));
} elseif (!isset($languages[$lang])) {
return $this->httpError(404);
}
$request->shift(10);
$allowed = $this->config()->allowed_actions;
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.
//
return parent::handleAction($request, $action);
} else {
//
// look up the manifest to see find the nearest match against the
// list of the URL. If the URL exists then set that as the current
// page to match against.
// strip off any extensions.
// if($cleaned !== $url) {
// $redirect = new SS_HTTPResponse();
// return $redirect->redirect($cleaned, 302);
// }
if ($record = $this->getManifest()->getPage($url)) {
$this->record = $record;
$this->init();
$type = get_class($this->record);
$body = $this->renderWith(array(
"DocumentationViewer_{$type}",
"DocumentationViewer"
));
return new SS_HTTPResponse($body, 200);
} elseif ($redirect = $this->getManifest()->getRedirect($url)) {
$response = new SS_HTTPResponse();
$to = Controller::join_links(Director::baseURL(), $base, $redirect);
return $response->redirect($to, 301);
} elseif (!$url || $url == $lang) {
$body = $this->renderWith(array(
"DocumentationViewer_DocumentationFolder",
"DocumentationViewer"
));
return new SS_HTTPResponse($body, 200);
}
}
return $this->httpError(404);
}
/**
* @param int $status
* @param string $message
*
* @return SS_HTTPResponse
*/
public function httpError($status, $message = null)
{
$this->init();
$class = get_class($this);
$body = $this->customise(new ArrayData(array(
'Message' => $message
)))->renderWith(array("{$class}_error", $class));
return new SS_HTTPResponse($body, $status);
}
/**
* @return DocumentationManifest
*/
public function getManifest()
{
if (!$this->manifest) {
$flush = SapphireTest::is_running_test() || (isset($_GET['flush']));
$this->manifest = new DocumentationManifest($flush);
}
return $this->manifest;
}
/**
* @return string
*/
public function getLanguage()
{
if (!$lang = $this->request->param('Lang')) {
$lang = $this->request->param('Action');
}
return $lang;
}
/**
* Generate a list of {@link Documentation } which have been registered and which can
* be documented.
*
* @return DataObject
*/
public function getMenu()
{
$entities = $this->getManifest()->getEntities();
$output = new ArrayList();
$record = $this->getPage();
$current = $this->getEntity();
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()) {
continue;
}
if ($current && $checkVers) {
if ($entity->getVersion() !== $current->getVersion()) {
continue;
}
}
$mode = 'link';
$children = new ArrayList();
if ($entity->hasRecord($record) || $entity->getIsDefaultEntity()) {
$mode = 'current';
// add children
$children = $this->getManifest()->getChildrenFor(
$entity->getPath(), ($record) ? $record->getPath() : $entity->getPath()
);
} else {
if ($current && $current->getKey() == $entity->getKey()) {
continue;
}
}
$link = $entity->Link();
$output->push(new ArrayData(array(
'Title' => $entity->getTitle(),
'Link' => $link,
'LinkingMode' => $mode,
'DefaultEntity' => $entity->getIsDefaultEntity(),
'Children' => $children
)));
}
return $output;
}
/**
* Return the content for the page. If its an actual documentation page then
* display the content from the page, otherwise display the contents from
* the index.md file if its a folder
*
* @return HTMLText
*/
public function getContent()
{
$page = $this->getPage();
$html = $page->getHTML();
$html = $this->replaceChildrenCalls($html);
return $html;
}
public function replaceChildrenCalls($html)
{
$codes = new ShortcodeParser();
$codes->register('CHILDREN', array($this, 'includeChildren'));
return $codes->parse($html);
}
/**
* Short code parser
*/
public function includeChildren($args)
{
if (isset($args['Folder'])) {
$children = $this->getManifest()->getChildrenFor(
Controller::join_links(dirname($this->record->getPath()), $args['Folder'])
);
} else {
$children = $this->getManifest()->getChildrenFor(
dirname($this->record->getPath())
);
}
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), '/')) {
unset($children[$k]);
}
}
}
}
return $this->customise(new ArrayData(array(
'Children' => $children
)))->renderWith('Includes/DocumentationPages');
}
/**
* @return ArrayList
*/
public function getChildren()
{
if ($this->record instanceof DocumentationFolder) {
return $this->getManifest()->getChildrenFor(
$this->record->getPath()
);
} elseif ($this->record) {
return $this->getManifest()->getChildrenFor(
dirname($this->record->getPath())
);
}
return new ArrayList();
}
/**
* Generate a list of breadcrumbs for the user.
*
* @return ArrayList
*/
public function getBreadcrumbs()
{
if ($this->record) {
return $this->getManifest()->generateBreadcrumbs(
$this->record,
$this->record->getEntity()
);
}
}
/**
* @return DocumentationPage
*/
public function getPage()
{
return $this->record;
}
/**
* @return DocumentationEntity
*/
public function getEntity()
{
return ($this->record) ? $this->record->getEntity() : null;
}
/**
* @return ArrayList
*/
public function getVersions()
{
return $this->getManifest()->getVersions($this->getEntity());
}
/**
* Generate a string for the title tag in the URL.
*
* @return string
*/
public function getTitle()
{
return ($this->record) ? $this->record->getTitle() : null;
}
/**
* @return string
*/
public function AbsoluteLink($action)
{
return Controller::join_links(
Director::absoluteBaseUrl(),
$this->Link($action)
);
}
/**
* Return the base link to this documentation location.
*
* @return string
*/
public function Link($action = '')
{
$link = Controller::join_links(
Config::inst()->get('DocumentationViewer', 'link_base'),
$this->getLanguage(),
$action,
'/'
);
return $link;
}
/**
* Generate a list of all the pages in the documentation grouped by the
* first letter of the page.
*
* @return GroupedList
*/
public function AllPages()
{
$pages = $this->getManifest()->getPages();
$output = new ArrayList();
foreach ($pages as $url => $page) {
$first = strtoupper(trim(substr($page['title'], 0, 1)));
if ($first) {
$output->push(new ArrayData(array(
'Link' => $url,
'Title' => $page['title'],
'FirstLetter' => $first
)));
}
}
return GroupedList::create($output->sort('Title', 'ASC'));
}
/**
* Documentation Search Form. Allows filtering of the results by many entities
* and multiple versions.
*
* @return Form
*/
public function DocumentationSearchForm()
{
if (!Config::inst()->get('DocumentationSearch', 'enabled')) {
return false;
}
return new DocumentationSearchForm($this);
}
/**
* Sets the mapping between a entity name and the link for the end user
* to jump into editing the documentation.
*
* Some variables are replaced:
* - %version%
* - %entity%
* - %path%
* - %lang%
*
* For example to provide an edit link to the framework module in github:
*
* <code>
* DocumentationViewer::set_edit_link(
* 'framework',
* 'https://github.com/silverstripe/%entity%/edit/%version%/docs/%lang%/%path%',
* $opts
* ));
* </code>
*
* @param string module name
* @param string link
* @param array options ('rewritetrunktomaster')
*/
public static function set_edit_link($module, $link, $options = array())
{
self::$edit_links[$module] = array(
'url' => $link,
'options' => $options
);
}
/**
* Returns an edit link to the current page (optional).
*
* @return string
*/
public function getEditLink()
{
$page = $this->getPage();
if ($page) {
$entity = $page->getEntity();
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()) {
$version = $entity->getBranch();
}
if ($version == "trunk" && (isset($url['options']['rewritetrunktomaster']))) {
if ($url['options']['rewritetrunktomaster']) {
$version = "master";
}
}
return str_replace(
array('%entity%', '%lang%', '%version%', '%path%'),
array(
$entity->title,
$this->getLanguage(),
$version,
ltrim($page->getRelativePath(), '/')
),
$url['url']
);
}
}
return false;
}
/**
* Returns the next page. Either retrieves the sibling of the current page
* or return the next sibling of the parent page.
*
* @return DocumentationPage
*/
public function getNextPage()
{
return ($this->record)
? $this->getManifest()->getNextPage(
$this->record->getPath(), $this->getEntity()->getPath())
: null;
}
/**
* Returns the previous page. Either returns the previous sibling or the
* parent of this page
*
* @return DocumentationPage
*/
public function getPreviousPage()
{
return ($this->record)
? $this->getManifest()->getPreviousPage(
$this->record->getPath(), $this->getEntity()->getPath())
: null;
}
/**
* @return string
*/
public function getGoogleAnalyticsCode()
{
$code = $this->config()->get('google_analytics_code');
if ($code) {
return $code;
}
}
/**
* @return string
*/
public function getDocumentationTitle()
{
return $this->config()->get('documentation_title');
}
public function getDocumentationBaseHref()
{
return Config::inst()->get('DocumentationViewer', 'link_base');
}
}

View File

@ -1,93 +1,96 @@
<?php
class DocumentationSearchExtension extends Extension {
class DocumentationSearchExtension extends Extension
{
/**
* Return an array of folders and titles
*
* @return array
*/
public function getSearchedEntities()
{
$entities = array();
/**
* Return an array of folders and titles
*
* @return array
*/
public function getSearchedEntities() {
$entities = array();
if (!empty($_REQUEST['Entities'])) {
if (is_array($_REQUEST['Entities'])) {
$entities = Convert::raw2att($_REQUEST['Entities']);
} else {
$entities = explode(',', Convert::raw2att($_REQUEST['Entities']));
$entities = array_combine($entities, $entities);
}
}
if(!empty($_REQUEST['Entities'])) {
if(is_array($_REQUEST['Entities'])) {
$entities = Convert::raw2att($_REQUEST['Entities']);
}
else {
$entities = explode(',', Convert::raw2att($_REQUEST['Entities']));
$entities = array_combine($entities, $entities);
}
}
return $entities;
}
return $entities;
}
/**
* Return an array of versions that we're allowed to return
*
* @return array
*/
public function getSearchedVersions()
{
$versions = array();
/**
* Return an array of versions that we're allowed to return
*
* @return array
*/
public function getSearchedVersions() {
$versions = array();
if (!empty($_REQUEST['Versions'])) {
if (is_array($_REQUEST['Versions'])) {
$versions = Convert::raw2att($_REQUEST['Versions']);
$versions = array_combine($versions, $versions);
} else {
$version = Convert::raw2att($_REQUEST['Versions']);
$versions[$version] = $version;
}
}
if(!empty($_REQUEST['Versions'])) {
if(is_array($_REQUEST['Versions'])) {
$versions = Convert::raw2att($_REQUEST['Versions']);
$versions = array_combine($versions, $versions);
}
else {
$version = Convert::raw2att($_REQUEST['Versions']);
$versions[$version] = $version;
}
}
return $versions;
}
return $versions;
}
/**
* Return the current search query.
*
* @return HTMLText|null
*/
public function getSearchQuery()
{
if (isset($_REQUEST['Search'])) {
return DBField::create_field('HTMLText', $_REQUEST['Search']);
} elseif (isset($_REQUEST['q'])) {
return DBField::create_field('HTMLText', $_REQUEST['q']);
}
}
/**
* Return the current search query.
*
* @return HTMLText|null
*/
public function getSearchQuery() {
if(isset($_REQUEST['Search'])) {
return DBField::create_field('HTMLText', $_REQUEST['Search']);
} else if(isset($_REQUEST['q'])) {
return DBField::create_field('HTMLText', $_REQUEST['q']);
}
}
/**
* Past straight to results, display and encode the query.
*/
public function getSearchResults()
{
$query = $this->getSearchQuery();
/**
* Past straight to results, display and encode the query.
*/
public function getSearchResults() {
$query = $this->getSearchQuery();
$search = new DocumentationSearch();
$search->setQuery($query);
$search->setVersions($this->getSearchedVersions());
$search->setModules($this->getSearchedEntities());
$search->setOutputController($this->owner);
$search = new DocumentationSearch();
$search->setQuery($query);
$search->setVersions($this->getSearchedVersions());
$search->setModules($this->getSearchedEntities());
$search->setOutputController($this->owner);
return $search->renderResults();
}
return $search->renderResults();
}
/**
* Returns an search form which allows people to express more complex rules
* and options than the plain search form.
*
* @return Form
*/
public function AdvancedSearchForm() {
return new DocumentationAdvancedSearchForm($this->owner);
}
/**
* @return bool
*/
public function getAdvancedSearchEnabled() {
return Config::inst()->get("DocumentationSearch", 'advanced_search_enabled');
}
/**
* Returns an search form which allows people to express more complex rules
* and options than the plain search form.
*
* @return Form
*/
public function AdvancedSearchForm()
{
return new DocumentationAdvancedSearchForm($this->owner);
}
/**
* @return bool
*/
public function getAdvancedSearchEnabled()
{
return Config::inst()->get("DocumentationSearch", 'advanced_search_enabled');
}
}

View File

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

View File

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

View File

@ -3,56 +3,57 @@
/**
* @package docsviewer
*/
class DocumentationAdvancedSearchForm extends Form {
class DocumentationAdvancedSearchForm extends Form
{
public function __construct($controller)
{
$versions = $controller->getManifest()->getAllVersions();
$entities = $controller->getManifest()->getEntities();
public function __construct($controller) {
$versions = $controller->getManifest()->getAllVersions();
$entities = $controller->getManifest()->getEntities();
$q = ($q = $controller->getSearchQuery()) ? $q->NoHTML() : "";
$q = ($q = $controller->getSearchQuery()) ? $q->NoHTML() : "";
// klude to take an array of objects down to a simple map
$entities = $entities->map('Key', 'Title');
// klude to take an array of objects down to a simple map
$entities = $entities->map('Key', 'Title');
// if we haven't gone any search limit then we're searching everything
$searchedEntities = $controller->getSearchedEntities();
// if we haven't gone any search limit then we're searching everything
$searchedEntities = $controller->getSearchedEntities();
if (count($searchedEntities) < 1) {
$searchedEntities = $entities;
}
if(count($searchedEntities) < 1) {
$searchedEntities = $entities;
}
$searchedVersions = $controller->getSearchedVersions();
$searchedVersions = $controller->getSearchedVersions();
if (count($searchedVersions) < 1) {
$searchedVersions = $versions;
}
if(count($searchedVersions) < 1) {
$searchedVersions = $versions;
}
$fields = FieldList::create(
TextField::create('q', _t('DocumentationViewer.KEYWORDS', 'Keywords'), $q),
//CheckboxSetField::create('Entities', _t('DocumentationViewer.MODULES', 'Modules'), $entities, $searchedEntities),
CheckboxSetField::create(
'Versions',
_t('DocumentationViewer.VERSIONS', 'Versions'),
$versions, $searchedVersions
)
);
$fields = FieldList::create(
TextField::create('q', _t('DocumentationViewer.KEYWORDS', 'Keywords'), $q),
//CheckboxSetField::create('Entities', _t('DocumentationViewer.MODULES', 'Modules'), $entities, $searchedEntities),
CheckboxSetField::create(
'Versions',
_t('DocumentationViewer.VERSIONS', 'Versions'),
$versions, $searchedVersions
)
);
$actions = FieldList::create(
FormAction::create('results', _t('DocumentationViewer.SEARCH', 'Search'))
);
$actions = FieldList::create(
FormAction::create('results', _t('DocumentationViewer.SEARCH', 'Search'))
);
$required = RequiredFields::create(array('Search'));
$required = RequiredFields::create(array('Search'));
parent::__construct(
$controller,
'AdvancedSearchForm',
$fields,
$actions,
$required
);
parent::__construct(
$controller,
'AdvancedSearchForm',
$fields,
$actions,
$required
);
$this->disableSecurityToken();
$this->setFormMethod('GET');
$this->setFormAction($controller->Link('results'));
}
$this->disableSecurityToken();
$this->setFormMethod('GET');
$this->setFormAction($controller->Link('results'));
}
}

View File

@ -1,37 +1,36 @@
<?php
class DocumentationSearchForm extends Form {
class DocumentationSearchForm extends Form
{
public function __construct($controller)
{
$fields = new FieldList(
TextField::create('q', _t('DocumentationViewer.SEARCH', 'Search'), '')
->setAttribute('placeholder', _t('DocumentationViewer.SEARCH', 'Search'))
);
public function __construct($controller) {
$page = $controller->getPage();
if ($page) {
$versions = HiddenField::create(
'Versions',
_t('DocumentationViewer.VERSIONS', 'Versions'),
$page->getEntity()->getVersion()
);
$fields = new FieldList(
TextField::create('q', _t('DocumentationViewer.SEARCH', 'Search'), '')
->setAttribute('placeholder', _t('DocumentationViewer.SEARCH', 'Search'))
);
$fields->push($versions);
}
$page = $controller->getPage();
$actions = new FieldList(
new FormAction('results', _t('DocumentationViewer.SEARCH', 'Search'))
);
if($page){
$versions = HiddenField::create(
'Versions',
_t('DocumentationViewer.VERSIONS', 'Versions'),
$page->getEntity()->getVersion()
);
parent::__construct($controller, 'DocumentationSearchForm', $fields, $actions);
$fields->push($versions);
}
$this->disableSecurityToken();
$this->setFormMethod('GET');
$this->setFormAction($controller->Link('results'));
$actions = new FieldList(
new FormAction('results', _t('DocumentationViewer.SEARCH', 'Search'))
);
parent::__construct($controller, 'DocumentationSearchForm', $fields, $actions);
$this->disableSecurityToken();
$this->setFormMethod('GET');
$this->setFormAction($controller->Link('results'));
$this->addExtraClass('search');
}
$this->addExtraClass('search');
}
}

View File

@ -16,287 +16,308 @@
* @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
* title for, but matching needs to occur on a specific key.
*
* @var string $key
*/
protected $key;
/**
* 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
* title for, but matching needs to occur on a specific key.
*
* @var string $key
*/
protected $key;
/**
* The human readable title of this entity. Set when the module is
* registered.
*
* @var string $title
*/
protected $title;
/**
* The human readable title of this entity. Set when the module is
* registered.
*
* @var string $title
*/
protected $title;
/**
* If the system is setup to only document one entity then you may only
* want to show a single entity in the URL and the sidebar. Set this when
* you register the entity with the key `DefaultEntity` and the URL will
* not include any version or language information.
*
* @var boolean $default_entity
*/
protected $defaultEntity;
/**
* If the system is setup to only document one entity then you may only
* want to show a single entity in the URL and the sidebar. Set this when
* you register the entity with the key `DefaultEntity` and the URL will
* not include any version or language information.
*
* @var boolean $default_entity
*/
protected $defaultEntity;
/**
* @var mixed
*/
protected $path;
/**
* @var mixed
*/
protected $path;
/**
* @see {@link http://php.net/manual/en/function.version-compare.php}
* @var float $version
*/
protected $version;
/**
* @see {@link http://php.net/manual/en/function.version-compare.php}
* @var float $version
*/
protected $version;
/**
* The repository branch name (allows for $version to be an alias on development branches).
*
* @var string $branch
*/
protected $branch;
/**
* The repository branch name (allows for $version to be an alias on development branches).
*
* @var string $branch
*/
protected $branch;
/**
* If this entity is a stable release or not. If it is not stable (i.e it
* could be a past or future release) then a warning message will be shown.
*
* @var boolean $stable
*/
protected $stable;
/**
* If this entity is a stable release or not. If it is not stable (i.e it
* could be a past or future release) then a warning message will be shown.
*
* @var boolean $stable
*/
protected $stable;
/**
* @var string
*/
protected $language;
/**
* @var string
*/
protected $language;
/**
*
*/
public function __construct($key) {
$this->key = DocumentationHelper::clean_page_url($key);
}
/**
*
*/
public function __construct($key)
{
$this->key = DocumentationHelper::clean_page_url($key);
}
/**
* Get the title of this module.
*
* @return string
*/
public function getTitle() {
if(!$this->title) {
$this->title = DocumentationHelper::clean_page_name($this->key);
}
/**
* Get the title of this module.
*
* @return string
*/
public function getTitle()
{
if (!$this->title) {
$this->title = DocumentationHelper::clean_page_name($this->key);
}
return $this->title;
}
return $this->title;
}
/**
* @param string $title
* @return this
*/
public function setTitle($title) {
$this->title = $title;
/**
* @param string $title
* @return this
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
return $this;
}
/**
* Returns the web accessible link to this entity.
*
* Includes the version information
*
* @param boolean $short If true, will attempt to return a short version of the url
* This might omit the version number if this is the default version.
* @return string
*/
public function Link($short = false) {
if($this->getIsDefaultEntity()) {
$base = Controller::join_links(
Config::inst()->get('DocumentationViewer', 'link_base'),
$this->getLanguage(),
'/'
);
} else {
$base = Controller::join_links(
Config::inst()->get('DocumentationViewer', 'link_base'),
$this->getLanguage(),
$this->getKey(),
'/'
);
}
/**
* Returns the web accessible link to this entity.
*
* Includes the version information
*
* @param boolean $short If true, will attempt to return a short version of the url
* This might omit the version number if this is the default version.
* @return string
*/
public function Link($short = false)
{
if ($this->getIsDefaultEntity()) {
$base = Controller::join_links(
Config::inst()->get('DocumentationViewer', 'link_base'),
$this->getLanguage(),
'/'
);
} else {
$base = Controller::join_links(
Config::inst()->get('DocumentationViewer', 'link_base'),
$this->getLanguage(),
$this->getKey(),
'/'
);
}
$base = ltrim(str_replace('//', '/', $base), '/');
$base = ltrim(str_replace('//', '/', $base), '/');
if($short && $this->stable) {
return $base;
}
if ($short && $this->stable) {
return $base;
}
return Controller::join_links(
$base,
$this->getVersion(),
'/'
);
}
return Controller::join_links(
$base,
$this->getVersion(),
'/'
);
}
/**
* @return string
*/
public function __toString() {
return sprintf('DocumentationEntity: %s)', $this->getPath());
}
/**
* @return string
*/
public function __toString()
{
return sprintf('DocumentationEntity: %s)', $this->getPath());
}
/**
* @param DocumentationPage $page
*
* @return boolean
*/
public function hasRecord($page) {
if(!$page) {
return false;
}
/**
* @param DocumentationPage $page
*
* @return boolean
*/
public function hasRecord($page)
{
if (!$page) {
return false;
}
return strstr($page->getPath(), $this->getPath()) !== false;
}
return strstr($page->getPath(), $this->getPath()) !== false;
}
/**
* @param boolean $bool
*/
public function setIsDefaultEntity($bool) {
$this->defaultEntity = $bool;
/**
* @param boolean $bool
*/
public function setIsDefaultEntity($bool)
{
$this->defaultEntity = $bool;
return $this;
}
return $this;
}
/**
* @return boolean
*/
public function getIsDefaultEntity() {
return $this->defaultEntity;
}
/**
* @return boolean
*/
public function getIsDefaultEntity()
{
return $this->defaultEntity;
}
/**
* @return string
*/
public function getKey() {
return $this->key;
}
/**
* @return string
*/
public function getKey()
{
return $this->key;
}
/**
* @return string
*/
public function getLanguage() {
return $this->language;
}
/**
* @return string
*/
public function getLanguage()
{
return $this->language;
}
/**
* @param string
*
* @return this
*/
public function setLanguage($language) {
$this->language = $language;
/**
* @param string
*
* @return this
*/
public function setLanguage($language)
{
$this->language = $language;
return $this;
}
return $this;
}
/**
* @param string
*/
public function setVersion($version) {
$this->version = $version;
/**
* @param string
*/
public function setVersion($version)
{
$this->version = $version;
return $this;
}
return $this;
}
/**
* @return float
*/
public function getVersion() {
return $this->version;
}
/**
* @return float
*/
public function getVersion()
{
return $this->version;
}
/**
* @param string
*/
public function setBranch($branch) {
$this->branch = $branch;
/**
* @param string
*/
public function setBranch($branch)
{
$this->branch = $branch;
return $this;
}
return $this;
}
/**
* @return float
*/
public function getBranch() {
return $this->branch;
}
/**
* @return float
*/
public function getBranch()
{
return $this->branch;
}
/**
* @return string
*/
public function getPath() {
return $this->path;
}
/**
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* @param string $path
*
* @return this
*/
public function setPath($path) {
$this->path = $path;
/**
* @param string $path
*
* @return this
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
return $this;
}
/**
* @param boolean
*/
public function setIsStable($stable) {
$this->stable = $stable;
/**
* @param boolean
*/
public function setIsStable($stable)
{
$this->stable = $stable;
return $this;
}
return $this;
}
/**
* @return boolean
*/
public function getIsStable() {
return $this->stable;
}
/**
* @return boolean
*/
public function getIsStable()
{
return $this->stable;
}
/**
* Returns an integer value based on if a given version is the latest
* version. Will return -1 for if the version is older, 0 if versions are
* the same and 1 if the version is greater than.
*
* @param string $version
* @return int
*/
public function compare(DocumentationEntity $other) {
return version_compare($this->getVersion(), $other->getVersion());
}
/**
* Returns an integer value based on if a given version is the latest
* version. Will return -1 for if the version is older, 0 if versions are
* the same and 1 if the version is greater than.
*
* @param string $version
* @return int
*/
public function compare(DocumentationEntity $other)
{
return version_compare($this->getVersion(), $other->getVersion());
}
/**
* @return array
*/
public function toMap() {
return array(
'Key' => $this->key,
'Path' => $this->getPath(),
'Version' => $this->getVersion(),
'Branch' => $this->getBranch(),
'IsStable' => $this->getIsStable(),
'Language' => $this->getLanguage()
);
}
/**
* @return array
*/
public function toMap()
{
return array(
'Key' => $this->key,
'Path' => $this->getPath(),
'Version' => $this->getVersion(),
'Branch' => $this->getBranch(),
'IsStable' => $this->getIsStable(),
'Language' => $this->getLanguage()
);
}
}

View File

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

View File

@ -10,280 +10,295 @@
* @package docsviewer
* @subpackage model
*/
class DocumentationPage extends ViewableData {
class DocumentationPage extends ViewableData
{
/**
* @var string
*/
protected $title, $summary, $introduction;
/**
* @var string
*/
protected $title, $summary, $introduction;
/**
* @var DocumentationEntity
*/
protected $entity;
/**
* @var DocumentationEntity
*/
protected $entity;
/**
* @var string
*/
protected $path;
/**
* @var string
*/
protected $path;
/**
* Filename
*
* @var string
*/
protected $filename;
/**
* Filename
*
* @var string
*/
protected $filename;
protected $read = false;
protected $read = false;
/**
* @param DocumentationEntity $entity
* @param string $filename
* @param string $path
*/
public function __construct(DocumentationEntity $entity, $filename, $path)
{
$this->filename = $filename;
$this->path = $path;
$this->entity = $entity;
}
/**
* @param DocumentationEntity $entity
* @param string $filename
* @param string $path
*/
public function __construct(DocumentationEntity $entity, $filename, $path) {
$this->filename = $filename;
$this->path = $path;
$this->entity = $entity;
}
/**
* @return string
*/
public function getExtension()
{
return DocumentationHelper::get_extension($this->filename);
}
/**
* @return string
*/
public function getExtension() {
return DocumentationHelper::get_extension($this->filename);
}
/**
* @param string - has to be plain text for open search compatibility.
*
* @return string
*/
public function getBreadcrumbTitle($divider = ' - ')
{
$pathParts = explode('/', trim($this->getRelativePath(), '/'));
/**
* @param string - has to be plain text for open search compatibility.
*
* @return string
*/
public function getBreadcrumbTitle($divider = ' - ') {
$pathParts = explode('/', trim($this->getRelativePath(), '/'));
// from the page from this
array_pop($pathParts);
// from the page from this
array_pop($pathParts);
// add the module to the breadcrumb trail.
$pathParts[] = $this->entity->getTitle();
// add the module to the breadcrumb trail.
$pathParts[] = $this->entity->getTitle();
$titleParts = array_map(array(
'DocumentationHelper', 'clean_page_name'
), $pathParts);
$titleParts = array_map(array(
'DocumentationHelper', 'clean_page_name'
), $pathParts);
$titleParts = array_filter($titleParts, function ($val) {
if ($val) {
return $val;
}
});
$titleParts = array_filter($titleParts, function($val) {
if($val) {
return $val;
}
});
if ($this->getTitle()) {
array_unshift($titleParts, $this->getTitle());
}
if($this->getTitle()) {
array_unshift($titleParts, $this->getTitle());
}
return implode($divider, $titleParts);
}
return implode($divider, $titleParts);
}
/**
* @return DocumentationEntity
*/
public function getEntity()
{
return $this->entity;
}
/**
* @return DocumentationEntity
*/
public function getEntity() {
return $this->entity;
}
/**
* @return string
*/
public function getTitle()
{
if ($this->title) {
return $this->title;
}
/**
* @return string
*/
public function getTitle() {
if($this->title) {
return $this->title;
}
$page = DocumentationHelper::clean_page_name($this->filename);
$page = DocumentationHelper::clean_page_name($this->filename);
if ($page == "Index") {
return $this->getTitleFromFolder();
}
if($page == "Index") {
return $this->getTitleFromFolder();
}
return $page;
}
return $page;
}
public function getTitleFromFolder()
{
$folder = $this->getPath();
$entity = $this->getEntity()->getPath();
public function getTitleFromFolder() {
$folder = $this->getPath();
$entity = $this->getEntity()->getPath();
$folder = str_replace('index.md', '', $folder);
$folder = str_replace('index.md', '', $folder);
// 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) {
return $this->getEntity()->getTitle();
} else {
$path = explode(DIRECTORY_SEPARATOR, trim($folder, DIRECTORY_SEPARATOR));
$folderName = array_pop($path);
}
// 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) {
return $this->getEntity()->getTitle();
} else {
$path = explode(DIRECTORY_SEPARATOR, trim($folder, DIRECTORY_SEPARATOR));
$folderName = array_pop($path);
}
return DocumentationHelper::clean_page_name($folderName);
}
return DocumentationHelper::clean_page_name($folderName);
}
/**
* @return string
*/
public function getSummary()
{
return $this->summary;
}
/**
* @return string
*/
public function getSummary() {
return $this->summary;
}
/**
* Return the raw markdown for a given documentation page.
*
* @param boolean $removeMetaData
*
* @return string
*/
public function getMarkdown($removeMetaData = false)
{
try {
if ($md = file_get_contents($this->getPath())) {
$this->populateMetaDataFromText($md, $removeMetaData);
/**
* Return the raw markdown for a given documentation page.
*
* @param boolean $removeMetaData
*
* @return string
*/
public function getMarkdown($removeMetaData = false) {
try {
if ($md = file_get_contents($this->getPath())) {
$this->populateMetaDataFromText($md, $removeMetaData);
return $md;
}
return $md;
}
$this->read = true;
} catch (InvalidArgumentException $e) {
}
$this->read = true;
}
catch(InvalidArgumentException $e) {
return false;
}
}
public function setMetaData($key, $value)
{
$key = strtolower($key);
return false;
}
$this->$key = $value;
}
public function setMetaData($key, $value) {
$key = strtolower($key);
public function getIntroduction()
{
if (!$this->read) {
$this->getMarkdown();
}
$this->$key = $value;
}
return $this->introduction;
}
public function getIntroduction() {
if(!$this->read) {
$this->getMarkdown();
}
/**
* Parse a file and return the parsed HTML version.
*
* @param string $baselink
*
* @return string
*/
public function getHTML()
{
$html = DocumentationParser::parse(
$this,
$this->entity->Link()
);
return $this->introduction;
}
return $html;
}
/**
* Parse a file and return the parsed HTML version.
*
* @param string $baselink
*
* @return string
*/
public function getHTML() {
$html = DocumentationParser::parse(
$this,
$this->entity->Link()
);
/**
* This should return the link from the entity root to the page. The link
* value has the cleaned version of the folder names. See
* {@link getRelativePath()} for the actual file path.
*
* @return string
*/
public function getRelativeLink()
{
$path = $this->getRelativePath();
$url = explode('/', $path);
$url = implode('/', array_map(function ($a) {
return DocumentationHelper::clean_page_url($a);
}, $url));
return $html;
}
$url = trim($url, '/') . '/';
/**
* This should return the link from the entity root to the page. The link
* value has the cleaned version of the folder names. See
* {@link getRelativePath()} for the actual file path.
*
* @return string
*/
public function getRelativeLink() {
$path = $this->getRelativePath();
$url = explode('/', $path);
$url = implode('/', array_map(function($a) {
return DocumentationHelper::clean_page_url($a);
}, $url));
return $url;
}
$url = trim($url, '/') . '/';
/**
* This should return the link from the entity root to the page. For the url
* polished version, see {@link getRelativeLink()}.
*
* @return string
*/
public function getRelativePath()
{
return str_replace($this->entity->getPath(), '', $this->getPath());
}
return $url;
}
/**
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* This should return the link from the entity root to the page. For the url
* polished version, see {@link getRelativeLink()}.
*
* @return string
*/
public function getRelativePath() {
return str_replace($this->entity->getPath(), '', $this->getPath());
/**
* Returns the URL that will be required for the user to hit to view the
* given document base name.
*
* @param boolean $short If true, will attempt to return a short version of the url
* This might omit the version number if this is the default version.
* @return string
*/
public function Link($short = false)
{
return ltrim(Controller::join_links(
$this->entity->Link($short),
$this->getRelativeLink()
), '/');
}
}
/**
* Return metadata from the first html block in the page, then remove the
* block on request
*
* @param DocumentationPage $md
* @param bool $remove
*/
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);
/**
* @return string
*/
public function getPath() {
return $this->path;
}
if ($matches && $block[1]) {
$metaDataFound = false;
/**
* Returns the URL that will be required for the user to hit to view the
* given document base name.
*
* @param boolean $short If true, will attempt to return a short version of the url
* This might omit the version number if this is the default version.
* @return string
*/
public function Link($short = false) {
return ltrim(Controller::join_links(
$this->entity->Link($short),
$this->getRelativeLink()
), '/');
}
// 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);
/**
* Return metadata from the first html block in the page, then remove the
* block on request
*
* @param DocumentationPage $md
* @param bool $remove
*/
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);
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];
$metaDataFound = true;
}
}
}
if($matches && $block[1]) {
$metaDataFound = false;
// optionally remove the metadata block (only on the page that
// is displayed)
if ($metaDataFound && $removeMetaData) {
$md = preg_replace($extPattern, '', $md);
}
}
}
}
// 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);
public function getVersion()
{
return $this->entity->getVersion();
}
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];
$metaDataFound = true;
}
}
}
// optionally remove the metadata block (only on the page that
// is displayed)
if ($metaDataFound && $removeMetaData) {
$md = preg_replace($extPattern, '', $md);
}
}
}
}
public function getVersion() {
return $this->entity->getVersion();
}
public function __toString() {
return sprintf(get_class($this) .': %s)', $this->getPath());
}
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) {
$manifest = new DocumentationManifest(true);
echo "<pre>";
print_r($manifest->getPages());
echo "</pre>";
die();;
}
class DocumentationBuild extends BuildTask
{
public function run($request)
{
$manifest = new DocumentationManifest(true);
echo "<pre>";
print_r($manifest->getPages());
echo "</pre>";
die();
;
}
}

View File

@ -9,124 +9,127 @@
* @subpackage tasks
*/
class RebuildLuceneDocsIndex extends BuildTask {
class RebuildLuceneDocsIndex extends BuildTask
{
protected $title = "Rebuild Documentation Search Indexes";
protected $title = "Rebuild Documentation Search Indexes";
protected $description = "
protected $description = "
Rebuilds the indexes used for the search engine in the docsviewer.";
public function run($request) {
$this->rebuildIndexes();
}
public function run($request)
{
$this->rebuildIndexes();
}
public function rebuildIndexes($quiet = false) {
require_once 'Zend/Search/Lucene.php';
public function rebuildIndexes($quiet = false)
{
require_once 'Zend/Search/Lucene.php';
ini_set("memory_limit", -1);
ini_set('max_execution_time', 0);
ini_set("memory_limit", -1);
ini_set('max_execution_time', 0);
Filesystem::makeFolder(DocumentationSearch::get_index_location());
Filesystem::makeFolder(DocumentationSearch::get_index_location());
// only rebuild the index if we have to. Check for either flush or the time write.lock.file
// was last altered
$lock = DocumentationSearch::get_index_location() .'/write.lock.file';
$lockFileFresh = (file_exists($lock) && filemtime($lock) > (time() - (60 * 60 * 24)));
// only rebuild the index if we have to. Check for either flush or the time write.lock.file
// was last altered
$lock = DocumentationSearch::get_index_location() .'/write.lock.file';
$lockFileFresh = (file_exists($lock) && filemtime($lock) > (time() - (60 * 60 * 24)));
echo "Building index in ". DocumentationSearch::get_index_location() . PHP_EOL;
echo "Building index in ". DocumentationSearch::get_index_location() . PHP_EOL;
if($lockFileFresh && !isset($_REQUEST['flush'])) {
if(!$quiet) {
echo "Index recently rebuilt. If you want to force reindex use ?flush=1";
}
if ($lockFileFresh && !isset($_REQUEST['flush'])) {
if (!$quiet) {
echo "Index recently rebuilt. If you want to force reindex use ?flush=1";
}
return true;
}
return true;
}
try {
$index = Zend_Search_Lucene::open(DocumentationSearch::get_index_location());
$index->removeReference();
}
catch (Zend_Search_Lucene_Exception $e) {
user_error($e);
}
try {
$index = Zend_Search_Lucene::open(DocumentationSearch::get_index_location());
$index->removeReference();
} 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) {
user_error($c);
}
try {
$index = Zend_Search_Lucene::create(DocumentationSearch::get_index_location());
} catch (Zend_Search_Lucene_Exception $c) {
user_error($c);
}
// includes registration
$manifest = new DocumentationManifest(true);
$pages = $manifest->getPages();
// includes registration
$manifest = new DocumentationManifest(true);
$pages = $manifest->getPages();
if($pages) {
$count = 0;
if ($pages) {
$count = 0;
// iconv complains about all the markdown formatting
// turn off notices while we parse
// iconv complains about all the markdown formatting
// turn off notices while we parse
if(!Director::is_cli()) {
echo "<ul>";
}
foreach($pages as $url => $record) {
$count++;
$page = $manifest->getPage($url);
if (!Director::is_cli()) {
echo "<ul>";
}
foreach ($pages as $url => $record) {
$count++;
$page = $manifest->getPage($url);
$doc = new Zend_Search_Lucene_Document();
$error = error_reporting();
error_reporting(E_ALL ^ E_NOTICE);
$content = $page->getHTML();
error_reporting($error);
$doc = new Zend_Search_Lucene_Document();
$error = error_reporting();
error_reporting(E_ALL ^ E_NOTICE);
$content = $page->getHTML();
error_reporting($error);
$doc->addField(Zend_Search_Lucene_Field::Text('content', $content));
$doc->addField($titleField = Zend_Search_Lucene_Field::Text('Title', $page->getTitle()));
$doc->addField($breadcrumbField = Zend_Search_Lucene_Field::Text('BreadcrumbTitle', $page->getBreadcrumbTitle()));
$doc->addField(Zend_Search_Lucene_Field::Text('content', $content));
$doc->addField($titleField = Zend_Search_Lucene_Field::Text('Title', $page->getTitle()));
$doc->addField($breadcrumbField = Zend_Search_Lucene_Field::Text('BreadcrumbTitle', $page->getBreadcrumbTitle()));
$doc->addField(Zend_Search_Lucene_Field::Keyword(
'Version', $page->getEntity()->getVersion()
));
$doc->addField(Zend_Search_Lucene_Field::Keyword(
'Version', $page->getEntity()->getVersion()
));
$doc->addField(Zend_Search_Lucene_Field::Keyword(
'Language', $page->getEntity()->getLanguage()
));
$doc->addField(Zend_Search_Lucene_Field::Keyword(
'Language', $page->getEntity()->getLanguage()
));
$doc->addField(Zend_Search_Lucene_Field::Keyword(
'Entity', $page->getEntity()
));
$doc->addField(Zend_Search_Lucene_Field::Keyword(
'Entity', $page->getEntity()
));
$doc->addField(Zend_Search_Lucene_Field::Keyword(
'Link', $page->Link()
));
$doc->addField(Zend_Search_Lucene_Field::Keyword(
'Link', $page->Link()
));
// custom boosts
$titleField->boost = 3;
$breadcrumbField->boost = 1.5;
// custom boosts
$titleField->boost = 3;
$breadcrumbField->boost = 1.5;
$boost = Config::inst()->get('DocumentationSearch', 'boost_by_path');
$boost = Config::inst()->get('DocumentationSearch', 'boost_by_path');
foreach($boost as $pathExpr => $boost) {
if(preg_match($pathExpr, $page->getRelativePath())) {
$doc->boost = $boost;
}
}
foreach ($boost as $pathExpr => $boost) {
if (preg_match($pathExpr, $page->getRelativePath())) {
$doc->boost = $boost;
}
}
error_reporting(E_ALL ^ E_NOTICE);
$index->addDocument($doc);
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();
$index->commit();
if(!$quiet) {
echo "complete.";
}
}
if (!$quiet) {
echo "complete.";
}
}
}

View File

@ -4,67 +4,72 @@
* @package docsviewer
* @subpackage tests
*/
class DocumentationHelperTests extends SapphireTest {
class DocumentationHelperTests extends SapphireTest
{
public function testCleanName()
{
$this->assertEquals("File path", DocumentationHelper::clean_page_name(
'00_file-path.md'
));
}
public function testCleanName() {
$this->assertEquals("File path", DocumentationHelper::clean_page_name(
'00_file-path.md'
));
}
public function testCleanUrl()
{
$this->assertEquals("some_path", DocumentationHelper::clean_page_url(
'Some Path'
));
public function testCleanUrl() {
$this->assertEquals("some_path", DocumentationHelper::clean_page_url(
'Some Path'
));
$this->assertEquals("somefilepath", DocumentationHelper::clean_page_url(
'00_SomeFilePath.md'
));
}
$this->assertEquals("somefilepath", DocumentationHelper::clean_page_url(
'00_SomeFilePath.md'
));
}
public function testTrimSortNumber()
{
$this->assertEquals('file', DocumentationHelper::trim_sort_number(
'0_file'
));
public function testTrimSortNumber() {
$this->assertEquals('file', DocumentationHelper::trim_sort_number(
'0_file'
));
$this->assertEquals('2.1', DocumentationHelper::trim_sort_number(
'2.1'
));
$this->assertEquals('2.1', DocumentationHelper::trim_sort_number(
'2.1'
));
$this->assertEquals('dev/tasks/2.1', DocumentationHelper::trim_sort_number(
'dev/tasks/2.1'
));
}
$this->assertEquals('dev/tasks/2.1', DocumentationHelper::trim_sort_number(
'dev/tasks/2.1'
));
}
public function testTrimExtension()
{
$this->assertEquals('file', DocumentationHelper::trim_extension_off(
'file.md'
));
public function testTrimExtension() {
$this->assertEquals('file', DocumentationHelper::trim_extension_off(
'file.md'
));
$this->assertEquals('dev/path/file', DocumentationHelper::trim_extension_off(
'dev/path/file.md'
));
}
$this->assertEquals('dev/path/file', DocumentationHelper::trim_extension_off(
'dev/path/file.md'
));
}
public function testGetExtension()
{
$this->assertEquals('md', DocumentationHelper::get_extension(
'file.md'
));
public function testGetExtension() {
$this->assertEquals('md', DocumentationHelper::get_extension(
'file.md'
));
$this->assertEquals('md', DocumentationHelper::get_extension(
'dev/tasks/file.md'
));
$this->assertEquals('md', DocumentationHelper::get_extension(
'dev/tasks/file.md'
));
$this->assertEquals('txt', DocumentationHelper::get_extension(
'dev/tasks/file.txt'
));
$this->assertEquals('txt', DocumentationHelper::get_extension(
'dev/tasks/file.txt'
));
$this->assertNull(DocumentationHelper::get_extension(
'doc_test/2.3'
));
$this->assertNull(DocumentationHelper::get_extension(
'doc_test/2.3'
));
$this->assertNull(DocumentationHelper::get_extension(
'dev/docs/en/doc_test/2.3/subfolder'
));
}
$this->assertNull(DocumentationHelper::get_extension(
'dev/docs/en/doc_test/2.3/subfolder'
));
}
}

View File

@ -4,208 +4,219 @@
* @package docsviewer
* @subpackage tests
*/
class DocumentationManifestTests extends SapphireTest {
class DocumentationManifestTests extends SapphireTest
{
private $manifest;
private $manifest;
public function setUp()
{
parent::setUp();
public function setUp() {
parent::setUp();
Config::nest();
Config::nest();
// explicitly use dev/docs. Custom paths should be tested separately
Config::inst()->update(
'DocumentationViewer', 'link_base', 'dev/docs'
);
// explicitly use dev/docs. Custom paths should be tested separately
Config::inst()->update(
'DocumentationViewer', 'link_base', 'dev/docs'
);
// disable automatic module registration so modules don't interfere.
Config::inst()->update(
'DocumentationManifest', 'automatic_registration', false
);
// disable automatic module registration so modules don't interfere.
Config::inst()->update(
'DocumentationManifest', 'automatic_registration', false
);
Config::inst()->remove('DocumentationManifest', 'register_entities');
Config::inst()->remove('DocumentationManifest', 'register_entities');
Config::inst()->update(
'DocumentationManifest', 'register_entities', array(
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs/",
'Title' => 'Doc Test',
'Key' => 'testdocs',
'Version' => '2.3'
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-v2.4/",
'Title' => 'Doc Test',
'Version' => '2.4',
'Key' => 'testdocs',
'Stable' => true
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-v3.0/",
'Title' => 'Doc Test',
'Key' => 'testdocs',
'Version' => '3.0'
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-manifest/",
'Title' => 'Manifest',
'Key' => 'manifest'
)
)
);
Config::inst()->update(
'DocumentationManifest', 'register_entities', array(
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs/",
'Title' => 'Doc Test',
'Key' => 'testdocs',
'Version' => '2.3'
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-v2.4/",
'Title' => 'Doc Test',
'Version' => '2.4',
'Key' => 'testdocs',
'Stable' => true
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-v3.0/",
'Title' => 'Doc Test',
'Key' => 'testdocs',
'Version' => '3.0'
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-manifest/",
'Title' => 'Manifest',
'Key' => 'manifest'
)
)
);
$this->manifest = new DocumentationManifest(true);
}
$this->manifest = new DocumentationManifest(true);
}
public function tearDown()
{
parent::tearDown();
public function tearDown() {
parent::tearDown();
Config::unnest();
}
Config::unnest();
}
/**
* Check that the manifest matches what we'd expect.
*/
public function testRegenerate() {
$match = array(
'de/testdocs/2.3/',
'de/testdocs/2.3/german/',
'de/testdocs/2.3/test/',
'en/testdocs/2.3/',
'en/testdocs/2.3/sort/',
'en/testdocs/2.3/sort/basic/',
'en/testdocs/2.3/sort/intermediate/',
'en/testdocs/2.3/sort/advanced/',
'en/testdocs/2.3/sort/some-page/',
'en/testdocs/2.3/sort/another-page/',
'en/testdocs/2.3/subfolder/',
'en/testdocs/2.3/subfolder/subpage/',
'en/testdocs/2.3/subfolder/subsubfolder/',
'en/testdocs/2.3/subfolder/subsubfolder/subsubpage/',
'en/testdocs/2.3/test/',
'en/testdocs/2.4/',
'en/testdocs/2.4/test/',
'en/testdocs/3.0/',
'en/testdocs/3.0/changelog/',
'en/testdocs/3.0/tutorials/',
'en/testdocs/3.0/empty/',
'en/manifest/',
'en/manifest/guide/',
'en/manifest/guide/test/',
'en/manifest/second-guide/',
'en/manifest/second-guide/afile/'
);
/**
* Check that the manifest matches what we'd expect.
*/
public function testRegenerate()
{
$match = array(
'de/testdocs/2.3/',
'de/testdocs/2.3/german/',
'de/testdocs/2.3/test/',
'en/testdocs/2.3/',
'en/testdocs/2.3/sort/',
'en/testdocs/2.3/sort/basic/',
'en/testdocs/2.3/sort/intermediate/',
'en/testdocs/2.3/sort/advanced/',
'en/testdocs/2.3/sort/some-page/',
'en/testdocs/2.3/sort/another-page/',
'en/testdocs/2.3/subfolder/',
'en/testdocs/2.3/subfolder/subpage/',
'en/testdocs/2.3/subfolder/subsubfolder/',
'en/testdocs/2.3/subfolder/subsubfolder/subsubpage/',
'en/testdocs/2.3/test/',
'en/testdocs/2.4/',
'en/testdocs/2.4/test/',
'en/testdocs/3.0/',
'en/testdocs/3.0/changelog/',
'en/testdocs/3.0/tutorials/',
'en/testdocs/3.0/empty/',
'en/manifest/',
'en/manifest/guide/',
'en/manifest/guide/test/',
'en/manifest/second-guide/',
'en/manifest/second-guide/afile/'
);
$this->assertEquals($match, array_keys($this->manifest->getPages()));
}
$this->assertEquals($match, array_keys($this->manifest->getPages()));
}
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(
DOCSVIEWER_PATH . '/tests/docs/en/subfolder/subsubfolder/subsubpage.md',
DOCSVIEWER_PATH . '/tests/docs/en/'
)->Link);
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(
DOCSVIEWER_PATH . '/tests/docs/en/subfolder/subsubfolder/subsubpage.md',
DOCSVIEWER_PATH . '/tests/docs/en/'
)->Link);
// after sorting, 2 is shown.
$this->assertContains('/intermediate/', $this->manifest->getNextPage(
DOCSVIEWER_PATH . '/tests/docs/en/sort/01-basic.md',
DOCSVIEWER_PATH . '/tests/docs/en/'
)->Link);
// after sorting, 2 is shown.
$this->assertContains('/intermediate/', $this->manifest->getNextPage(
DOCSVIEWER_PATH . '/tests/docs/en/sort/01-basic.md',
DOCSVIEWER_PATH . '/tests/docs/en/'
)->Link);
// next gets the following URL
$this->assertContains('/test/', $this->manifest->getNextPage(
DOCSVIEWER_PATH . '/tests/docs-v2.4/en/index.md',
DOCSVIEWER_PATH . '/tests/docs-v2.4/en/'
)->Link);
// next gets the following URL
$this->assertContains('/test/', $this->manifest->getNextPage(
DOCSVIEWER_PATH . '/tests/docs-v2.4/en/index.md',
DOCSVIEWER_PATH . '/tests/docs-v2.4/en/'
)->Link);
// last folder in a entity does not leak
$this->assertNull($this->manifest->getNextPage(
DOCSVIEWER_PATH . '/tests/docs/en/test.md',
DOCSVIEWER_PATH . '/tests/docs/en/'
));
}
// last folder in a entity does not leak
$this->assertNull($this->manifest->getNextPage(
DOCSVIEWER_PATH . '/tests/docs/en/test.md',
DOCSVIEWER_PATH . '/tests/docs/en/'
));
}
public function testGetPreviousPage() {
// goes right into subfolders
$this->assertContains('subfolder/subsubfolder/subsubpage', $this->manifest->getPreviousPage(
DOCSVIEWER_PATH . '/tests/docs/en/test.md',
DOCSVIEWER_PATH . '/tests/docs/en/'
)->Link);
public function testGetPreviousPage()
{
// goes right into subfolders
$this->assertContains('subfolder/subsubfolder/subsubpage', $this->manifest->getPreviousPage(
DOCSVIEWER_PATH . '/tests/docs/en/test.md',
DOCSVIEWER_PATH . '/tests/docs/en/'
)->Link);
// does not leak between entities
$this->assertNull($this->manifest->getPreviousPage(
DOCSVIEWER_PATH . '/tests/docs/en/index.md',
DOCSVIEWER_PATH . '/tests/docs/en/'
));
// does not leak between entities
$this->assertNull($this->manifest->getPreviousPage(
DOCSVIEWER_PATH . '/tests/docs/en/index.md',
DOCSVIEWER_PATH . '/tests/docs/en/'
));
// does not leak between entities
$this->assertNull($this->manifest->getPreviousPage(
DOCSVIEWER_PATH . ' /tests/docs/en/index.md',
DOCSVIEWER_PATH . '/tests/docs/en/'
));
}
// does not leak between entities
$this->assertNull($this->manifest->getPreviousPage(
DOCSVIEWER_PATH . ' /tests/docs/en/index.md',
DOCSVIEWER_PATH . '/tests/docs/en/'
));
}
public function testGetPage() {
$this->markTestIncomplete();
}
public function testGetPage()
{
$this->markTestIncomplete();
}
public function testGenerateBreadcrumbs() {
$this->markTestIncomplete();
}
public function testGenerateBreadcrumbs()
{
$this->markTestIncomplete();
}
public function testGetChildrenFor() {
$expected = array(
array('Title' => 'Test', 'LinkingMode' => 'link')
);
public function testGetChildrenFor()
{
$expected = array(
array('Title' => 'Test', 'LinkingMode' => 'link')
);
$this->assertDOSContains($expected, $this->manifest->getChildrenFor(
DOCSVIEWER_PATH . "/tests/docs/en/"
));
$this->assertDOSContains($expected, $this->manifest->getChildrenFor(
DOCSVIEWER_PATH . "/tests/docs/en/"
));
$expected = array(
array('Title' => 'ChangeLog', 'LinkingMode' => 'current'),
array('Title' => 'Tutorials'),
array('Title' => 'Empty')
);
$expected = array(
array('Title' => 'ChangeLog', 'LinkingMode' => 'current'),
array('Title' => 'Tutorials'),
array('Title' => 'Empty')
);
$this->assertDOSContains($expected, $this->manifest->getChildrenFor(
DOCSVIEWER_PATH . '/tests/docs-v3.0/en/',
DOCSVIEWER_PATH . '/tests/docs-v3.0/en/ChangeLog.md'
));
}
$this->assertDOSContains($expected, $this->manifest->getChildrenFor(
DOCSVIEWER_PATH . '/tests/docs-v3.0/en/',
DOCSVIEWER_PATH . '/tests/docs-v3.0/en/ChangeLog.md'
));
}
public function testGetAllVersions() {
$expected = array(
'2.3' => '2.3',
'2.4' => '2.4',
'3.0' => '3.0',
'0.0' => 'Master'
);
public function testGetAllVersions()
{
$expected = array(
'2.3' => '2.3',
'2.4' => '2.4',
'3.0' => '3.0',
'0.0' => 'Master'
);
$this->assertEquals($expected, $this->manifest->getAllVersions());
}
$this->assertEquals($expected, $this->manifest->getAllVersions());
}
public function testGetAllEntityVersions() {
$expected = array(
'Version' => '2.3',
'Version' => '2.4',
'Version' => '3.0'
);
public function testGetAllEntityVersions()
{
$expected = array(
'Version' => '2.3',
'Version' => '2.4',
'Version' => '3.0'
);
$entity = $this->manifest->getEntities()->find('Language', 'en');
$entity = $this->manifest->getEntities()->find('Language', 'en');
$this->assertEquals(3, $this->manifest->getAllVersionsOfEntity($entity)->count());
$this->assertEquals(3, $this->manifest->getAllVersionsOfEntity($entity)->count());
$entity = $this->manifest->getEntities()->find('Language', 'de');
$entity = $this->manifest->getEntities()->find('Language', 'de');
$this->assertEquals(1, $this->manifest->getAllVersionsOfEntity($entity)->count());
}
$this->assertEquals(1, $this->manifest->getAllVersionsOfEntity($entity)->count());
}
public function testGetStableVersion() {
$this->markTestIncomplete();
}
public function testGetStableVersion()
{
$this->markTestIncomplete();
}
}

View File

@ -4,87 +4,90 @@
* @package docsviewer
* @subpackage tests
*/
class DocumentationPageTest extends SapphireTest {
class DocumentationPageTest extends SapphireTest
{
protected $entity;
protected $entity;
public function setUp()
{
parent::setUp();
public function setUp() {
parent::setUp();
$this->entity = new DocumentationEntity('doctest');
$this->entity->setPath(DOCSVIEWER_PATH . '/tests/docs/en/');
$this->entity->setVersion('2.4');
$this->entity->setLanguage('en');
$this->entity = new DocumentationEntity('doctest');
$this->entity->setPath(DOCSVIEWER_PATH . '/tests/docs/en/');
$this->entity->setVersion('2.4');
$this->entity->setLanguage('en');
Config::nest();
Config::nest();
// explicitly use dev/docs. Custom paths should be tested separately
Config::inst()->update(
'DocumentationViewer', 'link_base', 'dev/docs/'
);
// explicitly use dev/docs. Custom paths should be tested separately
Config::inst()->update(
'DocumentationViewer', 'link_base', 'dev/docs/'
);
$manifest = new DocumentationManifest(true);
}
$manifest = new DocumentationManifest(true);
}
public function tearDown()
{
parent::tearDown();
public function tearDown() {
parent::tearDown();
Config::unnest();
}
Config::unnest();
}
public function testGetLink()
{
$page = new DocumentationPage(
$this->entity,
'test.md',
DOCSVIEWER_PATH . '/tests/docs/en/test.md'
);
public function testGetLink() {
$page = new DocumentationPage(
$this->entity,
'test.md',
DOCSVIEWER_PATH . '/tests/docs/en/test.md'
);
// single layer
$this->assertEquals('dev/docs/en/doctest/2.4/test/', $page->Link(),
'The page link should have no extension and have a language'
);
// single layer
$this->assertEquals('dev/docs/en/doctest/2.4/test/', $page->Link(),
'The page link should have no extension and have a language'
);
$page = new DocumentationFolder(
$this->entity,
'sort',
DOCSVIEWER_PATH . '/tests/docs/en/sort/'
);
$page = new DocumentationFolder(
$this->entity,
'sort',
DOCSVIEWER_PATH . '/tests/docs/en/sort/'
);
$this->assertEquals('dev/docs/en/doctest/2.4/sort/', $page->Link());
$this->assertEquals('dev/docs/en/doctest/2.4/sort/', $page->Link());
$page = new DocumentationFolder(
$this->entity,
'1-basic.md',
DOCSVIEWER_PATH . '/tests/docs/en/sort/1-basic.md'
);
$page = new DocumentationFolder(
$this->entity,
'1-basic.md',
DOCSVIEWER_PATH . '/tests/docs/en/sort/1-basic.md'
);
$this->assertEquals('dev/docs/en/doctest/2.4/sort/basic/', $page->Link());
}
$this->assertEquals('dev/docs/en/doctest/2.4/sort/basic/', $page->Link());
}
public function testGetBreadcrumbTitle()
{
$page = new DocumentationPage(
$this->entity,
'test.md',
DOCSVIEWER_PATH . '/tests/docs/en/test.md'
);
public function testGetBreadcrumbTitle() {
$page = new DocumentationPage(
$this->entity,
'test.md',
DOCSVIEWER_PATH . '/tests/docs/en/test.md'
);
$this->assertEquals("Test - Doctest", $page->getBreadcrumbTitle());
$this->assertEquals("Test - Doctest", $page->getBreadcrumbTitle());
$page = new DocumentationFolder(
$this->entity,
'1-basic.md',
DOCSVIEWER_PATH . '/tests/docs/en/sort/1-basic.md'
);
$page = new DocumentationFolder(
$this->entity,
'1-basic.md',
DOCSVIEWER_PATH . '/tests/docs/en/sort/1-basic.md'
);
$this->assertEquals('Basic - Sort - Doctest', $page->getBreadcrumbTitle());
$this->assertEquals('Basic - Sort - Doctest', $page->getBreadcrumbTitle());
$page = new DocumentationFolder(
$this->entity,
'',
DOCSVIEWER_PATH . '/tests/docs/en/sort/'
);
$page = new DocumentationFolder(
$this->entity,
'',
DOCSVIEWER_PATH . '/tests/docs/en/sort/'
);
$this->assertEquals('Sort - Doctest', $page->getBreadcrumbTitle());
}
$this->assertEquals('Sort - Doctest', $page->getBreadcrumbTitle());
}
}

View File

@ -4,87 +4,90 @@
* @package docsviewer
* @subpackage tests
*/
class DocumentationParserTest extends SapphireTest {
class DocumentationParserTest extends SapphireTest
{
protected $entity, $entityAlt, $page, $subPage, $subSubPage, $filePage, $metaDataPage, $indexPage;
protected $entity, $entityAlt, $page, $subPage, $subSubPage, $filePage, $metaDataPage, $indexPage;
public function tearDown()
{
parent::tearDown();
public function tearDown() {
parent::tearDown();
Config::unnest();
}
Config::unnest();
}
public function setUp()
{
parent::setUp();
public function setUp() {
parent::setUp();
Config::nest();
Config::nest();
// explicitly use dev/docs. Custom paths should be tested separately
Config::inst()->update(
'DocumentationViewer', 'link_base', 'dev/docs/'
);
// explicitly use dev/docs. Custom paths should be tested separately
Config::inst()->update(
'DocumentationViewer', 'link_base', 'dev/docs/'
);
$this->entity = new DocumentationEntity('DocumentationParserTest');
$this->entity->setPath(DOCSVIEWER_PATH . '/tests/docs/en/');
$this->entity->setVersion('2.4');
$this->entity->setLanguage('en');
$this->entity = new DocumentationEntity('DocumentationParserTest');
$this->entity->setPath(DOCSVIEWER_PATH . '/tests/docs/en/');
$this->entity->setVersion('2.4');
$this->entity->setLanguage('en');
$this->entityAlt = new DocumentationEntity('DocumentationParserParserTest');
$this->entityAlt->setPath(DOCSVIEWER_PATH . '/tests/docs-parser/en/');
$this->entityAlt->setVersion('2.4');
$this->entityAlt->setLanguage('en');
$this->entityAlt = new DocumentationEntity('DocumentationParserParserTest');
$this->entityAlt->setPath(DOCSVIEWER_PATH . '/tests/docs-parser/en/');
$this->entityAlt->setVersion('2.4');
$this->entityAlt->setLanguage('en');
$this->page = new DocumentationPage(
$this->entity,
'test.md',
DOCSVIEWER_PATH . '/tests/docs/en/test.md'
);
$this->page = new DocumentationPage(
$this->entity,
'test.md',
DOCSVIEWER_PATH . '/tests/docs/en/test.md'
);
$this->subPage = new DocumentationPage(
$this->entity,
'subpage.md',
DOCSVIEWER_PATH. '/tests/docs/en/subfolder/subpage.md'
);
$this->subPage = new DocumentationPage(
$this->entity,
'subpage.md',
DOCSVIEWER_PATH. '/tests/docs/en/subfolder/subpage.md'
);
$this->subSubPage = new DocumentationPage(
$this->entity,
'subsubpage.md',
DOCSVIEWER_PATH. '/tests/docs/en/subfolder/subsubfolder/subsubpage.md'
);
$this->subSubPage = new DocumentationPage(
$this->entity,
'subsubpage.md',
DOCSVIEWER_PATH. '/tests/docs/en/subfolder/subsubfolder/subsubpage.md'
);
$this->filePage = new DocumentationPage(
$this->entityAlt,
'file-download.md',
DOCSVIEWER_PATH . '/tests/docs-parser/en/file-download.md'
);
$this->filePage = new DocumentationPage(
$this->entityAlt,
'file-download.md',
DOCSVIEWER_PATH . '/tests/docs-parser/en/file-download.md'
);
$this->metaDataPage = new DocumentationPage(
$this->entityAlt,
'MetaDataTest.md',
DOCSVIEWER_PATH . '/tests/docs-parser/en/MetaDataTest.md'
);
$this->metaDataPage = new DocumentationPage(
$this->entityAlt,
'MetaDataTest.md',
DOCSVIEWER_PATH . '/tests/docs-parser/en/MetaDataTest.md'
);
$this->indexPage = new DocumentationPage(
$this->entity,
'index.md',
DOCSVIEWER_PATH. '/tests/docs/en/index.md'
);
$this->indexPage = new DocumentationPage(
$this->entity,
'index.md',
DOCSVIEWER_PATH. '/tests/docs/en/index.md'
);
$manifest = new DocumentationManifest(true);
}
public function testRewriteCodeBlocks() {
$codePage = new DocumentationPage(
$this->entityAlt,
'CodeSnippets.md',
DOCSVIEWER_PATH . '/tests/docs-parser/en/CodeSnippets.md'
);
$manifest = new DocumentationManifest(true);
}
public function testRewriteCodeBlocks()
{
$codePage = new DocumentationPage(
$this->entityAlt,
'CodeSnippets.md',
DOCSVIEWER_PATH . '/tests/docs-parser/en/CodeSnippets.md'
);
$result = DocumentationParser::rewrite_code_blocks(
$codePage->getMarkdown()
);
$result = DocumentationParser::rewrite_code_blocks(
$codePage->getMarkdown()
);
$expected = <<<HTML
$expected = <<<HTML
#### <% control Foo %>
```
code block
@ -112,13 +115,13 @@ baz: qux
```
HTML;
$this->assertEquals($expected, $result, 'Code blocks support line breaks');
$this->assertEquals($expected, $result, 'Code blocks support line breaks');
$result = DocumentationParser::rewrite_code_blocks(
$this->page->getMarkdown()
);
$result = DocumentationParser::rewrite_code_blocks(
$this->page->getMarkdown()
);
$expected = <<<HTML
$expected = <<<HTML
```php
code block
with multiple
@ -130,24 +133,24 @@ lines
Normal text after code block
HTML;
$this->assertContains($expected, $result, 'Custom code blocks with ::: prefix');
$this->assertContains($expected, $result, 'Custom code blocks with ::: prefix');
$expected = <<<HTML
$expected = <<<HTML
```
code block
without formatting prefix
```
HTML;
$this->assertContains($expected, $result, 'Traditional markdown code blocks');
$this->assertContains($expected, $result, 'Traditional markdown code blocks');
$expected = <<<HTML
$expected = <<<HTML
```
Fenced code block
```
HTML;
$this->assertContains($expected, $result, 'Backtick code blocks');
$this->assertContains($expected, $result, 'Backtick code blocks');
$expected = <<<HTML
$expected = <<<HTML
```php
Fenced box with
@ -158,227 +161,232 @@ between
content
```
HTML;
$this->assertContains($expected, $result, 'Backtick with newlines');
}
$this->assertContains($expected, $result, 'Backtick with newlines');
}
public function testRelativeLinks() {
// index.md
$result = DocumentationParser::rewrite_relative_links(
$this->indexPage->getMarkdown(),
$this->indexPage
);
public function testRelativeLinks()
{
// index.md
$result = DocumentationParser::rewrite_relative_links(
$this->indexPage->getMarkdown(),
$this->indexPage
);
$this->assertContains(
'[link: subfolder index](dev/docs/en/documentationparsertest/2.4/subfolder/)',
$result
);
$this->assertContains(
'[link: subfolder index](dev/docs/en/documentationparsertest/2.4/subfolder/)',
$result
);
// test.md
// test.md
$result = DocumentationParser::rewrite_relative_links(
$this->page->getMarkdown(),
$this->page
);
$result = DocumentationParser::rewrite_relative_links(
$this->page->getMarkdown(),
$this->page
);
$this->assertContains(
'[link: subfolder index](dev/docs/en/documentationparsertest/2.4/subfolder/)',
$result
);
$this->assertContains(
'[link: subfolder page](dev/docs/en/documentationparsertest/2.4/subfolder/subpage/)',
$result
);
$this->assertContains(
'[link: http](http://silverstripe.org)',
$result
);
$this->assertContains(
'[link: api](api:DataObject)',
$result
);
$this->assertContains(
'[link: subfolder index](dev/docs/en/documentationparsertest/2.4/subfolder/)',
$result
);
$this->assertContains(
'[link: subfolder page](dev/docs/en/documentationparsertest/2.4/subfolder/subpage/)',
$result
);
$this->assertContains(
'[link: http](http://silverstripe.org)',
$result
);
$this->assertContains(
'[link: api](api:DataObject)',
$result
);
$result = DocumentationParser::rewrite_relative_links(
$this->subPage->getMarkdown(),
$this->subPage
);
$result = DocumentationParser::rewrite_relative_links(
$this->subPage->getMarkdown(),
$this->subPage
);
# @todo this should redirect to /subpage/
$this->assertContains(
'[link: relative](dev/docs/en/documentationparsertest/2.4/subfolder/subpage.md/)',
$result
);
# @todo this should redirect to /subpage/
$this->assertContains(
'[link: relative](dev/docs/en/documentationparsertest/2.4/subfolder/subpage.md/)',
$result
);
$this->assertContains(
'[link: absolute index](dev/docs/en/documentationparsertest/2.4/)',
$result
);
$this->assertContains(
'[link: absolute index](dev/docs/en/documentationparsertest/2.4/)',
$result
);
# @todo this should redirect to /
$this->assertContains(
'[link: absolute index with name](dev/docs/en/documentationparsertest/2.4/index/)',
$result
);
# @todo this should redirect to /
$this->assertContains(
'[link: absolute index with name](dev/docs/en/documentationparsertest/2.4/index/)',
$result
);
$this->assertContains(
'[link: relative index](dev/docs/en/documentationparsertest/2.4/)',
$result
);
$this->assertContains(
'[link: relative index](dev/docs/en/documentationparsertest/2.4/)',
$result
);
$this->assertContains(
'[link: relative parent page](dev/docs/en/documentationparsertest/2.4/test/)',
$result
);
$this->assertContains(
'[link: relative parent page](dev/docs/en/documentationparsertest/2.4/test/)',
$result
);
$this->assertContains(
'[link: absolute parent page](dev/docs/en/documentationparsertest/2.4/test/)',
$result
);
$this->assertContains(
'[link: absolute parent page](dev/docs/en/documentationparsertest/2.4/test/)',
$result
);
$result = DocumentationParser::rewrite_relative_links(
$this->subSubPage->getMarkdown(),
$this->subSubPage
);
$result = DocumentationParser::rewrite_relative_links(
$this->subSubPage->getMarkdown(),
$this->subSubPage
);
$this->assertContains(
'[link: absolute index](dev/docs/en/documentationparsertest/2.4/)',
$result
);
$this->assertContains(
'[link: absolute index](dev/docs/en/documentationparsertest/2.4/)',
$result
);
$this->assertContains(
'[link: relative index](dev/docs/en/documentationparsertest/2.4/subfolder/)',
$result
);
$this->assertContains(
'[link: relative index](dev/docs/en/documentationparsertest/2.4/subfolder/)',
$result
);
$this->assertContains(
'[link: relative parent page](dev/docs/en/documentationparsertest/2.4/subfolder/subpage/)',
$result
);
$this->assertContains(
'[link: relative parent page](dev/docs/en/documentationparsertest/2.4/subfolder/subpage/)',
$result
);
$this->assertContains(
'[link: relative grandparent page](dev/docs/en/documentationparsertest/2.4/test/)',
$result
);
$this->assertContains(
'[link: relative grandparent page](dev/docs/en/documentationparsertest/2.4/test/)',
$result
);
$this->assertContains(
'[link: absolute page](dev/docs/en/documentationparsertest/2.4/test/)',
$result
);
}
$this->assertContains(
'[link: absolute page](dev/docs/en/documentationparsertest/2.4/test/)',
$result
);
}
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'));
$this->assertEquals('title-and-one', DocumentationParser::generate_html_id('Title & One'));
$this->assertEquals('title-one', DocumentationParser::generate_html_id(' Title one '));
$this->assertEquals('title-one', DocumentationParser::generate_html_id('Title--one'));
}
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'));
$this->assertEquals('title-and-one', DocumentationParser::generate_html_id('Title & One'));
$this->assertEquals('title-one', DocumentationParser::generate_html_id(' Title one '));
$this->assertEquals('title-one', DocumentationParser::generate_html_id('Title--one'));
}
public function testImageRewrites() {
public function testImageRewrites()
{
$result = DocumentationParser::rewrite_image_links(
$this->subPage->getMarkdown(),
$this->subPage
);
$result = DocumentationParser::rewrite_image_links(
$this->subPage->getMarkdown(),
$this->subPage
);
$expected = Controller::join_links(
Director::absoluteBaseURL(), DOCSVIEWER_DIR, '/tests/docs/en/subfolder/_images/image.png'
);
$expected = Controller::join_links(
Director::absoluteBaseURL(), DOCSVIEWER_DIR, '/tests/docs/en/subfolder/_images/image.png'
);
$this->assertContains(
sprintf('[relative image link](%s)', $expected),
$result
);
$this->assertContains(
sprintf('[relative image link](%s)', $expected),
$result
);
$this->assertContains(
sprintf('[parent image link](%s)', Controller::join_links(
Director::absoluteBaseURL(), DOCSVIEWER_DIR, '/tests/docs/en/_images/image.png'
)),
$result
);
$this->assertContains(
sprintf('[parent image link](%s)', Controller::join_links(
Director::absoluteBaseURL(), DOCSVIEWER_DIR, '/tests/docs/en/_images/image.png'
)),
$result
);
$expected = Controller::join_links(
Director::absoluteBaseURL(), DOCSVIEWER_DIR, '/tests/docs/en/_images/image.png'
);
$expected = Controller::join_links(
Director::absoluteBaseURL(), DOCSVIEWER_DIR, '/tests/docs/en/_images/image.png'
);
$this->assertContains(
sprintf('[absolute image link](%s)', $expected),
$result
);
}
$this->assertContains(
sprintf('[absolute image link](%s)', $expected),
$result
);
}
public function testApiLinks()
{
$result = DocumentationParser::rewrite_api_links(
$this->page->getMarkdown(),
$this->page
);
public function testApiLinks() {
$result = DocumentationParser::rewrite_api_links(
$this->page->getMarkdown(),
$this->page
);
$this->assertContains(
'[link: api](http://api.silverstripe.org/search/lookup/?q=DataObject&amp;version=2.4&amp;module=documentationparsertest)',
$result
);
$this->assertContains(
'[DataObject::$has_one](http://api.silverstripe.org/search/lookup/?q=DataObject::$has_one&amp;version=2.4&amp;module=documentationparsertest)',
$result
);
}
$this->assertContains(
'[link: api](http://api.silverstripe.org/search/lookup/?q=DataObject&amp;version=2.4&amp;module=documentationparsertest)',
$result
);
$this->assertContains(
'[DataObject::$has_one](http://api.silverstripe.org/search/lookup/?q=DataObject::$has_one&amp;version=2.4&amp;module=documentationparsertest)',
$result
);
}
public function testHeadlineAnchors()
{
$result = DocumentationParser::rewrite_heading_anchors(
$this->page->getMarkdown(),
$this->page
);
public function testHeadlineAnchors() {
$result = DocumentationParser::rewrite_heading_anchors(
$this->page->getMarkdown(),
$this->page
);
/*
# Heading one {#Heading-one}
/*
# Heading one {#Heading-one}
# Heading with custom anchor {#custom-anchor} {#Heading-with-custom-anchor-custom-anchor}
# Heading with custom anchor {#custom-anchor} {#Heading-with-custom-anchor-custom-anchor}
## Heading two {#Heading-two}
## Heading two {#Heading-two}
### Heading three {#Heading-three}
### Heading three {#Heading-three}
## Heading duplicate {#Heading-duplicate}
## Heading duplicate {#Heading-duplicate}
## Heading duplicate {#Heading-duplicate-2}
## Heading duplicate {#Heading-duplicate-2}
## Heading duplicate {#Heading-duplicate-3}
## Heading duplicate {#Heading-duplicate-3}
*/
*/
$this->assertContains('# Heading one {#heading-one}', $result);
$this->assertContains('# Heading with custom anchor {#custom-anchor}', $result);
$this->assertNotContains('# Heading with custom anchor {#custom-anchor} {#heading', $result);
$this->assertContains('# Heading two {#heading-two}', $result);
$this->assertContains('# Heading three {#heading-three}', $result);
$this->assertContains('## Heading duplicate {#heading-duplicate}', $result);
$this->assertContains('## Heading duplicate {#heading-duplicate-2}', $result);
$this->assertContains('## Heading duplicate {#heading-duplicate-3}', $result);
}
$this->assertContains('# Heading one {#heading-one}', $result);
$this->assertContains('# Heading with custom anchor {#custom-anchor}', $result);
$this->assertNotContains('# Heading with custom anchor {#custom-anchor} {#heading', $result);
$this->assertContains('# Heading two {#heading-two}', $result);
$this->assertContains('# Heading three {#heading-three}', $result);
$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() {
DocumentationParser::retrieve_meta_data($this->metaDataPage);
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());
}
$this->assertEquals('Dr. Foo Bar.', $this->metaDataPage->author);
$this->assertEquals("Foo Bar's Test page.", $this->metaDataPage->getTitle());
}
public function testRewritingRelativeLinksToFiles() {
$parsed = DocumentationParser::parse($this->filePage);
public function testRewritingRelativeLinksToFiles()
{
$parsed = DocumentationParser::parse($this->filePage);
$this->assertContains(
DOCSVIEWER_DIR .'/tests/docs-parser/en/_images/external_link.png',
$parsed
);
$this->assertContains(
DOCSVIEWER_DIR .'/tests/docs-parser/en/_images/external_link.png',
$parsed
);
$this->assertContains(
DOCSVIEWER_DIR .'/tests/docs-parser/en/_images/test.tar.gz',
$parsed
);
}
$this->assertContains(
DOCSVIEWER_DIR .'/tests/docs-parser/en/_images/test.tar.gz',
$parsed
);
}
}

View File

@ -4,40 +4,42 @@
* @package docsviewer
* @subpackage tests
*/
class DocumentationPermalinksTest extends FunctionalTest {
class DocumentationPermalinksTest extends FunctionalTest
{
public function testSavingAndAccessingMapping()
{
// basic test
DocumentationPermalinks::add(array(
'foo' => 'en/framework/subfolder/foo',
'bar' => 'en/cms/bar'
));
public function testSavingAndAccessingMapping() {
// basic test
DocumentationPermalinks::add(array(
'foo' => 'en/framework/subfolder/foo',
'bar' => 'en/cms/bar'
));
$this->assertEquals('en/framework/subfolder/foo',
DocumentationPermalinks::map('foo')
);
$this->assertEquals('en/framework/subfolder/foo',
DocumentationPermalinks::map('foo')
);
$this->assertEquals('en/cms/bar',
DocumentationPermalinks::map('bar')
);
}
$this->assertEquals('en/cms/bar',
DocumentationPermalinks::map('bar')
);
}
/**
* Tests to make sure short codes get translated to full paths.
*
*/
public function testRedirectingMapping()
{
DocumentationPermalinks::add(array(
'foo' => 'en/framework/subfolder/foo',
'bar' => 'en/cms/bar'
));
/**
* Tests to make sure short codes get translated to full paths.
*
*/
public function testRedirectingMapping() {
DocumentationPermalinks::add(array(
'foo' => 'en/framework/subfolder/foo',
'bar' => 'en/cms/bar'
));
$this->autoFollowRedirection = false;
$this->autoFollowRedirection = false;
$v = new DocumentationViewer();
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'foo'), DataModel::inst());
$v = new DocumentationViewer();
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'foo'), DataModel::inst());
$this->assertEquals('301', $response->getStatusCode());
$this->assertContains('en/framework/subfolder/foo', $response->getHeader('Location'));
}
$this->assertEquals('301', $response->getStatusCode());
$this->assertContains('en/framework/subfolder/foo', $response->getHeader('Location'));
}
}

View File

@ -5,62 +5,65 @@
* @subpackage tests
*/
class DocumentationSearchTest extends FunctionalTest {
class DocumentationSearchTest extends FunctionalTest
{
public function setUp()
{
parent::setUp();
public function setUp() {
parent::setUp();
Config::nest();
Config::nest();
// explicitly use dev/docs. Custom paths should be tested separately
Config::inst()->update(
'DocumentationViewer', 'link_base', 'dev/docs'
);
// explicitly use dev/docs. Custom paths should be tested separately
Config::inst()->update(
'DocumentationViewer', 'link_base', 'dev/docs'
);
// disable automatic module registration so modules don't interfere.
Config::inst()->update(
'DocumentationManifest', 'automatic_registration', false
);
// disable automatic module registration so modules don't interfere.
Config::inst()->update(
'DocumentationManifest', 'automatic_registration', false
);
Config::inst()->remove('DocumentationManifest', 'register_entities');
Config::inst()->update('DocumentationSearch', 'enabled', true);
Config::inst()->update(
'DocumentationManifest', 'register_entities', array(
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-search/",
'Title' => 'Docs Search Test', )
)
);
Config::inst()->remove('DocumentationManifest', 'register_entities');
Config::inst()->update('DocumentationSearch', 'enabled', true);
Config::inst()->update(
'DocumentationManifest', 'register_entities', array(
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-search/",
'Title' => 'Docs Search Test', )
)
);
$this->manifest = new DocumentationManifest(true);
}
$this->manifest = new DocumentationManifest(true);
}
public function tearDown()
{
parent::tearDown();
public function tearDown() {
parent::tearDown();
Config::unnest();
}
Config::unnest();
}
public function testOpenSearchControllerAccessible()
{
$c = new DocumentationOpenSearchController();
$response = $c->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst());
$this->assertEquals(404, $response->getStatusCode());
public function testOpenSearchControllerAccessible() {
$c = new DocumentationOpenSearchController();
$response = $c->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst());
$this->assertEquals(404, $response->getStatusCode());
Config::inst()->update('DocumentationSearch', 'enabled', false);
Config::inst()->update('DocumentationSearch', 'enabled', false);
$response = $c->handleRequest(new SS_HTTPRequest('GET', 'description/'), DataModel::inst());
$this->assertEquals(404, $response->getStatusCode());
$response = $c->handleRequest(new SS_HTTPRequest('GET', 'description/'), DataModel::inst());
$this->assertEquals(404, $response->getStatusCode());
// test we get a response to the description. The meta data test will
// check that the individual fields are valid but we should check urls
// are there
// test we get a response to the description. The meta data test will
// check that the individual fields are valid but we should check urls
// are there
Config::inst()->update('DocumentationSearch', 'enabled', true);
Config::inst()->update('DocumentationSearch', 'enabled', true);
$response = $c->handleRequest(new SS_HTTPRequest('GET', 'description'), DataModel::inst());
$this->assertEquals(200, $response->getStatusCode());
$response = $c->handleRequest(new SS_HTTPRequest('GET', 'description'), DataModel::inst());
$this->assertEquals(200, $response->getStatusCode());
$desc = new SimpleXMLElement($response->getBody());
$this->assertEquals(2, count($desc->Url));
}
$desc = new SimpleXMLElement($response->getBody());
$this->assertEquals(2, count($desc->Url));
}
}

View File

@ -8,208 +8,213 @@
* @subpackage tests
*/
class DocumentationViewerTest extends FunctionalTest {
class DocumentationViewerTest extends FunctionalTest
{
protected $autoFollowRedirection = false;
protected $autoFollowRedirection = false;
protected $manifest;
protected $manifest;
public function setUp()
{
parent::setUp();
public function setUp() {
parent::setUp();
Config::nest();
Config::nest();
// explicitly use dev/docs. Custom paths should be tested separately
Config::inst()->update(
'DocumentationViewer', 'link_base', 'dev/docs/'
);
// explicitly use dev/docs. Custom paths should be tested separately
Config::inst()->update(
'DocumentationViewer', 'link_base', 'dev/docs/'
);
// disable automatic module registration so modules don't interfere.
Config::inst()->update(
'DocumentationManifest', 'automatic_registration', false
);
// disable automatic module registration so modules don't interfere.
Config::inst()->update(
'DocumentationManifest', 'automatic_registration', false
);
Config::inst()->remove('DocumentationManifest', 'register_entities');
Config::inst()->remove('DocumentationManifest', 'register_entities');
Config::inst()->update(
'DocumentationManifest', 'register_entities', array(
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs/",
'Title' => 'Doc Test',
'Version' => '2.3'
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-v2.4/",
'Title' => 'Doc Test',
'Version' => '2.4',
'Stable' => true
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-v3.0/",
'Title' => 'Doc Test',
'Version' => '3.0'
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-parser/",
'Title' => 'DocumentationViewerAltModule1'
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-search/",
'Title' => 'DocumentationViewerAltModule2'
)
)
);
Config::inst()->update(
'DocumentationManifest', 'register_entities', array(
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs/",
'Title' => 'Doc Test',
'Version' => '2.3'
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-v2.4/",
'Title' => 'Doc Test',
'Version' => '2.4',
'Stable' => true
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-v3.0/",
'Title' => 'Doc Test',
'Version' => '3.0'
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-parser/",
'Title' => 'DocumentationViewerAltModule1'
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-search/",
'Title' => 'DocumentationViewerAltModule2'
)
)
);
Config::inst()->update('SSViewer', 'theme_enabled', false);
Config::inst()->update('SSViewer', 'theme_enabled', false);
$this->manifest = new DocumentationManifest(true);
}
$this->manifest = new DocumentationManifest(true);
}
public function tearDown()
{
parent::tearDown();
public function tearDown() {
parent::tearDown();
Config::unnest();
}
Config::unnest();
}
/**
* This tests that all the locations will exist if we access it via the urls.
*/
public function testLocationsExists()
{
$this->autoFollowRedirection = false;
/**
* This tests that all the locations will exist if we access it via the urls.
*/
public function testLocationsExists() {
$this->autoFollowRedirection = false;
$response = $this->get('dev/docs/en/doc_test/2.3/subfolder/');
$this->assertEquals($response->getStatusCode(), 200, 'Existing base folder');
$response = $this->get('dev/docs/en/doc_test/2.3/subfolder/');
$this->assertEquals($response->getStatusCode(), 200, 'Existing base folder');
$response = $this->get('dev/docs/en/doc_test/2.3/subfolder/subsubfolder/');
$this->assertEquals($response->getStatusCode(), 200, 'Existing base folder');
$response = $this->get('dev/docs/en/doc_test/2.3/subfolder/subsubfolder/');
$this->assertEquals($response->getStatusCode(), 200, 'Existing base folder');
$response = $this->get('dev/docs/en/doc_test/2.3/subfolder/subsubfolder/subsubpage/');
$this->assertEquals($response->getStatusCode(), 200, 'Existing base folder');
$response = $this->get('dev/docs/en/doc_test/2.3/subfolder/subsubfolder/subsubpage/');
$this->assertEquals($response->getStatusCode(), 200, 'Existing base folder');
$response = $this->get('dev/docs/en/');
$this->assertEquals($response->getStatusCode(), 200, 'Lists the home index');
$response = $this->get('dev/docs/en/');
$this->assertEquals($response->getStatusCode(), 200, 'Lists the home index');
$response = $this->get('dev/docs/');
$this->assertEquals($response->getStatusCode(), 302, 'Go to english view');
$response = $this->get('dev/docs/');
$this->assertEquals($response->getStatusCode(), 302, 'Go to english view');
$response = $this->get('dev/docs/en/doc_test/3.0/empty.md');
$this->assertEquals(301, $response->getStatusCode(), 'Direct markdown links also work. They should redirect to /empty/');
$response = $this->get('dev/docs/en/doc_test/3.0/empty.md');
$this->assertEquals(301, $response->getStatusCode(), 'Direct markdown links also work. They should redirect to /empty/');
// 2.4 is the stable release. Not in the URL
$response = $this->get('dev/docs/en/doc_test/2.4');
$this->assertEquals($response->getStatusCode(), 200, 'Existing base folder');
$this->assertContains('english test', $response->getBody(), 'Toplevel content page');
// 2.4 is the stable release. Not in the URL
$response = $this->get('dev/docs/en/doc_test/2.4');
$this->assertEquals($response->getStatusCode(), 200, 'Existing base folder');
$this->assertContains('english test', $response->getBody(), 'Toplevel content page');
// accessing base redirects to the version with the version number.
$response = $this->get('dev/docs/en/doc_test/');
$this->assertEquals($response->getStatusCode(), 301, 'Existing base folder redirects to with version');
// accessing base redirects to the version with the version number.
$response = $this->get('dev/docs/en/doc_test/');
$this->assertEquals($response->getStatusCode(), 301, 'Existing base folder redirects to with version');
$response = $this->get('dev/docs/en/doc_test/3.0/');
$this->assertEquals($response->getStatusCode(), 200, 'Existing base folder');
$response = $this->get('dev/docs/en/doc_test/3.0/');
$this->assertEquals($response->getStatusCode(), 200, 'Existing base folder');
$response = $this->get('dev/docs/en/doc_test/2.3/nonexistant-subfolder');
$this->assertEquals($response->getStatusCode(), 404, 'Nonexistant subfolder');
$response = $this->get('dev/docs/en/doc_test/2.3/nonexistant-subfolder');
$this->assertEquals($response->getStatusCode(), 404, 'Nonexistant subfolder');
$response = $this->get('dev/docs/en/doc_test/2.3/nonexistant-file.txt');
$this->assertEquals($response->getStatusCode(), 301, 'Nonexistant file');
$response = $this->get('dev/docs/en/doc_test/2.3/nonexistant-file.txt');
$this->assertEquals($response->getStatusCode(), 301, 'Nonexistant file');
$response = $this->get('dev/docs/en/doc_test/2.3/nonexistant-file/');
$this->assertEquals($response->getStatusCode(), 404, 'Nonexistant file');
$response = $this->get('dev/docs/en/doc_test/2.3/nonexistant-file/');
$this->assertEquals($response->getStatusCode(), 404, 'Nonexistant file');
$response = $this->get('dev/docs/en/doc_test/2.3/test');
$this->assertEquals($response->getStatusCode(), 200, 'Existing file');
$response = $this->get('dev/docs/en/doc_test/2.3/test');
$this->assertEquals($response->getStatusCode(), 200, 'Existing file');
$response = $this->get('dev/docs/en/doc_test/3.0/empty?foo');
$this->assertEquals(200, $response->getStatusCode(), 'Existing page');
$response = $this->get('dev/docs/en/doc_test/3.0/empty?foo');
$this->assertEquals(200, $response->getStatusCode(), 'Existing page');
$response = $this->get('dev/docs/en/doc_test/3.0/empty/');
$this->assertEquals($response->getStatusCode(), 200, 'Existing page');
$response = $this->get('dev/docs/en/doc_test/3.0/empty/');
$this->assertEquals($response->getStatusCode(), 200, 'Existing page');
$response = $this->get('dev/docs/en/doc_test/3.0/test');
$this->assertEquals($response->getStatusCode(), 404, 'Missing page');
$response = $this->get('dev/docs/en/doc_test/3.0/test');
$this->assertEquals($response->getStatusCode(), 404, 'Missing page');
$response = $this->get('dev/docs/en/doc_test/3.0/test.md');
$this->assertEquals($response->getStatusCode(), 301, 'Missing page');
$response = $this->get('dev/docs/en/doc_test/3.0/test.md');
$this->assertEquals($response->getStatusCode(), 301, 'Missing page');
$response = $this->get('dev/docs/en/doc_test/3.0/test/');
$this->assertEquals($response->getStatusCode(), 404, 'Missing page');
$response = $this->get('dev/docs/en/doc_test/3.0/test/');
$this->assertEquals($response->getStatusCode(), 404, 'Missing page');
$response = $this->get('dev/docs/dk/');
$this->assertEquals($response->getStatusCode(), 404, 'Access a language that doesn\'t exist');
}
$response = $this->get('dev/docs/dk/');
$this->assertEquals($response->getStatusCode(), 404, 'Access a language that doesn\'t exist');
}
public function testGetMenu() {
$v = new DocumentationViewer();
// check with children
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.3/'), DataModel::inst());
public function testGetMenu()
{
$v = new DocumentationViewer();
// check with children
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.3/'), DataModel::inst());
$expected = array(
'dev/docs/en/doc_test/2.3/sort/' => 'Sort',
'dev/docs/en/doc_test/2.3/subfolder/' => 'Subfolder',
'dev/docs/en/doc_test/2.3/test/' => 'Test'
);
$expected = array(
'dev/docs/en/doc_test/2.3/sort/' => 'Sort',
'dev/docs/en/doc_test/2.3/subfolder/' => 'Subfolder',
'dev/docs/en/doc_test/2.3/test/' => 'Test'
);
$actual = $v->getMenu()->first()->Children->map('Link', 'Title');
$this->assertEquals($expected, $actual);
$actual = $v->getMenu()->first()->Children->map('Link', 'Title');
$this->assertEquals($expected, $actual);
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.4/'), DataModel::inst());
$this->assertEquals('current', $v->getMenu()->first()->LinkingMode);
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.4/'), DataModel::inst());
$this->assertEquals('current', $v->getMenu()->first()->LinkingMode);
// 2.4 stable release has 1 child page (not including index)
$this->assertEquals(1, $v->getMenu()->first()->Children->count());
// 2.4 stable release has 1 child page (not including index)
$this->assertEquals(1, $v->getMenu()->first()->Children->count());
// menu should contain all the english entities
$expected = array(
'dev/docs/en/doc_test/2.4/' => 'Doc Test',
'dev/docs/en/documentationvieweraltmodule1/' => 'DocumentationViewerAltModule1',
'dev/docs/en/documentationvieweraltmodule2/' => 'DocumentationViewerAltModule2'
);
// menu should contain all the english entities
$expected = array(
'dev/docs/en/doc_test/2.4/' => 'Doc Test',
'dev/docs/en/documentationvieweraltmodule1/' => 'DocumentationViewerAltModule1',
'dev/docs/en/documentationvieweraltmodule2/' => 'DocumentationViewerAltModule2'
);
$this->assertEquals($expected, $v->getMenu()->map('Link', 'Title'));
}
$this->assertEquals($expected, $v->getMenu()->map('Link', 'Title'));
}
public function testGetLanguage() {
$v = new DocumentationViewer();
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.3/'), DataModel::inst());
public function testGetLanguage()
{
$v = new DocumentationViewer();
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.3/'), DataModel::inst());
$this->assertEquals('en', $v->getLanguage());
$this->assertEquals('en', $v->getLanguage());
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.3/subfolder/subsubfolder/subsubpage/'), DataModel::inst());
$this->assertEquals('en', $v->getLanguage());
}
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.3/subfolder/subsubfolder/subsubpage/'), DataModel::inst());
$this->assertEquals('en', $v->getLanguage());
}
public function testAccessingAll() {
$response = $this->get('dev/docs/en/all/');
public function testAccessingAll()
{
$response = $this->get('dev/docs/en/all/');
// should response with the documentation index
$this->assertEquals(200, $response->getStatusCode());
// should response with the documentation index
$this->assertEquals(200, $response->getStatusCode());
$items = $this->cssParser()->getBySelector('#documentation_index');
$this->assertNotEmpty($items);
$items = $this->cssParser()->getBySelector('#documentation_index');
$this->assertNotEmpty($items);
// should also have a DE version of the page
$response = $this->get('dev/docs/de/all/');
// should also have a DE version of the page
$response = $this->get('dev/docs/de/all/');
// should response with the documentation index
$this->assertEquals(200, $response->getStatusCode());
// should response with the documentation index
$this->assertEquals(200, $response->getStatusCode());
$items = $this->cssParser()->getBySelector('#documentation_index');
$this->assertNotEmpty($items);
$items = $this->cssParser()->getBySelector('#documentation_index');
$this->assertNotEmpty($items);
// accessing a language that doesn't exist should throw a 404
$response = $this->get('dev/docs/fu/all/');
$this->assertEquals(404, $response->getStatusCode());
// accessing a language that doesn't exist should throw a 404
$response = $this->get('dev/docs/fu/all/');
$this->assertEquals(404, $response->getStatusCode());
// accessing all without a language should fail
$response = $this->get('dev/docs/all/');
$this->assertEquals(404, $response->getStatusCode());
}
// accessing all without a language should fail
$response = $this->get('dev/docs/all/');
$this->assertEquals(404, $response->getStatusCode());
}
}

View File

@ -4,83 +4,85 @@
* @package docsviewer
* @subpackage tests
*/
class DocumentationViewerVersionWarningTest extends SapphireTest {
class DocumentationViewerVersionWarningTest extends SapphireTest
{
protected $autoFollowRedirection = false;
protected $autoFollowRedirection = false;
private $manifest;
private $manifest;
public function setUp()
{
parent::setUp();
public function setUp() {
parent::setUp();
Config::nest();
Config::nest();
// explicitly use dev/docs. Custom paths should be tested separately
Config::inst()->update(
'DocumentationViewer', 'link_base', 'dev/docs'
);
// explicitly use dev/docs. Custom paths should be tested separately
Config::inst()->update(
'DocumentationViewer', 'link_base', 'dev/docs'
);
// disable automatic module registration so modules don't interfere.
Config::inst()->update(
'DocumentationManifest', 'automatic_registration', false
);
// disable automatic module registration so modules don't interfere.
Config::inst()->update(
'DocumentationManifest', 'automatic_registration', false
);
Config::inst()->remove('DocumentationManifest', 'register_entities');
Config::inst()->remove('DocumentationManifest', 'register_entities');
Config::inst()->update(
'DocumentationManifest', 'register_entities', array(
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs/",
'Title' => 'Doc Test',
'Key' => 'testdocs',
'Version' => '2.3'
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-v2.4/",
'Title' => 'Doc Test',
'Version' => '2.4',
'Key' => 'testdocs',
'Stable' => true
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-v3.0/",
'Title' => 'Doc Test',
'Key' => 'testdocs',
'Version' => '3.0'
)
)
);
Config::inst()->update(
'DocumentationManifest', 'register_entities', array(
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs/",
'Title' => 'Doc Test',
'Key' => 'testdocs',
'Version' => '2.3'
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-v2.4/",
'Title' => 'Doc Test',
'Version' => '2.4',
'Key' => 'testdocs',
'Stable' => true
),
array(
'Path' => DOCSVIEWER_PATH . "/tests/docs-v3.0/",
'Title' => 'Doc Test',
'Key' => 'testdocs',
'Version' => '3.0'
)
)
);
$this->manifest = new DocumentationManifest(true);
}
$this->manifest = new DocumentationManifest(true);
}
public function tearDown()
{
parent::tearDown();
public function tearDown() {
parent::tearDown();
Config::unnest();
}
Config::unnest();
public function testVersionWarning()
{
$v = new DocumentationViewer();
}
public function testVersionWarning() {
$v = new DocumentationViewer();
// the current version is set to 2.4, no notice should be shown on that page
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/testdocs/'), DataModel::inst());
$this->assertFalse($v->VersionWarning());
// the current version is set to 2.4, no notice should be shown on that page
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/testdocs/'), DataModel::inst());
$this->assertFalse($v->VersionWarning());
// 2.3 is an older release, hitting that should return us an outdated flag
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/testdocs/2.3/'), DataModel::inst());
$warn = $v->VersionWarning();
// 2.3 is an older release, hitting that should return us an outdated flag
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/testdocs/2.3/'), DataModel::inst());
$warn = $v->VersionWarning();
$this->assertTrue($warn->OutdatedRelease);
$this->assertNull($warn->FutureRelease);
$this->assertTrue($warn->OutdatedRelease);
$this->assertNull($warn->FutureRelease);
// 3.0 is a future release
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/testdocs/3.0/'), DataModel::inst());
$warn = $v->VersionWarning();
// 3.0 is a future release
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/testdocs/3.0/'), DataModel::inst());
$warn = $v->VersionWarning();
$this->assertNull($warn->OutdatedRelease);
$this->assertTrue($warn->FutureRelease);
}
$this->assertNull($warn->OutdatedRelease);
$this->assertTrue($warn->FutureRelease);
}
}