Code Style and documentation

This commit is contained in:
Stéphane Goetz 2015-07-17 23:38:06 +02:00
parent e7afd9aa28
commit 4f8d817365
22 changed files with 415 additions and 177 deletions

View File

@ -2,11 +2,18 @@
use ArrayObject; use ArrayObject;
class Config extends ArrayObject { class Config extends ArrayObject
{
public function merge($newValues, $override = true) { /**
* Merge an array into the object
*
* @param array $newValues
* @param bool $override
*/
public function merge($newValues, $override = true)
{
foreach ($newValues as $key => $value) { foreach ($newValues as $key => $value) {
if (array_key_exists($key, $this) && $override == false) { if ($override === false && array_key_exists($key, $this)) {
continue; continue;
} }
@ -14,7 +21,13 @@ class Config extends ArrayObject {
} }
} }
public function conservativeMerge($newValues) { /**
* Merge an array into the object, ignore already added keys.
*
* @param $newValues
*/
public function conservativeMerge($newValues)
{
$this->merge($newValues, false); $this->merge($newValues, false);
} }
} }

View File

@ -19,9 +19,10 @@ class Daux
protected $processor; protected $processor;
/** /**
* @var Tree\Entry * @var Tree\Directory
*/ */
public $tree; public $tree;
/** /**
* @var Config * @var Config
*/ */
@ -84,6 +85,14 @@ class Daux
$this->options->merge($default_config); $this->options->merge($default_config);
} }
/**
* Load the configuration files, first, "config.json"
* in the documentation and then the file specified
* when running the configuration
*
* @param string $override_file
* @throws Exception
*/
private function loadConfigOverrides($override_file) private function loadConfigOverrides($override_file)
{ {
// Read documentation overrides // Read documentation overrides

View File

@ -4,6 +4,11 @@ use Todaymade\Daux\Tree\Directory;
class DauxHelper class DauxHelper
{ {
/**
* @param Config $params
* @param string $current_url
* @return array
*/
public static function getTheme($params, $current_url) public static function getTheme($params, $current_url)
{ {
$theme_folder = $params['local_base'] . DS . 'resources' . DS . 'themes' . DS . $params['theme-name']; $theme_folder = $params['local_base'] . DS . 'resources' . DS . 'themes' . DS . $params['theme-name'];
@ -39,21 +44,19 @@ class DauxHelper
$theme['templates'] = strtr($theme['templates'], $substitutions); $theme['templates'] = strtr($theme['templates'], $substitutions);
$theme['favicon'] = utf8_encode(strtr($theme['favicon'], $substitutions)); $theme['favicon'] = utf8_encode(strtr($theme['favicon'], $substitutions));
foreach ($theme['css'] as $key => $css) { foreach (['css', 'js', 'fonts'] as $element) {
$theme['css'][$key] = utf8_encode(strtr($css, $substitutions)); foreach ($theme[$element] as $key => $value) {
} $theme[$element][$key] = utf8_encode(strtr($value, $substitutions));
}
foreach ($theme['fonts'] as $key => $font) {
$theme['fonts'][$key] = utf8_encode(strtr($font, $substitutions));
}
foreach ($theme['js'] as $key => $js) {
$theme['js'][$key] = utf8_encode(strtr($js, $substitutions));
} }
return $theme; return $theme;
} }
/**
* @param string $path
* @return string
*/
public static function getCleanPath($path) public static function getCleanPath($path)
{ {
$path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path); $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
@ -72,24 +75,31 @@ class DauxHelper
return implode(DIRECTORY_SEPARATOR, $absolutes); return implode(DIRECTORY_SEPARATOR, $absolutes);
} }
/**
* Get pathinfo for a file
*
* @param string $path
* @return array
*/
public static function pathinfo($path) public static function pathinfo($path)
{ {
preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $m); preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $m);
if (isset($m[1])) { $ret = [];
$ret['dir']=$m[1]; foreach (['dir' => 1, 'basename' => 2, 'filename' => 3, 'extension' => 5] as $key => $group) {
} if (isset($m[$group])) {
if (isset($m[2])) { $ret[$key] = $m[$group];
$ret['basename']=$m[2]; }
}
if (isset($m[5])) {
$ret['extension']=$m[5];
}
if (isset($m[3])) {
$ret['filename']=$m[3];
} }
return $ret; return $ret;
} }
/**
* Locate a file in the tree. Returns the file if found or false
*
* @param Directory $tree
* @param string $request
* @return Tree\Entry|false
*/
public static function getFile($tree, $request) public static function getFile($tree, $request)
{ {
$request = explode('/', $request); $request = explode('/', $request);
@ -148,11 +158,14 @@ class DauxHelper
$separator = '_'; $separator = '_';
// Convert all dashes into underscores // Convert all dashes into underscores
$title = preg_replace('!['.preg_quote("-").']+!u', $separator, $title); $title = preg_replace('![' . preg_quote("-") . ']+!u', $separator, $title);
// Remove all characters that are not the separator, letters, numbers, or whitespace. // Remove all characters that are not the separator, letters, numbers, or whitespace.
$title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', $title); $title = preg_replace('![^' . preg_quote($separator) . '\pL\pN\s]+!u', '', $title);
// Replace all separator characters and whitespace by a single separator // Replace all separator characters and whitespace by a single separator
$title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title); $title = preg_replace('![' . preg_quote($separator) . '\s]+!u', $separator, $title);
return trim($title, $separator); return trim($title, $separator);
} }
@ -167,7 +180,9 @@ class DauxHelper
{ {
static $charsArray; static $charsArray;
if (isset($charsArray)) return $charsArray; if (isset($charsArray)) {
return $charsArray;
}
return $charsArray = array( return $charsArray = array(
'a' => array( 'a' => array(
@ -238,7 +253,7 @@ class DauxHelper
'Ἇ', 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'Ᾰ', 'Ἇ', 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'Ᾰ',
'Ᾱ', 'Ὰ', 'Ά', 'ᾼ', 'А'), 'Ᾱ', 'Ὰ', 'Ά', 'ᾼ', 'А'),
'B' => array('Б', 'Β'), 'B' => array('Б', 'Β'),
'C' => array('Ç','Ć', 'Č', 'Ĉ', 'Ċ'), 'C' => array('Ç', 'Ć', 'Č', 'Ĉ', 'Ċ'),
'D' => array('Ď', 'Ð', 'Đ', 'Ɖ', 'Ɗ', 'Ƌ', 'ᴅ', 'ᴆ', 'Д', 'Δ'), 'D' => array('Ď', 'Ð', 'Đ', 'Ɖ', 'Ɗ', 'Ƌ', 'ᴅ', 'ᴆ', 'Д', 'Δ'),
'E' => array('É', 'È', 'Ẻ', 'Ẽ', 'Ẹ', 'Ê', 'Ế', 'Ề', 'Ể', 'Ễ', 'E' => array('É', 'È', 'Ẻ', 'Ẽ', 'Ẹ', 'Ê', 'Ế', 'Ề', 'Ể', 'Ễ',
'Ệ', 'Ë', 'Ē', 'Ę', 'Ě', 'Ĕ', 'Ė', 'Ε', 'Έ', 'Ἐ', 'Ệ', 'Ë', 'Ē', 'Ę', 'Ě', 'Ĕ', 'Ė', 'Ε', 'Έ', 'Ἐ',

View File

@ -27,7 +27,7 @@ class CommonMarkConverter extends \League\CommonMark\CommonMarkConverter
protected function getLinkRenderer(Environment $environment) protected function getLinkRenderer(Environment $environment)
{ {
return new LinkRenderer($environment->getConfig('daux')); return new LinkRenderer($environment->getConfig('daux'));
} }
protected function extendEnvironment(Environment $environment) protected function extendEnvironment(Environment $environment)

View File

@ -22,12 +22,12 @@ class LinkRenderer extends \League\CommonMark\Inline\Renderer\LinkRenderer
} }
/** /**
* @param $url * @param string $url
* @return Entry * @return Entry
* @throws Exception * @throws Exception
*/ */
protected function resolveInternalFile($url) { protected function resolveInternalFile($url)
{
$file = DauxHelper::getFile($this->daux['tree'], $url); $file = DauxHelper::getFile($this->daux['tree'], $url);
if ($file) { if ($file) {
return $file; return $file;

View File

@ -3,11 +3,9 @@
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException; use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\ParseException; use GuzzleHttp\Exception\ParseException;
use GuzzleHttp\Exception\TransferException;
class Api class Api
{ {
protected $base_url; protected $base_url;
protected $user; protected $user;
protected $pass; protected $pass;
@ -75,61 +73,24 @@ class Api
} }
/** /**
* /rest/api/content/{id}/child/{type} * Get a list of pages
* *
* @param $rootPage * @param integer $rootPage
* @return mixed * @param bool $recursive
* @return array
*/ */
public function getList($rootPage) public function getList($rootPage, $recursive = false)
{ {
//We do a limit of 15 as it appears that confluence has $increment = 15;
//a bug when retrieving more than 20 entries with "body.storage"
$url = "content/$rootPage/child/page?expand=version,body.storage&limit=15"; // We set a limit of 15 as it appears that
// Confluence fails silently when retrieving
// more than 20 entries with "body.storage"
$base_url = $url = "content/$rootPage/child/page?expand=version,body.storage&limit=$increment";
$start = 0;
$pages = []; $pages = [];
do {
try {
$list = $this->getClient()->get($url)->json();
} catch (BadResponseException $e) {
throw $this->handleError($e);
}
foreach ($list['results'] as $result) {
$pages[$result['title']] = [
"id" => $result['id'],
"title" => $result['title'],
"version" => $result['version']['number'],
"content" => $result['body']['storage']['value'],
];
}
if (array_key_exists('next', $list['_links'])) {
$url = $list['_links']['next'];
}
} while (array_key_exists('next', $list['_links']));
return $pages;
}
/**
* /rest/api/content/{id}/child/{type}
*
* @param $rootPage
* @return mixed
*/
public function getHierarchy($rootPage)
{
$increment = 15;
//We do a limit of 15 as it appears that confluence has
//a bug when retrieving more than 20 entries with "body.storage"
$base_url = $url = "content/$rootPage/child/page?expand=version,body.storage&limit=$increment";
$start = 0;
$children = [];
do { do {
try { try {
$hierarchy = $this->getClient()->get($url)->json(); $hierarchy = $this->getClient()->get($url)->json();
@ -138,24 +99,35 @@ class Api
} }
foreach ($hierarchy['results'] as $result) { foreach ($hierarchy['results'] as $result) {
$children[$result['title']] = [ $pages[$result['title']] = [
"id" => $result['id'], "id" => $result['id'],
"title" => $result['title'], "title" => $result['title'],
"version" => $result['version']['number'], "version" => $result['version']['number'],
"content" => $result['body']['storage']['value'], "content" => $result['body']['storage']['value'],
"children" => $this->getHierarchy($result['id'])
]; ];
if ($recursive) {
$pages[$result['title']]['children'] = $this->getList($result['id'], true);
}
} }
//We don't use _links->next as after ~30 elements it doesn't show any new elements // We don't use _links->next as after ~30 elements
$start += $increment; // it doesn't show any new elements. This seems
$url = "$base_url&start=$start"; // to be a bug in Confluence
$start += $increment;
$url = "$base_url&start=$start";
} while (!empty($hierarchy['results'])); } while (!empty($hierarchy['results']));
return $children; return $pages;
} }
/**
* @param integer $parent_id
* @param string $title
* @param string $content
* @return integer
*/
public function createPage($parent_id, $title, $content) public function createPage($parent_id, $title, $content)
{ {
$body = [ $body = [
@ -167,7 +139,7 @@ class Api
]; ];
try { try {
$response = $this->getClient()->post('content', [ 'json' => $body ])->json(); $response = $this->getClient()->post('content', ['json' => $body])->json();
} catch (BadResponseException $e) { } catch (BadResponseException $e) {
throw $this->handleError($e); throw $this->handleError($e);
} }
@ -175,6 +147,13 @@ class Api
return $response['id']; return $response['id'];
} }
/**
* @param integer $parent_id
* @param integer $page_id
* @param integer $newVersion
* @param string $title
* @param string $content
*/
public function updatePage($parent_id, $page_id, $newVersion, $title, $content) public function updatePage($parent_id, $page_id, $newVersion, $title, $content)
{ {
$body = [ $body = [
@ -193,6 +172,12 @@ class Api
} }
} }
/**
* Delete a page
*
* @param integer $page_id
* @return mixed
*/
public function deletePage($page_id) public function deletePage($page_id)
{ {
try { try {
@ -202,6 +187,10 @@ class Api
} }
} }
/**
* @param integer $id
* @param array $attachment
*/
public function uploadAttachment($id, $attachment) public function uploadAttachment($id, $attachment)
{ {
//get if attachment is uploaded //get if attachment is uploaded
@ -211,13 +200,13 @@ class Api
throw $this->handleError($e); throw $this->handleError($e);
} }
$url = "content/$id/child/attachment" . (count($result['results'])? "/{$result['results'][0]['id']}/data" : ""); $url = "content/$id/child/attachment" . count($result['results']) ? "/{$result['results'][0]['id']}/data" : "";
try { try {
$this->getClient()->post( $this->getClient()->post(
$url, $url,
[ [
'body' => ['file' => fopen($attachment['file']->getPath(), 'r')] , 'body' => ['file' => fopen($attachment['file']->getPath(), 'r')],
'headers' => ['X-Atlassian-Token' => 'nocheck'], 'headers' => ['X-Atlassian-Token' => 'nocheck'],
] ]
); );

View File

@ -24,7 +24,7 @@ class IndentedCodeRenderer implements BlockRendererInterface
return new HtmlElement( return new HtmlElement(
'ac:structured-macro', 'ac:structured-macro',
['ac:name' => 'code'], ['ac:name' => 'code'],
new HtmlElement('ac:plain-text-body', [], '<![CDATA['.$block->getStringContent().']]>') new HtmlElement('ac:plain-text-body', [], '<![CDATA[' . $block->getStringContent() . ']]>')
); );
} }
} }

View File

@ -30,7 +30,7 @@ class LinkRenderer extends \Todaymade\Daux\Format\Base\CommonMark\LinkRenderer
'ri:space-key' => $this->daux['confluence']['space_id'] 'ri:space-key' => $this->daux['confluence']['space_id']
]; ];
$page = strval(new HtmlElement('ri:page', $link_props, '', true)); $page = strval(new HtmlElement('ri:page', $link_props, '', true));
$children = $htmlRenderer->renderInlines($inline->getChildren()); $children = $htmlRenderer->renderInlines($inline->getChildren());
if (strpos($children, "<") !== false) { if (strpos($children, "<") !== false) {
$children = '<ac:link-body>' . $children . '</ac:link-body>'; $children = '<ac:link-body>' . $children . '</ac:link-body>';

View File

@ -21,7 +21,7 @@ class MarkdownPage extends \Todaymade\Daux\Format\Base\MarkdownPage
// We do it after generation so we can catch the images that were in html already // We do it after generation so we can catch the images that were in html already
$page = preg_replace_callback( $page = preg_replace_callback(
"/<img\\s+[^>]*src=['\"]([^\"]*)['\"][^>]*>/", "/<img\\s+[^>]*src=['\"]([^\"]*)['\"][^>]*>/",
function ($matches) { function($matches) {
if ($result = $this->findImage($matches[1], $matches[0])) { if ($result = $this->findImage($matches[1], $matches[0])) {
return $result; return $result;
@ -84,7 +84,7 @@ class MarkdownPage extends \Todaymade\Daux\Format\Base\MarkdownPage
$img = "<ac:image"; $img = "<ac:image";
foreach ($attributes as $name => $value) { foreach ($attributes as $name => $value) {
$img .= ' ac:' . $name.'="'.htmlentities($value, ENT_QUOTES, 'UTF-8', false).'"'; $img .= ' ac:' . $name . '="' . htmlentities($value, ENT_QUOTES, 'UTF-8', false) . '"';
} }
$img .= "><ri:attachment ri:filename=\"$filename\" /></ac:image>"; $img .= "><ri:attachment ri:filename=\"$filename\" /></ac:image>";

View File

@ -45,11 +45,12 @@ class Publisher
$this->client->setSpace($confluence['space_id']); $this->client->setSpace($confluence['space_id']);
} }
public function run($title, $closure) { public function run($title, $closure)
{
try { try {
return $this->runAction($title, $this->output, $this->width, $closure); return $this->runAction($title, $this->output, $this->width, $closure);
} catch (BadResponseException $e) { } catch (BadResponseException $e) {
$this->output->writeLn(" <error>" . $e->getMessage() . "</error>"); $this->output->writeLn(" <error>" . $e->getMessage() . "</error>");
} }
} }
@ -69,7 +70,7 @@ class Publisher
"Getting already published pages...", "Getting already published pages...",
function() use (&$published) { function() use (&$published) {
if ($published != null) { if ($published != null) {
$published['children'] = $this->client->getHierarchy($published['id']); $published['children'] = $this->client->getList($published['id'], true);
} }
} }
); );
@ -149,7 +150,7 @@ class Publisher
protected function createRecursive($parent_id, $entry, $published) protected function createRecursive($parent_id, $entry, $published)
{ {
$callback = function ($parent_id, $entry, $published) { $callback = function($parent_id, $entry, $published) {
//TODO :: remove deleted pages //TODO :: remove deleted pages
@ -173,7 +174,7 @@ class Publisher
protected function updateRecursive($parent_id, $entry, $published) protected function updateRecursive($parent_id, $entry, $published)
{ {
$callback = function ($parent_id, $entry, $published) { $callback = function($parent_id, $entry, $published) {
if (array_key_exists('id', $published) && array_key_exists('page', $entry)) { if (array_key_exists('id', $published) && array_key_exists('page', $entry)) {
$this->updatePage($parent_id, $entry, $published); $this->updatePage($parent_id, $entry, $published);
} }
@ -246,7 +247,7 @@ class Publisher
foreach ($entry['page']->attachments as $attachment) { foreach ($entry['page']->attachments as $attachment) {
$this->run( $this->run(
" With attachment: $attachment[filename]", " With attachment: $attachment[filename]",
function() use($published, $attachment) { function() use ($published, $attachment) {
$this->client->uploadAttachment($published['id'], $attachment); $this->client->uploadAttachment($published['id'], $attachment);
} }
); );

View File

@ -32,6 +32,17 @@ class Generator
$this->generateRecursive($daux->tree, $destination, $params, $output, $width); $this->generateRecursive($daux->tree, $destination, $params, $output, $width);
} }
/**
* Recursively generate the documentation
*
* @param \Todaymade\Daux\Tree\Entry $tree
* @param string $output_dir
* @param \Todaymade\Daux\Config $params
* @param OutputInterface $output
* @param integer $width
* @param string $base_url
* @throws \Exception
*/
private function generateRecursive($tree, $output_dir, $params, $output, $width, $base_url = '') private function generateRecursive($tree, $output_dir, $params, $output, $width, $base_url = '')
{ {
$params['base_url'] = $params['base_page'] = $base_url; $params['base_url'] = $params['base_page'] = $base_url;
@ -46,7 +57,7 @@ class Generator
foreach ($tree->value as $key => $node) { foreach ($tree->value as $key => $node) {
if ($node instanceof Directory) { if ($node instanceof Directory) {
$new_output_dir = $output_dir . DS . $key; $new_output_dir = $output_dir . DS . $key;
@mkdir($new_output_dir); mkdir($new_output_dir);
$this->generateRecursive($node, $new_output_dir, $params, $output, $width, '../' . $base_url); $this->generateRecursive($node, $new_output_dir, $params, $output, $width, '../' . $base_url);
} elseif ($node instanceof Content) { } elseif ($node instanceof Content) {
$this->runAction( $this->runAction(

View File

@ -79,6 +79,6 @@ class MarkdownPage extends \Todaymade\Daux\Format\Base\MarkdownPage
} }
$template = new Template($params['templates'], $params['theme']['templates']); $template = new Template($params['templates'], $params['theme']['templates']);
return $template->render($this->homepage? 'home' : 'content', ['page' => $page, 'params' => $params]); return $template->render($this->homepage ? 'home' : 'content', ['page' => $page, 'params' => $params]);
} }
} }

View File

@ -7,6 +7,10 @@ class Template
{ {
protected $engine; protected $engine;
/**
* @param string $base
* @param string $theme
*/
public function __construct($base, $theme) public function __construct($base, $theme)
{ {
// Create new Plates instance // Create new Plates instance
@ -19,6 +23,11 @@ class Template
$this->registerFunctions(); $this->registerFunctions();
} }
/**
* @param string $name
* @param array $data
* @return string
*/
public function render($name, array $data = array()) public function render($name, array $data = array())
{ {
$this->engine->addData([ $this->engine->addData([
@ -94,7 +103,7 @@ class Template
$nav[] = [ $nav[] = [
'title' => $node->getTitle(), 'title' => $node->getTitle(),
'href' => $base_page . $link, 'href' => $base_page . $link,
'class' => ($current_url === $link)? 'active' : '' 'class' => ($current_url === $link) ? 'active' : ''
]; ];
} }
if ($node instanceof \Todaymade\Daux\Tree\Directory) { if ($node instanceof \Todaymade\Daux\Tree\Directory) {
@ -102,7 +111,7 @@ class Template
$folder = [ $folder = [
'title' => $node->getTitle(), 'title' => $node->getTitle(),
'class' => (strpos($current_url, $link) === 0)? 'open' : '', 'class' => (strpos($current_url, $link) === 0) ? 'open' : '',
]; ];
if ($mode === Daux::STATIC_MODE) { if ($mode === Daux::STATIC_MODE) {
@ -123,6 +132,10 @@ class Template
return $nav; return $nav;
} }
/**
* @param string $separator
* @return string
*/
private function getSeparator($separator) private function getSeparator($separator)
{ {
switch ($separator) { switch ($separator) {

View File

@ -4,7 +4,6 @@ use Symfony\Component\Console\Command\Command as SymfonyCommand;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Todaymade\Daux\Daux; use Todaymade\Daux\Daux;
use Todaymade\Daux\Format\HTML\Generator as HTMLGenerator; use Todaymade\Daux\Format\HTML\Generator as HTMLGenerator;
use Todaymade\Daux\Format\Confluence\Generator as ConfluenceGenerator; use Todaymade\Daux\Format\Confluence\Generator as ConfluenceGenerator;
@ -31,20 +30,20 @@ class Command extends SymfonyCommand
$width = $this->getApplication()->getTerminalDimensions()[0]; $width = $this->getApplication()->getTerminalDimensions()[0];
$processor = $input->getOption('processor'); $processor = $input->getOption('processor');
if (!empty($processor) && $processor != 'none') { if (!empty($processor) && $processor != 'none') {
$class = "\\Todaymade\\Daux\\Extension\\" . $processor; $class = "\\Todaymade\\Daux\\Extension\\" . $processor;
if (class_exists($class)) { if (class_exists($class)) {
$daux->setProcessor(new $class($daux, $output, $width)); $daux->setProcessor(new $class($daux, $output, $width));
} else if (file_exists($processor)) { } elseif (file_exists($processor)) {
include $processor; include $processor;
} }
} }
// Improve the tree with a processor // Improve the tree with a processor
$daux->getProcessor()->manipulateTree($daux->tree); $daux->getProcessor()->manipulateTree($daux->tree);
switch(strtolower($input->getOption('format'))) { switch (strtolower($input->getOption('format'))) {
case 'confluence': case 'confluence':
(new ConfluenceGenerator())->generate($daux, $output, $width); (new ConfluenceGenerator())->generate($daux, $output, $width);
break; break;

View File

@ -2,15 +2,26 @@
class Helper class Helper
{ {
/**
* Copy all files from $path to $local_base
*
* @param string $path
* @param string $local_base
*/
public static function copyAssets($path, $local_base) public static function copyAssets($path, $local_base)
{ {
@mkdir($path); mkdir($path);
static::rmdir($path); static::rmdir($path);
@mkdir($path . DS . 'resources'); mkdir($path . DS . 'resources');
static::copyRecursive($local_base . DS . 'resources', $path . DS . 'resources'); static::copyRecursive($local_base . DS . 'resources', $path . DS . 'resources');
} }
/**
* Remove a directory recursively
*
* @param string $dir
*/
private static function rmdir($dir) private static function rmdir($dir)
{ {
$it = new \RecursiveDirectoryIterator($dir); $it = new \RecursiveDirectoryIterator($dir);
@ -27,16 +38,22 @@ class Helper
} }
} }
private static function copyRecursive($src, $dst) /**
* Copy files recursively
*
* @param string $source
* @param string $destination
*/
private static function copyRecursive($source, $destination)
{ {
$dir = opendir($src); $dir = opendir($source);
@mkdir($dst); mkdir($destination);
while (false !== ( $file = readdir($dir))) { while (false !== ($file = readdir($dir))) {
if (( $file != '.' ) && ( $file != '..' )) { if ($file != '.' && $file != '..') {
if (is_dir($src . '/' . $file)) { if (is_dir($source . '/' . $file)) {
static::copyRecursive($src . '/' . $file, $dst . '/' . $file); static::copyRecursive($source . '/' . $file, $destination . '/' . $file);
} else { } else {
copy($src . '/' . $file, $dst . '/' . $file); copy($source . '/' . $file, $destination . '/' . $file);
} }
} }
} }

View File

@ -21,6 +21,11 @@ class Processor
*/ */
protected $width; protected $width;
/**
* @param Daux $daux
* @param OutputInterface $output
* @param integer $width
*/
public function __construct(Daux $daux, OutputInterface $output, $width) public function __construct(Daux $daux, OutputInterface $output, $width)
{ {
$this->daux = $daux; $this->daux = $daux;
@ -28,10 +33,24 @@ class Processor
$this->width = $width; $this->width = $width;
} }
/**
* With this connection point, you can transform
* the tree as you want, move pages, modify
* pages and even add new ones.
*
* @param Directory $root
*/
public function manipulateTree(Directory $root) public function manipulateTree(Directory $root)
{ {
} }
/**
* This connection point provides
* a way to extend the Markdown
* parser and renderer.
*
* @param Environment $environment
*/
public function extendCommonMarkEnvironment(Environment $environment) public function extendCommonMarkEnvironment(Environment $environment)
{ {
} }

View File

@ -9,19 +9,32 @@ class ErrorPage extends SimplePage
const MISSING_PAGE_ERROR_TYPE = 'MISSING_PAGE_ERROR'; const MISSING_PAGE_ERROR_TYPE = 'MISSING_PAGE_ERROR';
const FATAL_ERROR_TYPE = 'FATAL_ERROR'; const FATAL_ERROR_TYPE = 'FATAL_ERROR';
/**
* @var \Todaymade\Daux\Config
*/
private $params; private $params;
/**
* @param string $title
* @param string $content
* @param \Todaymade\Daux\Config $params
*/
public function __construct($title, $content, $params) public function __construct($title, $content, $params)
{ {
parent::__construct($title, $content); parent::__construct($title, $content);
$this->params = $params; $this->params = $params;
} }
/**
* @return string
*/
protected function generatePage() protected function generatePage()
{ {
$params = $this->params; $params = $this->params;
$page['title'] = $this->title; $page = [
$page['content'] = $this->content; 'title' => $this->title,
'content' => $this->content,
];
$template = new Template($params['templates'], $params['theme']['templates']); $template = new Template($params['templates'], $params['theme']['templates']);
return $template->render('error', ['page' => $page, 'params' => $params]); return $template->render('error', ['page' => $page, 'params' => $params]);

View File

@ -6,7 +6,6 @@ use Todaymade\Daux\Exception;
use Todaymade\Daux\Format\HTML\MarkdownPage; use Todaymade\Daux\Format\HTML\MarkdownPage;
use Todaymade\Daux\Format\HTML\RawPage; use Todaymade\Daux\Format\HTML\RawPage;
use Todaymade\Daux\Format\HTML\SimplePage; use Todaymade\Daux\Format\HTML\SimplePage;
use Todaymade\Daux\Tree\Directory;
use Todaymade\Daux\Tree\Raw; use Todaymade\Daux\Tree\Raw;
class Server class Server
@ -16,6 +15,11 @@ class Server
private $host; private $host;
private $base_url; private $base_url;
/**
* Serve the documentation
*
* @throws Exception
*/
public static function serve() public static function serve()
{ {
$daux = new Daux(Daux::LIVE_MODE); $daux = new Daux(Daux::LIVE_MODE);
@ -63,6 +67,9 @@ class Server
} }
} }
/**
* @return \Todaymade\Daux\Config
*/
public function getParams() public function getParams()
{ {
$params = $this->daux->getParams(); $params = $this->daux->getParams();
@ -83,6 +90,14 @@ class Server
return $params; return $params;
} }
/**
* Handle an incoming request
*
* @param array $query
* @return \Todaymade\Daux\Tree\Entry
* @throws Exception
* @throws NotFoundException
*/
public function handle($query = []) public function handle($query = [])
{ {
$this->params = $this->getParams(); $this->params = $this->getParams();
@ -108,6 +123,14 @@ class Server
} }
} }
/**
* @param string $request
* @param string $content
* @return SimplePage
*
* @throws Exception
* @throws NotFoundException
*/
private function saveFile($request, $content) private function saveFile($request, $content)
{ {
$file = $this->getFile($request); $file = $this->getFile($request);
@ -123,6 +146,11 @@ class Server
return new SimplePage('Success', 'Successfully Edited'); return new SimplePage('Success', 'Successfully Edited');
} }
/**
* @param string $request
* @return \Todaymade\Daux\Tree\Entry
* @throws NotFoundException
*/
private function getPage($request) private function getPage($request)
{ {
$file = DauxHelper::getFile($this->daux->tree, $request); $file = DauxHelper::getFile($this->daux->tree, $request);

View File

@ -5,6 +5,15 @@ use Todaymade\Daux\DauxHelper;
class Builder class Builder
{ {
/**
* Build the initial tree
*
* @param string $dir
* @param array $ignore
* @param \Todaymade\Daux\Config $params
* @param array $parents
* @return Directory|void
*/
public static function build($dir, $ignore, $params, $parents = null) public static function build($dir, $ignore, $params, $parents = null)
{ {
if (!$dh = opendir($dir)) { if (!$dh = opendir($dir)) {
@ -62,7 +71,13 @@ class Builder
return $node; return $node;
} }
public static function getOrCreateDir($parent, $title) { /**
* @param Entry $parent
* @param String $title
* @return Directory
*/
public static function getOrCreateDir($parent, $title)
{
$slug = DauxHelper::slug($title); $slug = DauxHelper::slug($title);
if (array_key_exists($slug, $parent->value)) { if (array_key_exists($slug, $parent->value)) {
@ -77,7 +92,13 @@ class Builder
return $dir; return $dir;
} }
public static function getOrCreatePage($parents, $title) { /**
* @param array $parents
* @param string $title
* @return Content
*/
public static function getOrCreatePage($parents, $title)
{
$slug = DauxHelper::slug($title); $slug = DauxHelper::slug($title);
$uri = $slug . ".html"; $uri = $slug . ".html";

View File

@ -4,7 +4,10 @@ use Todaymade\Daux\DauxHelper;
class Content extends Entry class Content extends Entry
{ {
protected $content; /**
* @var string
*/
protected $content;
public function __construct($path = '', $parents = array()) public function __construct($path = '', $parents = array())
{ {
@ -13,20 +16,30 @@ class Content extends Entry
$this->value = $this->uri; $this->value = $this->uri;
} }
public function getContent() /**
{ * @return string
if (!$this->content) { */
$this->content = file_get_contents($this->getPath()); public function getContent()
} {
if (!$this->content) {
$this->content = file_get_contents($this->getPath());
}
return $this->content; return $this->content;
} }
public function setContent($content) /**
{ * @param string $content
$this->content = $content; */
} public function setContent($content)
{
$this->content = $content;
}
/**
* @param string $file
* @return string
*/
protected function getFilename($file) protected function getFilename($file)
{ {
return DauxHelper::pathinfo($file)['filename']; return DauxHelper::pathinfo($file)['filename'];

View File

@ -4,53 +4,90 @@ use Todaymade\Daux\DauxHelper;
abstract class Entry abstract class Entry
{ {
/** @var string */
protected $title; protected $title;
/** @var string */
protected $name; protected $name;
/** @var Content */
protected $index_page; protected $index_page;
/** @var Content */
protected $first_page; protected $first_page;
/** @var string */
protected $uri; protected $uri;
/** @var string */
protected $local_path; protected $local_path;
/** @var integer */
protected $last_modified; protected $last_modified;
/** @var array */
protected $parents; protected $parents;
/**
* @param string $path
* @param array $parents
*/
public function __construct($path = '', $parents = array()) public function __construct($path = '', $parents = array())
{ {
$this->setPath($path); $this->setPath($path);
$this->setParents($parents); $this->setParents($parents);
} }
/**
* @return string
*/
public function getName() public function getName()
{ {
return $this->name; return $this->name;
} }
public function setName($name) /**
{ * @param string $name
$this->name = $name; */
} public function setName($name)
{
$this->name = $name;
}
/**
* @return string
*/
public function getUri() public function getUri()
{ {
return $this->uri; return $this->uri;
} }
/**
* @param string $uri
*/
public function setUri($uri) public function setUri($uri)
{ {
$this->uri = $uri; $this->uri = $uri;
} }
/**
* @return Content
*/
public function getIndexPage() public function getIndexPage()
{ {
return $this->index_page; return $this->index_page;
} }
/**
* @param Content $index_page
*/
public function setIndexPage($index_page) public function setIndexPage($index_page)
{ {
$this->index_page = $index_page; $this->index_page = $index_page;
} }
/** /**
* @return Entry * @return Content
*/ */
public function getFirstPage() public function getFirstPage()
{ {
@ -80,38 +117,59 @@ abstract class Entry
return false; return false;
} }
/**
* @param Content $first_page
*/
public function setFirstPage($first_page) public function setFirstPage($first_page)
{ {
$this->first_page = $first_page; $this->first_page = $first_page;
} }
/**
* @return string
*/
public function getTitle() public function getTitle()
{ {
return $this->title; return $this->title;
} }
public function setTitle($title) /**
{ * @param string $title
$this->title = $title; */
} public function setTitle($title)
{
$this->title = $title;
}
/**
* @return array
*/
public function getParents() public function getParents()
{ {
return $this->parents; return $this->parents;
} }
public function setParents($parents) /**
{ * @param array $parents
$this->parents = $parents; */
} public function setParents($parents)
{
$this->parents = $parents;
}
/**
* @return string
*/
public function getPath() public function getPath()
{ {
return $this->local_path; return $this->local_path;
} }
public function setPath($path) /**
{ * @param string $path
*/
public function setPath($path)
{
if (!isset($path) || $path == '' || !file_exists($path)) { if (!isset($path) || $path == '' || !file_exists($path)) {
return; return;
} }
@ -121,8 +179,12 @@ abstract class Entry
$this->title = $this->getTitleInternal($this->name); $this->title = $this->getTitleInternal($this->name);
$this->uri = $this->getUrlInternal($this->getFilename($path)); $this->uri = $this->getUrlInternal($this->getFilename($path));
$this->index_page = false; $this->index_page = false;
} }
/**
* @param string $content
* @return bool
*/
public function write($content) public function write($content)
{ {
if (!is_writable($this->local_path)) { if (!is_writable($this->local_path)) {
@ -133,6 +195,9 @@ abstract class Entry
return true; return true;
} }
/**
* @return string
*/
public function getUrl() public function getUrl()
{ {
$url = ''; $url = '';
@ -143,12 +208,20 @@ abstract class Entry
return $url; return $url;
} }
/**
* @param string $file
* @return string
*/
protected function getFilename($file) protected function getFilename($file)
{ {
$parts = explode('/', $file); $parts = explode('/', $file);
return end($parts); return end($parts);
} }
/**
* @param string $filename
* @return string
*/
protected function getTitleInternal($filename) protected function getTitleInternal($filename)
{ {
$filename = explode('_', $filename); $filename = explode('_', $filename);
@ -164,6 +237,10 @@ abstract class Entry
return $filename; return $filename;
} }
/**
* @param string $filename
* @return string
*/
protected function getUrlInternal($filename) protected function getUrlInternal($filename)
{ {
$filename = explode('_', $filename); $filename = explode('_', $filename);

View File

@ -9,10 +9,10 @@
<?php if ($params['file_editor']) echo '<a href="javascript:;" id="editThis" class="btn">Edit this page</a>'; ?> <?php if ($params['file_editor']) echo '<a href="javascript:;" id="editThis" class="btn">Edit this page</a>'; ?>
</h1> </h1>
<span style="float: left; font-size: 10px; color: gray;"> <span style="float: left; font-size: 10px; color: gray;">
<?php echo date("l, F j, Y", $page['modified_time']);?> <?php echo date("l, F j, Y", $page['modified_time']); ?>
</span> </span>
<span style="float: right; font-size: 10px; color: gray;"> <span style="float: right; font-size: 10px; color: gray;">
<?php echo date("g:i A", $page['modified_time']);?> <?php echo date("g:i A", $page['modified_time']); ?>
</span> </span>
</div> </div>
<?php } else { ?> <?php } else { ?>
@ -28,14 +28,14 @@
<?php echo $page['content']; ?> <?php echo $page['content']; ?>
<?php if ($params['file_editor']) { ?> <?php if ($params['file_editor']) { ?>
<div class="editor<?php if(!$params['date_modified']) echo ' paddingTop'; ?>"> <div class="editor<?php if (!$params['date_modified']) echo ' paddingTop'; ?>">
<h3>You are editing <?php echo $page['path']; ?>&nbsp;<a href="javascript:;" class="closeEditor btn btn-warning">Close</a></h3> <h3>You are editing <?php echo $page['path']; ?>&nbsp;<a href="javascript:;" class="closeEditor btn btn-warning">Close</a></h3>
<div class="navbar navbar-inverse navbar-default navbar-fixed-bottom" role="navigation"> <div class="navbar navbar-inverse navbar-default navbar-fixed-bottom" role="navigation">
<div class="navbar-inner"> <div class="navbar-inner">
<a href="javascript:;" class="save_editor btn btn-primary navbar-btn pull-right">Save file</a> <a href="javascript:;" class="save_editor btn btn-primary navbar-btn pull-right">Save file</a>
</div> </div>
</div> </div>
<textarea id="markdown_editor"><?php echo $page['markdown'];?></textarea> <textarea id="markdown_editor"><?php echo $page['markdown']; ?></textarea>
<div class="clearfix"></div> <div class="clearfix"></div>
</div> </div>
<?php } ?> <?php } ?>